This tutorial shows a complete Python integration flow using the FAPIhub background removal API. You can start with a single image and extend to high-volume processing in minutes.
Prerequisites
- A FAPIhub API key from dashboard
- Python 3.9+
- The
requestspackage
Step 1: Install dependencies
pip install requestsStep 2: Remove one background
import requests
with open("input.jpg", "rb") as image_file:
response = requests.post(
"https://fapihub.com/v2/rembg/",
headers={"ApiKey": "YOUR_API_KEY"},
files={"image": image_file},
timeout=30,
)
response.raise_for_status()
with open("output.png", "wb") as out:
out.write(response.content)
Step 3: Add error handling
try:
response = requests.post(...)
if response.status_code != 200:
print("Request failed", response.status_code, response.text)
else:
...
except requests.RequestException as exc:
print("Network or timeout error:", exc)
Step 4: Batch processing
import requests
from pathlib import Path
input_dir = Path("images")
output_dir = Path("results")
output_dir.mkdir(exist_ok=True)
for image_path in input_dir.glob("*.jpg"):
with open(image_path, "rb") as image_file:
response = requests.post(
"https://fapihub.com/v2/rembg/",
headers={"ApiKey": "YOUR_API_KEY"},
files={"image": image_file},
timeout=30,
)
if response.status_code == 200:
(output_dir / f"{image_path.stem}.png").write_bytes(response.content)
else:
print(f"{image_path.name} failed: HTTP {response.status_code}")
For production pipelines, add retry logic, queueing, and concurrency controls. Pricing stays predictable: $0.00214/image at 7,000 images a month on the Pro plan, and less per image on higher plans.
Step 5: Keep the API key out of your code
Hardcoding YOUR_API_KEY is fine for a first test, but the key should come from the environment before the script goes anywhere near a repository. A requests.Session also lets you set the header once and reuse the underlying connection across many calls, which helps in batch jobs.
export FAPIHUB_API_KEY="your_key_here"import os
import requests
API_URL = "https://fapihub.com/v2/rembg/"
session = requests.Session()
session.headers["ApiKey"] = os.environ["FAPIHUB_API_KEY"]
You can create, view, and deactivate keys in the dashboard. If a key leaks, deactivate it and generate a new one.
Step 6: Handle each error code properly
The error handling in Step 3 prints the failure, which is enough to debug. In production you want to treat each failure differently. Successful responses contain the PNG bytes directly. Errors return JSON shaped like {"error": {"code": "...", "message": "...", "request_id": "..."}}, so you can branch on the status code and log the request_id.
| Status | Code | Retry? |
|---|---|---|
| 400 | invalid_image | No. The file or a parameter is invalid. |
| 401 | invalid_api_key | No. Fix the key. |
| 402 | insufficient_credits | No. Quota is used up; upgrade or wait for the next billing period. |
| 429 | rate_limit_exceeded | Yes, after the Retry-After delay. |
| 5xx | server error | Yes, with exponential backoff. |
Here is a function that does all of that and raises a clear exception for errors that should not be retried:
import time
class BackgroundRemovalError(Exception):
def __init__(self, status, code, message, request_id=None):
super().__init__(f"{status} {code}: {message} (request_id={request_id})")
self.status = status
self.code = code
def parse_error(response):
try:
err = response.json().get("error", {})
except ValueError:
err = {}
return BackgroundRemovalError(
response.status_code,
err.get("code", "unknown"),
err.get("message", response.text[:200]),
err.get("request_id"),
)
def remove_background(image_bytes: bytes, max_attempts: int = 4) -> bytes:
for attempt in range(max_attempts):
try:
response = session.post(
API_URL,
files={"image": ("upload", image_bytes)},
timeout=60,
)
except requests.RequestException:
if attempt == max_attempts - 1:
raise
time.sleep(2 ** attempt)
continue
if response.status_code == 200:
return response.content
if response.status_code == 429:
time.sleep(int(response.headers.get("Retry-After", 2 ** attempt)))
continue
if response.status_code >= 500 and attempt < max_attempts - 1:
time.sleep(2 ** attempt)
continue
raise parse_error(response)
raise BackgroundRemovalError(429, "rate_limit_exceeded", "retries exhausted")
Retrying 5xx responses costs you nothing in quota, because server-side errors are never counted. Retrying a 400 or 401 just repeats the same failure, and 4xx responses do count.
Step 7: Validate files before you upload
Because 4xx errors count toward your quota, it pays to reject bad files locally. The API accepts JPEG, PNG, WebP, BMP, and GIF up to 10 MB. If you already have Pillow installed, you can also confirm that the file actually decodes as an image:
from pathlib import Path
from PIL import Image
MAX_BYTES = 10 * 1024 * 1024
ALLOWED_FORMATS = {"JPEG", "PNG", "WEBP", "BMP", "GIF"}
def is_valid_upload(path: Path) -> bool:
if path.stat().st_size > MAX_BYTES:
return False
try:
with Image.open(path) as img:
img.verify()
return img.format in ALLOWED_FORMATS
except Exception:
return False
Checking the decoded format is more reliable than checking the file extension, since files are often renamed or exported with the wrong suffix.
Step 8: Process a folder concurrently
The loop in Step 4 handles one image at a time. A small thread pool speeds this up considerably because most of the time is spent waiting on the network. Keep the worker count modest: every plan has a per-minute rate limit, and the retry logic from Step 6 absorbs the occasional 429.
from concurrent.futures import ThreadPoolExecutor, as_completed
input_dir = Path("images")
output_dir = Path("results")
output_dir.mkdir(exist_ok=True)
def process(path: Path) -> str:
target = output_dir / f"{path.stem}.png"
if target.exists():
return f"skipped {path.name}"
if not is_valid_upload(path):
return f"invalid {path.name}"
try:
target.write_bytes(remove_background(path.read_bytes()))
return f"done {path.name}"
except BackgroundRemovalError as exc:
return f"failed {path.name}: {exc}"
paths = [p for p in input_dir.iterdir() if p.is_file()]
with ThreadPoolExecutor(max_workers=4) as pool:
for future in as_completed(pool.submit(process, p) for p in paths):
print(future.result())
Skipping files that already have an output makes the script safe to rerun after an interruption. For very large jobs, see the bulk background removal guide, and for queues, idempotency, and monitoring, read production best practices.
Step 9: Use the other endpoints
The same request pattern works for every endpoint. Only the URL and the extra form fields change. A solid white background, for example:
response = session.post(
"https://fapihub.com/v2/rembg/color/",
files={"image": open("input.jpg", "rb")},
data={"bgcolor": "(255, 255, 255, 255)"},
timeout=60,
)
Other options follow the same shape:
/v2/rembg/and/v2/rembg/mask/accept an optionalmodelfield:falcon(default),aurora, orghost. Try each on your own images and keep the one that looks best./v2/rembg/blur/takes an integerradius(required, maximum 50)./v2/rembg/gradient/takestop_colorandbottom_coloras RGBA tuple strings./v2/rembg/shadow/takesshadow_colorsuch as"(0, 0, 0, 150)",offsetsuch as"(10, 10)", and an integerblur_radius.
You can try every option interactively in the playground before writing code. If you are building a web app, the Django integration guide shows how to wire this into a view.
Common mistakes
- Saving the result as JPEG. JPEG has no alpha channel, so the transparent background turns black or white. Save as
.png, or as WebP if you need smaller files with transparency. - Calling
response.json()on success. A 200 response is raw image bytes. Only parse JSON when the status is not 200. - No timeout. Without
timeout=, a stalled connection can hang a worker forever. - Leaving files open. Use
with open(...)or read the bytes first, especially inside loops that process thousands of files. - Calling the API from the browser. That exposes your key. Send uploads to your own backend and call the API server-side.
Frequently asked questions
What does the API return?
On success, the processed image bytes as a PNG with transparency preserved. Write response.content straight to a file. There is no JSON wrapper or download URL.
Which Python version do I need?
Any Python 3.9+ release works with the examples here. The only required package is requests; Pillow is optional for validation.
How many images can I process for free?
The Basic plan includes 100 full-resolution requests per month with no credit card. Pro covers 7,500 requests a month for $15, and per-usage packs cost $10 for 1,000 requests that never expire.
Why am I getting HTTP 402?
A 402 with insufficient_credits means your plan's quota for the period is used up. Upgrade your plan or add a per-usage pack, then rerun the failed images.
A fuller reference with more Python examples is on the Python background removal page.