📚 Tài liệu REST API

Tách nền ảnh bằng AI ngay trong ứng dụng của bạn. Xác thực bằng API key, không cần SDK — mọi ngôn ngữ có HTTP client đều dùng được.

Swagger UI tương tác: /docs · OpenAPI JSON: /openapi.json

Bắt đầu nhanh

  1. Đăng ký tài khoản tại Dashboard — hệ thống cấp ngay 1 API key (gói Free, 50 credits).
  2. Copy API key (dạng rbg_...) — key chỉ hiển thị một lần, hãy lưu ngay.
  3. Gửi ảnh tới endpoint POST /v1/remove-background với header X-API-Key.
Base URL:
  • Production: http://localhost:8000/v1 (thay bằng domain thật khi deploy)
  • Môi trường dev: http://localhost:8000/v1

Xác thực

Mọi request tới /v1/* đều yêu cầu header X-API-Key:

curl "http://localhost:8000/v1/account/credits" \
  -H "X-API-Key: rbg_your_api_key_here"
import requests

headers = {"X-API-Key": "rbg_your_api_key_here"}
response = requests.get("http://localhost:8000/v1/account/credits", headers=headers)
print(response.json())

Key được lưu trong DB dạng SHA256 hash — nếu làm mất, hãy thu hồi key cũ và tạo key mới trong Dashboard.

Phân quyền theo scope: khi tạo key trong Dashboard có thể chọn chỉ cho phép một nhóm tính năng — removebg (tách nền, gồm batch & async), watermark (xóa watermark), upscale (tăng độ phân giải), tools (ảnh thẻ, đổi màu, scan tài liệu, bảng màu). Key không có quyền sẽ nhận mã 403. Key cũ (trước 10/2026) hoặc bỏ chọn hết = mọi quyền.

Gói dịch vụ & giới hạn

GóiRequests / thángRequests / phút
Free50 credits5
Pro5.000 credits60
EnterpriseUnlimitedUnlimited

Mỗi lần tách nền thành công trừ 1 credit. Khi hết credit, API trả về mã 402.

POST /v1/remove-background

Tách nền từ file ảnh upload. Body dạng multipart/form-data.

Tham số

Tham sốBắt buộcMặc địnhMô tả
image✓—File ảnh: JPG, PNG, WEBP — tối đa 10MB
return_format—pngpng | webp (nhẹ hơn, giữ alpha) | jpg | base64
size—autoauto (gốc) | full (gốc) | preview (~0.25MP)
bg_color—trong suốtMàu nền thay thế, vd #ffffff, red, rgb(59,130,246)
model—autohigh (ISNet, viền sạch) | ultra (BiRefNet, sắc nét nhất) | portrait (ảnh người) | anime | fast | tên model rembg vd isnet-general-use
alpha_matting—theo servertrue = viền mềm hơn với tóc, lông (xử lý chậm hơn)
effect—noneshadow (đổ bóng dưới sản phẩm) | outline (viền sticker) | both
outline_width / outline_color—12 / #ffffffĐộ dày (1-100 px) và màu viền sticker
shadow_opacity—0.35Độ đậm bóng đổ 0..1
bg_image——File ảnh nền tùy chỉnh (JPG/PNG/WEBP) — ưu tiên hơn bg_color
canvas—nonesquare = khung 1:1 chuẩn sàn TMĐT (crop sát sản phẩm + đệm + đặt giữa)
canvas_size / padding_percent—800 / 8Kích thước canvas (200-4000 px) và khoảng đệm (0-30%)

Ví dụ

curl -X POST "http://localhost:8000/v1/remove-background" \
  -H "X-API-Key: rbg_your_api_key_here" \
  -F "image=@photo.jpg" \
  -F "return_format=png" \
  -F "size=auto" \
  -F "model=high" \
  -F "alpha_matting=true"
import requests

url = "http://localhost:8000/v1/remove-background"
headers = {"X-API-Key": "rbg_your_api_key_here"}
files = {"image": open("photo.jpg", "rb")}
data = {"return_format": "png", "size": "auto"}

response = requests.post(url, headers=headers, files=files, data=data)
result = response.json()
print(result["data"]["image_url"])
const form = new FormData();
form.append("image", fileInput.files[0]);
form.append("return_format", "png");

const res = await fetch("http://localhost:8000/v1/remove-background", {
  method: "POST",
  headers: { "X-API-Key": "rbg_your_api_key_here" },
  body: form,
});
const result = await res.json();
console.log(result.data.image_url);
<?php
$ch = curl_init('http://localhost:8000/v1/remove-background');
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => ['X-API-Key: rbg_your_api_key_here'],
    CURLOPT_POSTFIELDS     => [
        'image'         => new CURLFile('photo.jpg'),
        'return_format' => 'png',
    ],
]);
echo curl_exec($ch);

Response 200

{
  "success": true,
  "data": {
    "image_url": "http://localhost:8000/results/9f2c7a4e....png",
    "base64": null,
    "credits_used": 1,
    "credits_remaining": 99,
    "processing_time": "1.2s",
    "image_size": "1920x1080"
  },
  "message": "Background removed successfully"
}

Với return_format=base64, trường base64 chứa dữ liệu ảnh mã hóa base64 (kèm image_url như thường).

POST /v1/remove-background-url

Tách nền từ URL ảnh công khai. Body dạng JSON.

curl -X POST "http://localhost:8000/v1/remove-background-url" \
  -H "X-API-Key: rbg_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{"image_url": "https://example.com/photo.jpg", "size": "auto", "model": "high", "alpha_matting": true}'
import requests

url = "http://localhost:8000/v1/remove-background-url"
headers = {
    "X-API-Key": "rbg_your_api_key_here",
    "Content-Type": "application/json",
}
payload = {"image_url": "https://example.com/photo.jpg"}

response = requests.post(url, headers=headers, json=payload)
print(response.json())

Response 200

{
  "success": true,
  "data": {
    "image_url": "http://localhost:8000/results/3ab19d0e....png",
    "base64": null,
    "credits_used": 1,
    "credits_remaining": 98,
    "processing_time": "1.4s",
    "image_size": "1600x1200"
  },
  "message": "Background removed successfully"
}

Server chặn URL trỏ tới địa chỉ nội bộ/private (SSRF) và ảnh lớn hơn 10MB.

POST /v1/batch/remove-background

Tách nền nhiều ảnh (tối đa 10 ảnh) trong 1 request. Tham số như /v1/remove-background, áp dụng chung cho mọi ảnh. Mỗi ảnh thành công trừ 1 credit; ảnh lỗi trả success: false kèm error, không trừ credit. Rate limit đếm theo request (1 batch = 1 lượt).

Tham số (multipart/form-data)

Tham sốBắt buộcMặc địnhMô tả
images✓—1–10 file ảnh: JPG, PNG, WEBP — mỗi file tối đa 10MB
return_format—pngpng | webp | jpg | base64
size—autoauto | full | preview
bg_color—trong suốtMàu nền thay thế, vd #ffffff
model—autoGiống /v1/remove-background
alpha_matting—theo servertrue = viền mềm hơn

Ví dụ

curl -X POST "http://localhost:8000/v1/batch/remove-background" \
  -H "X-API-Key: rbg_your_api_key_here" \
  -F "images=@photo1.jpg" \
  -F "images=@photo2.jpg" \
  -F "return_format=png"

Response 200

{
  "success": true,
  "data": {
    "results": [
      {
        "original_name": "photo1.jpg",
        "success": true,
        "image_url": "http://localhost:8000/results/1ab19d0e....png",
        "image_size": "1600x1200",
        "processing_time": "1.4s",
        "cached": false
      },
      {
        "original_name": "photo2.jpg",
        "success": false,
        "error": "Tệp không phải ảnh hợp lệ hoặc đã hỏng"
      }
    ],
    "total": 2,
    "success_count": 1,
    "credits_used": 1,
    "total_time": "1.4s"
  },
  "message": "Batch finished: 1/2 ảnh thành công"
}

Nếu cả batch đều lỗi sẽ trả mã 400. Ảnh trùng lặp (cùng nội dung + tham số) trong batch dùng lại kết quả của nhau — chỉ tính 1 lần xử lý.

POST /v1/async/remove-background

Tách nền bất đồng bộ: server trả task_id ngay (HTTP 202), không giữ kết nối đến khi xử lý xong — phù hợp ảnh lớn hoặc khi client không chờ được. Tham số giống /v1/remove-background (gồm hiệu ứng effect, bg_image, canvas…) cộng thêm webhook_url. Credit trừ khi xử lý thành công.

Enqueue

curl -X POST "http://localhost:8000/v1/async/remove-background" \
  -H "X-API-Key: rbg_your_api_key_here" \
  -F "image=@photo.jpg" \
  -F "effect=shadow" \
  -F "webhook_url=https://your-app.com/hooks/removebg"
{
  "success": true,
  "data": {
    "task_id": "9f2c7a4ee4b14...",
    "status": "pending",
    "status_url": "/v1/async/status/9f2c7a4ee4b14..."
  },
  "message": "Đã nhận job — poll status hoặc đợi webhook"
}

webhook_url phải là URL http(s) công khai (địa chỉ nội bộ/private bị chặn). Khi job xong, server POST JSON: {task_id, status, event: "job.finished", image_url, error?}. Webhook lỗi không ảnh hưởng job — vẫn poll được status.

GET /v1/async/status/{task_id}

Poll trạng thái. Chỉ API key tạo job mới xem được (key khác nhận 404).

{
  "success": true,
  "data": {
    "task_id": "9f2c7a4ee4b14...",
    "status": "success",
    "image_url": "http://localhost:8000/results/...png",
    "image_size": "1600x1200",
    "processing_time": "1.4s",
    "credits_remaining": 98,
    "cached": false
  }
}

Trạng thái: pending → processing → success | error (kèm error).

Công cụ xử lý ảnh mới

4 endpoint thuộc scope tools, mỗi lần tạo ảnh thành công trừ 1 credit (trừ /v1/palette — chỉ phân tích, miễn phí credit).

POST /v1/id-photo — Tạo ảnh thẻ chuẩn

Nhận diện khuôn mặt tự động (model YuNet ~230KB, server tự tải lần đầu), tách nền bằng AI, căn đầu chiếm ~72% chiều cao theo chuẩn ảnh thẻ. Tham số: image, ratio (3x4 | 4x6), bg_color (mặc định #ffffff), output_height (px, 400-3000), return_format (jpg | png | base64).

POST /v1/recolor — Đổi màu vật thể

Đổi màu vùng chọn sang màu bất kỳ nhưng giữ nguyên nếp gấp, độ bóng (kênh độ sáng không đổi). Tham số: image, color (hex), strength (0..1), mask (tùy chọn — PNG trắng = vùng đổi; bỏ trống = đổi cả chủ thể bằng rembg), return_format (png | jpg | webp | base64).

POST /v1/scan-document — Scan tài liệu

Tự nhận diện tứ giác tờ giấy, cắt thẳng (warp perspective), làm rõ chữ. Tham số: image, mode (enhance màu cân sáng | gray | bw đen trắng làm rõ chữ), auto_crop (true/false), return_format. Response có thêm engine ghi rõ cropped=true/false.

POST /v1/palette — Bảng màu chủ đạo

curl -X POST "http://localhost:8000/v1/palette" \
  -H "X-API-Key: rbg_your_api_key_here" \
  -F "image=@photo.jpg" -F "k=6"
{
  "success": true,
  "data": {
    "colors": [
      { "hex": "#3b5998", "rgb": [59, 89, 152], "share": 0.41 },
      { "hex": "#f2f2f2", "rgb": [242, 242, 242], "share": 0.23 }
    ],
    "count": 6
  }
}

Không tạo file ảnh kết quả — chỉ trả mã HEX + tỉ lệ diện tích, không trừ credit.

POST /v1/ocr

Nhận diện chữ trong ảnh (OCR) bằng Tesseract OCR v5 — engine LSTM, hỗ trợ tốt tiếng Việt có dấu. Trả về toàn văn giữ nguyên cấu trúc dòng/đoạn kèm tọa độ từng dòng chữ trong ảnh gốc (dùng để vẽ khung demo vị trí). Có trang Web UI tại /ocr — kéo cả thư mục, dán Ctrl+V, xem vị trí chữ và copy nhanh.

Tham số (multipart/form-data)

Tham sốBắt buộcMô tả
image✔Ảnh chứa chữ: ảnh chụp, ảnh scan, ảnh màn hình — JPG, PNG, WEBP, tối đa 10MB
languagesBộ ngôn ngữ nối bằng +. Rỗng = mặc định server vie+eng. Ngôn ngữ khác cần file *.traineddata trong thư mục tessdata
psmChế độ phân trang Tesseract: 3 tự động (mặc định) | 4 cột chữ | 6 khối chữ đều | 7 dòng đơn | 11 chữ rải rác
curl -X POST "http://localhost:8000/v1/ocr" \
  -H "X-API-Key: rbg_your_api_key_here" \
  -F "image=@tailieu.jpg" \
  -F "languages=vie+eng"
import requests

url = "http://localhost:8000/v1/ocr"
headers = {"X-API-Key": "rbg_your_api_key_here"}

with open("tailieu.jpg", "rb") as fh:
    response = requests.post(url, headers=headers,
                             files={"image": fh},
                             data={"languages": "vie+eng"})
result = response.json()["data"]
print(result["text"])          # toàn văn bản
for line in result["lines"]:   # vị trí từng dòng trong ảnh gốc
    print(line["box"], line["text"])

Response 200

{
  "success": true,
  "data": {
    "text": "Xin chào Việt Nam!\n\nHộp thư 123 đường Nguyễn Trãi",
    "lines": [
      {
        "text": "Xin chào Việt Nam!",
        "box": [40, 47, 304, 31],
        "confidence": 95.8,
        "words": [{"text": "Xin", "box": [40, 47, 50, 26], "confidence": 96.0}]
      }
    ],
    "width": 900, "height": 300,
    "line_count": 2, "word_count": 8,
    "avg_confidence": 94.5,
    "languages": "vie+eng",
    "engine": "tesseract-5.4.0",
    "processing_time": 0.62,
    "credits_used": 1,
    "credits_remaining": 97
  },
  "message": "OK"
}

Thuộc scope ocr (key cũ không chọn scope vẫn gọi được). Mỗi ảnh thành công trừ 1 credit. box là [x, y, width, height] tính theo pixel ảnh gốc. Server cần cài Tesseract 5 (hoặc chép bản portable vào thư mục tesseract/ cạnh app); thiếu sẽ trả mã 503 kèm hướng dẫn.

POST /v1/remove-watermark

Xóa watermark (logo, chữ, stamp) khỏi ảnh bằng AI inpainting. Gửi ảnh gốc kèm mask PNG cùng kích thước ảnh — vùng trắng = xóa, đen = giữ nguyên. Model LaMa sẽ vá lại vùng đó từ nội dung xung quanh.

Tham số (multipart/form-data)

Tham sốBắt buộcMô tả
image✔File ảnh gốc: JPG, PNG hoặc WEBP — tối đa 10MB
mask✔Mask PNG cùng kích thước ảnh (hoặc sẽ được tự resize) — trắng = vùng xóa
return_formatpng (mặc định) | jpg | base64
engineauto (mặc định — LaMa, lỗi fallback OpenCV) | lama | migan (nhanh ~5-10 lần, dấu nhỏ) | opencv
curl -X POST "http://localhost:8000/v1/remove-watermark" \
  -H "X-API-Key: rbg_your_api_key_here" \
  -F "image=@photo.jpg" \
  -F "mask=@mask.png" \
  -F "engine=auto"
import requests

url = "http://localhost:8000/v1/remove-watermark"
headers = {"X-API-Key": "rbg_your_api_key_here"}
files = {
    "image": open("photo.jpg", "rb"),
    "mask": open("mask.png", "rb"),  # trắng = vùng xóa, đen = giữ nguyên
}
data = {"engine": "auto"}

response = requests.post(url, headers=headers, files=files, data=data)
print(response.json())

Response 200

{
  "success": true,
  "data": {
    "image_url": "http://localhost:8000/results/7c21c9ae....png",
    "base64": null,
    "credits_used": 1,
    "credits_remaining": 97,
    "processing_time": "3.2s",
    "image_size": "1600x1200",
    "engine": "lama"
  },
  "message": "Watermark removed successfully"
}

engine=opencv (cv2.inpaint TELEA) nhanh hơn nhiều nhưng chỉ nên dùng cho vùng nhỏ trên nền phẳng; lama cho kết quả mượt với vùng lớn — lần gọi đầu có thể chậm nếu model chưa được nạp sẵn. Lỗi mask trống / không khớp ảnh trả về mã 400.

POST /v1/upscale

Làm nét + tăng độ phân giải ảnh bằng AI super-resolution (Real-ESRGAN). Phóng to gấp 2× hoặc 4× theo cạnh, khôi phục chi tiết mờ/nhòe. Có trang Web UI tại /upscale kèm xem trước so sánh trước / sau.

Tham số (multipart/form-data)

Tham sốBắt buộcMô tả
image✔File ảnh gốc: JPG, PNG hoặc WEBP — tối đa 10MB. Ảnh PNG nền trong suốt được giữ nguyên alpha
scale2 | 4 (mặc định) — phóng to gấp mấy theo cạnh
engineauto (mặc định — General, lỗi fallback basic) | general (Real-ESRGAN gọn ~5MB, nhanh) | pro (RealESRGAN_x4plus ~64MB, nét nhất, chậm) | basic (LANCZOS + unsharp, không AI)
sharpenCường độ làm nét thêm sau khi upscale, 0–1.5 (mặc định 0.2; 0 = tắt)
return_formatpng (mặc định) | jpg | base64
curl -X POST "http://localhost:8000/v1/upscale" \
  -H "X-API-Key: rbg_your_api_key_here" \
  -F "image=@small_photo.jpg" \
  -F "scale=4" \
  -F "engine=auto"
import requests

url = "http://localhost:8000/v1/upscale"
headers = {"X-API-Key": "rbg_your_api_key_here"}
files = {"image": open("small_photo.jpg", "rb")}
data = {"scale": 4, "engine": "general", "sharpen": 0.2}

response = requests.post(url, headers=headers, files=files, data=data)
print(response.json())

Response 200

{
  "success": true,
  "data": {
    "image_url": "http://localhost:8000/results/3f8a91c2....png",
    "base64": null,
    "credits_used": 1,
    "credits_remaining": 96,
    "processing_time": "12.4s",
    "image_size": "2000x1500",
    "engine": "general",
    "scale": "4x"
  },
  "message": "Image upscaled successfully"
}

Ảnh phóng scale× không được vượt quá giới hạn pixel đầu ra của server (UPSCALE_MAX_OUTPUT_PIXELS, mặc định 24MP) — vượt trả về 400. Trên máy chỉ có CPU, engine pro có thể mất vài phút với ảnh lớn.

GET /v1/account/credits

Kiểm tra số credits còn lại của API key.

curl "http://localhost:8000/v1/account/credits" \
  -H "X-API-Key: rbg_your_api_key_here"

Response 200

{
  "success": true,
  "data": {
    "total_credits": 100,
    "used_credits": 25,
    "remaining_credits": 75,
    "plan": "free"
  },
  "message": "OK"
}

GET /v1/account/usage

Lịch sử sử dụng API của key, hỗ trợ phân trang và lọc theo ngày.

Query paramMặc địnhMô tả
page1Số trang
limit20Số dòng mỗi trang (1–100)
date_from—YYYY-MM-DD
date_to—YYYY-MM-DD
curl "http://localhost:8000/v1/account/usage?page=1&limit=20&date_from=2026-01-01" \
  -H "X-API-Key: rbg_your_api_key_here"

Response 200

{
  "success": true,
  "data": {
    "usage": [
      {
        "id": "req_9f2c7a4e5b1d4c3a8e7f2b1d0a9c8e7f",
        "endpoint": "/v1/remove-background",
        "timestamp": "2026-01-15T10:30:00Z",
        "credits_used": 1,
        "image_size": "1920x1080",
        "status": "success",
        "processing_time": 1.21
      }
    ],
    "total": 25,
    "page": 1,
    "limit": 20
  },
  "message": "OK"
}

Mã lỗi

MãÝ nghĩaNguyên nhân thường gặp
400Bad requestSai định dạng ảnh, URL không tải được, tham số không hợp lệ
401UnauthorizedThiếu header X-API-Key, key sai hoặc đã thu hồi
402Out of creditsKey đã hết credits — nâng cấp gói hoặc tạo key mới
413Payload too largeẢnh vượt giới hạn 10MB
422Validation errorThiếu tham số bắt buộc, sai kiểu dữ liệu
429Rate limit exceededVượt số request/phút của gói — xem header Retry-After
500Server errorLỗi xử lý phía server — thử lại sau

Dạng lỗi chung

{ "success": false, "error": "Invalid API key" }

Lưu ý quan trọng