Python Background Removal Tutorial

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 requests package

Step 1: Install dependencies

pip install requests

Step 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

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},
        )
    if response.status_code == 200:
        (output_dir / f"{image_path.stem}.png").write_bytes(response.content)

For production pipelines, add retry logic, queueing, and concurrency controls. Pricing remains predictable at $0.00214/image at volume, which is a major advantage versus alternatives.