RemBG Background Removal API – Документация для разработчиков и руководство по интеграции
Изучите весь API — выполняйте реальные запросы в браузере
Просмотрите все конечные точки, параметры и ответы. Попробуйте выполнить запросы с помощью ключа API, а затем в любое время получите необработанную спецификацию в /api/openapi.
Запустить интерактивный справочникУстановка rembg.js
npm i @remove-background-ai/rembg.js
API Reference for rembg.js
@remove-background-ai/rembg.js is a zero-config Node.js wrapper for the free Rembg API, enabling background removal with simple, customizable parameters.
Parameters for RemBG.js
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| apiKey | string | Required | – | Your Rembg API key |
| inputImage | string | Buffer | { base64: string } | Required | – | Image file, buffer, or base64 payload |
| onDownloadProgress | (event) => void | Optional | – | Hook for upload progress events |
| onUploadProgress | (event) => void | Optional | – | Hook for download progress events |
| options.format | webp (default) | png | Optional | webp | Specifies the output image format. Either "webp" (default) or "png" |
| options.returnBase64 | boolean | Optional | false | Return Base64 string instead of file |
| options.returnMask | boolean | Optional | false | Return only the alpha mask |
| options.w | number | Optional | – | Target width (maintains aspect ratio) |
| options.h | number | Optional | – | Target height (maintains aspect ratio) |
| options.exact_resize | boolean | Optional | false | Force exact width × height (may distort) |
| options.angle | number | Optional | 0 | Rotation angle in degrees |
| options.expand | boolean | Optional | true | Add padding so rotated images aren’t cropped |
| options.bg_color | string | Optional | - | Optional solid background color in hex (e.g. #FFFFFFFF) or named color (e.g. "red", "blue") |
Настройка среды: Убедитесь, что в корне вашего проекта есть файл .env, содержащий ваш ключ API.
Импорт необходимых модулей: Начните с импорта функции rembg из @remove-background-ai/rembg.js и модуля dotenv для обработки переменных среды.
Настройка обратных вызовов прогресса: Библиотека предлагает обратные вызовы onDownloadProgress и onUploadProgress для отслеживания хода файловых операций. В приведенном примере мы регистрируем эти события непосредственно в консоли.
Теперь давайте подробнее рассмотрим пример использования:
// script.mjs file
import { rembg } from '@remove-background-ai/rembg.js';
import dotenv from 'dotenv';
// Load environment variables from .env file
dotenv.config();
// API_KEY will be loaded from the .env file
const API_KEY = process.env.API_KEY;
// log upload and download progress
const onDownloadProgress = console.log;
const onUploadProgress = console.log;
rembg({
apiKey: API_KEY,
inputImage: './input.png', //inputImage can be one of these: string | Buffer | { base64: string };
onDownloadProgress,
onUploadProgress
}).then(({ outputImagePath, cleanup }) => {
console.log('✅🎉 background removed and saved under path=', outputImagePath);
// if called, it will cleanup (remove from disk) your removed background image
// cleanup();
});
Помните, функцию очистки можно вызвать, если вы хотите удалить обработанное изображение с диска после удаления фона.
Показан индикатор выполнения
При интеграции службы фонового удаления часто бывает полезно предоставить пользователям обратную связь о ходе выполнения их запроса на загрузку или скачивание. Чтобы облегчить это, вы можете определить свои собственные обратные вызовы onDownloadProgress и onUploadProgress. Оба этих обратных вызова принимают AxiosProgressEvent в качестве параметра события. По мере обработки запроса эти обратные вызовы вызываются несколько раз, что позволяет, например, отображать индикатор выполнения и регулировать его длину в зависимости от прогресса.
(base) root@DESKTOP-C0Q8KK7:~/rembg.js-test# node index.mjs
{
loaded: 65687,
total: 68474,
progress: 0.9592984198381868, <---- @95% progress
bytes: 65687,
rate: undefined,
estimated: undefined,
upload: true <---- upload progress
}
{
loaded: 68474,
total: 68474,
progress: 1, <---- @100% progress
bytes: 2787,
rate: undefined,
estimated: undefined,
upload: true <---- upload progress
}
{
loaded: 1002,
total: 68824,
progress: 0.014558874811112402, <---- @1% progress
bytes: 1002,
rate: undefined,
estimated: undefined,
download: true <---- download progress
}
{
loaded: 68824,
total: 68824,
progress: 1, <---- @100% progress
bytes: 67822,
rate: undefined,
estimated: undefined,
download: true <---- download progress
}
✅🎉 background removed and saved under path=/tmp/rembg--3339-DBqqeJ2eOs4D-.png
Curl
# Full example: upload an image and remove its background with all optional parameters curl -X POST "https://api.rembg.com/rmbg" -H "x-api-key: YOUR_API_KEY_HERE" # your personal API key -F "image=@/path/to/image.jpg" # input image file -F "format=webp" # output format: webp (default) or png -F "w=800" # target width in pixels (maintains aspect ratio unless exact_resize=true) -F "h=600" # target height in pixels -F "exact_resize=false" # true = force exact w × h, may distort -F "mask=false" # true = return only the alpha mask instead of full image -F "bg_color=#ffffffff" # optional solid background color (RGBA hex) -F "angle=0" # rotate the image by given degrees after processing -F "expand=true" # add padding so rotated images don’t get cropped
HTTP
POST /rmbg HTTP/1.1
Host: api.rembg.com
x-api-key: YOUR_API_KEY_HERE
Content-Type: multipart/form-data; boundary=----BOUNDARY
------BOUNDARY
Content-Disposition: form-data; name="image"; filename="image.jpg"
Content-Type: image/jpeg
<binary data of your image goes here>
------BOUNDARY
Content-Disposition: form-data; name="format"
webp
------BOUNDARY
Content-Disposition: form-data; name="w"
800
------BOUNDARY
Content-Disposition: form-data; name="h"
600
------BOUNDARY
Content-Disposition: form-data; name="exact_resize"
false
------BOUNDARY
Content-Disposition: form-data; name="mask"
false
------BOUNDARY
Content-Disposition: form-data; name="bg_color"
#ffffffff
------BOUNDARY
Content-Disposition: form-data; name="angle"
0
------BOUNDARY
Content-Disposition: form-data; name="expand"
true
------BOUNDARY--
Python Requests
import requests
# Endpoint URL for the background-removal API
url = "https://api.rembg.com/rmbg"
# Required API key header
headers = {
"x-api-key": "YOUR_API_KEY_HERE"
}
# The image file to process (opened in binary mode)
files = {
"image": open("/path/to/image.jpg", "rb")
}
# Optional form fields supported by your backend.
# Adjust values as needed; any of these can be omitted.
data = {
"format": "webp", # Output format: "webp" (default) or "png"
"w": 800, # Target width (maintains aspect ratio unless exact_resize is true)
"h": 600, # Target height
"exact_resize": "false", # "true" forces exact w×h, may distort
"mask": "false", # "true" returns only the alpha mask
"bg_color": "#ffffffff", # Optional solid background color (RGBA hex)
"angle": 0, # Rotation angle in degrees
"expand": "true", # Add padding so rotated images aren’t cropped
}
# Send the POST request with headers, file, and extra form data
response = requests.post(url, headers=headers, files=files, data=data)
# Handle the response
if response.status_code == 200:
# Save the processed image to disk
with open("output.webp", "wb") as f:
f.write(response.content)
print("Background removed successfully → saved as output.webp")
else:
# Print error details if the request failed
print("Error:", response.status_code, response.text)
Членство и использование кредитов
Возвращает метку вашего плана, включенные и предоплаченные кредитные балансы, а также данные об использовании. Вы можете выполнить запрос по календарному месяцу UTC (устаревшая версия), по периоду выставления счетов, соответствующему Stripe (для мониторинга посредством продления), или перечислить известные периоды выставления счетов. Аутентифицируйтесь только с помощью ключа API.
Схемы, примеры и тестовую консоль см. в той же конечной точке в полной ссылке: Открыть документацию по API
Конечная точка
GET https://www.rembg.com/api/membership-usageАутентификация
Отправьте свой ключ API: заголовок x-api-key: YOUR_API_KEY_HERE (создавайте ключи и управляйте ими в своем профиле на rembg.com).
Параметры запроса
| Параметр | Введите | Описание |
|---|---|---|
| year | number | Календарный год (1–9999). В месяце читает ключи Redis user:{uid}:app_usage:{year}:{month}. Если этот параметр опущен (и periodStartUnix не используется), по умолчанию используется текущий год в формате UTC. |
| month | number (1–12) | Календарный месяц 1–12 (для ключей используется формат UTC). Если этот параметр опущен, по умолчанию используется текущий месяц UTC. |
| periodStartUnix | number | Временная метка Unix в секундах: начало окна выставления счетов. Читает user:{uid}:app_usage:cycle:{ periodStartUnix} и api_usage:cycle:…. Невозможно объединить с годом или месяцем. |
| expand | string | Флаги, разделенные запятыми. Включите billing_cycle, чтобы добавить объект billingCycle: текущий период Stripe, если billing_ period_* существует в Redis, в противном случае — текущий календарный месяц в формате UTC. Также работает с periodStartUnix для конкретного окна. |
| includeBillingCycle | 1 / true | То же, что и расширение, содержащее billing_cycle: установите значение 1 или true, чтобы включить объект billingCycle. |
| listBillingCycles | 1 / true | Выделенный режим: listBillingCycles=1 или true возвращает только { billingCycles: [...] }. Сканирует Redis на предмет ключей цикла для этого пользователя; другие параметры запроса игнорируются в этом запросе. |
Не передавайте periodStartUnix вместе с годом или месяцем — API возвращает 400. Режим listBillingCycles является отдельным и игнорирует другие параметры.
Перечислите расчетные периоды
Используйте это для заполнения раскрывающегося списка прошлых и текущих окон подписки (каждая запись представляет собой periodStartUnix, который вы можете передать обратно с помощью periodStartUnix=…). Определяется время окончания периода (начало следующего периода — 1 или полоса current_ period_end для активного периода).
curl --location 'https://www.rembg.com/api/membership-usage?listBillingCycles=1' \ --header 'x-api-key: YOUR_API_KEY_HERE'
Пример ответа
{
"billingCycles": [
{
"periodStartUnix": 1774268612,
"periodEndUnix": 1776947012,
"appUsage": 120,
"apiUsage": 880
}
]
}Сначала сортируется самый новый период. Период появляется, если есть ключ использования цикла или если это текущий billing_ period_start из веб-перехватчиков Stripe.
Объект billingCycle
Присутствует, когда расширение включает в себя billing_cycle или includeBillingCycle. Используйте его для информационных панелей: граница продления, использование в окне и оставшиеся включенные кредиты.
| Поле | Описание |
|---|---|
| periodStartUnix | Начало окна биллинга (unix секунды). Соответствует Stripe current_ period_start при синхронизации учетной записи. |
| periodEndUnix | Конец текущего окна (в unix-секундах), т. е. непосредственно перед следующим обновлением — Stripe current_ period_end при синхронизации. Не совпадает с датой отмены подписки. |
| appUsage / apiUsage | В этом окне учитывается использование включенных кредитов: веб-редактор (приложение) и ключ API (API). UsedIncludedCredits равен их сумме. |
| includedCredits | Включенный (плановый) кредитный лимит, хранящийся в Redis (та же идея, что и кредиты верхнего уровня). |
| prepaidCredits | Предоплаченный (покупной) остаток; не сбрасывает каждый расчетный период. |
| usedIncludedCredits | Общее количество включенного использования в окне (приложение + API). Предоплаченное потребление сюда не добавляется. |
| remainingIncludedCredits | max(0, includeCredits − UsedIncludedCredits) для этого снимка. |
| stripeBillingSynced | true, если Redis имеет billing_ period_start/end из Stripe, поэтому окно соответствует вашей подписке; false означает, что для этого блока API вернулся к календарному месяцу UTC. |
Пока веб-перехватчики Stripe не записали периоды выставления счетов для пользователя, значение StripeBillingSynced может быть ложным, а окно billingCycle соответствует календарному месяцу UTC. После синхронизации ограничения на использование API изображений совпадают с теми же ключами цикла.
Чтобы узнать «кредиты, использованные до следующего продления», вызовите с помощью методаexpand=billing_cycle и используйте billingCycle. periodEndUnix в качестве границы продления, billingCycle.usedIncludedCredits (или appUsage + apiUsage) и billingCycle.remainingIncludedCredits. Добавьте prepaidCredits, если вам нужен общий располагаемый баланс.
Примеры (cURL)
Использование для определенного календарного месяца UTC
curl --location 'https://www.rembg.com/api/membership-usage?year=2026&month=3' \ --header 'x-api-key: YOUR_API_KEY_HERE'
Текущий платежный цикл + полная блокировка BillingCycle (согласно обновлению при синхронизации)
# Current subscription window + usage (renewal-aligned when Stripe is synced) curl --location 'https://www.rembg.com/api/membership-usage?expand=billing_cycle' \ --header 'x-api-key: YOUR_API_KEY_HERE'
Одно историческое окно выставления счетов по началу периода (из listBillingCycles или Stripe)
# Specific billing period by Stripe period start (unix seconds) curl --location 'https://www.rembg.com/api/membership-usage?periodStartUnix=1774268612&expand=billing_cycle' \ --header 'x-api-key: YOUR_API_KEY_HERE'
Пример JSON (с платежным циклом)
App_usage и api_usage верхнего уровня всегда отражают либо запрошенный календарный месяц, либо, если установлен periodStartUnix, счетчики этого цикла. Если параметр «expand=billing_cycle» опущен, «billingCycle» отсутствует.
{
"membership": "Premium-20000",
"credits": 18500,
"prepaidCredits": 2000,
"app_usage": 8500,
"api_usage": 10000,
"billingCycle": {
"periodStartUnix": 1740441600,
"periodEndUnix": 1743033599,
"appUsage": 4200,
"apiUsage": 5100,
"includedCredits": 18500,
"prepaidCredits": 2000,
"usedIncludedCredits": 9300,
"remainingIncludedCredits": 9200,
"stripeBillingSynced": true
}
}Если для полосы StripeBillingSynced установлено значение true, billingCycle соответствует принудительному применению API фонового удаления. Если значение равно false, используйте поля календарного месяца или подождите, пока веб-перехватчики заполнят billing_ period_* в Redis.
Error Responses
All error responses return a JSON body with a status field matching the HTTP status code.
Multiple Validation Errors Response
HTTP/1.1 400 Bad Request
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": "Multiple validation errors",
"details": [
{ "field": "w", "message": "'w' must be an integer, got: 'abc'" },
{ "field": "angle", "message": "'angle' must be between -360 and 360 degrees, got: 500.0" }
],
"status": 400
}Error Reference
| Scenario | Status | Error Message |
|---|---|---|
| No image provided | 400 | No image file provided. Please include an 'image' field in your form data. |
| No file selected | 400 | No file selected. Please choose an image file to upload. |
| Unsupported file type | 400 | File type '.exe' is not supported. Allowed formats: webp, bmp, png, jpg, jpeg |
| Corrupt image | 400 | File does not appear to be a valid image (invalid file signature) |
| Empty file (0 bytes) | 400 | Uploaded file is empty (0 bytes). |
| File too large | 400 | File size (55.2 MB) exceeds the maximum allowed size of 50 MB. |
| Image too wide | 400 | Image width (12000px) exceeds the maximum allowed width of 10000px. |
| Image too tall | 400 | Image height (15000px) exceeds the maximum allowed height of 10000px. |
| Bad w or h value | 400 | 'w' must be an integer, got: 'abc' |
| w or h out of range | 400 | 'w' must be at least 1, got: -5 |
| w or h above max | 400 | 'w' must be at most 10000, got: 15000 |
| Bad angle | 400 | 'angle' must be a number, got: 'ninety' |
| Angle out of range | 400 | 'angle' must be between -360 and 360 degrees, got: 500.0 |
| Bad output format | 400 | Invalid format 'gif'. Allowed formats: PNG, JPEG, WEBP, BMP |
| Bad bg_color | 400 | Invalid color format '#12345'. Use hex format: #RGB, #RGBA, #RRGGBB, or #RRGGBBAA |
| mask + bg_color conflict | 400 | Cannot use 'mask=true' together with 'bg_color'. Choose one or the other. |
| Email not verified | 403 | Email address not verified – please check your inbox |
| Invalid API key | 401 | invalid api key |
| Both API key and user token sent | 400 | This is a mistake: Cannot use both API key and user token |
| Rate limit exceeded (short-term) | 429 | You're making requests too quickly, Please Upgrade or slow down. |
| Rate limit exceeded (daily, anonymous) | 429 | You've reached your daily limit. Please sign up for more access. |
| Rate limit exceeded (monthly, authenticated) | 429 | You've reached your monthly limit. Consider purchasing more credits. |
Error Handling Guidelines
- Check HTTP status code 400 to identify validation errors
- Parse the
errorfield for the error message - Check for the
detailsarray when handling multiple validation errors - Use the
fieldproperty to map errors to specific request parameters