Skip to content

Client Examples

Mehrdad Pajuhaan edited this page Oct 23, 2026 · 1 revision

Client Examples

This page shows how to call the background removal service from common languages. All examples send the image as the multipart field file to POST /remove-bg and save the PNG response. Replace http://localhost:8000 with the address of your server.

cURL

curl -X POST \
  -F "file=@product.jpg" \
  http://localhost:8000/remove-bg \
  --output product.png

Print the response headers (processing time and device) with -D -:

curl -s -D - -o product.png -F "file=@product.jpg" http://localhost:8000/remove-bg

Python (requests)

import requests

with open("product.jpg", "rb") as f:
    response = requests.post(
        "http://localhost:8000/remove-bg",
        files={"file": ("product.jpg", f, "image/jpeg")},
        timeout=120,
    )

if response.status_code == 200:
    with open("product.png", "wb") as out:
        out.write(response.content)
    print("Processed in", response.headers.get("S-Processing-Time"), "s on",
          response.headers.get("S-Processing-Device", "n/a"))
else:
    print("Error:", response.status_code, response.text)

requests is not part of requirements.txt; install it in the client environment with pip install requests.

JavaScript (Node.js 18+ or a back end)

import { readFile, writeFile } from "node:fs/promises";

const form = new FormData();
form.append("file", new Blob([await readFile("product.jpg")]), "product.jpg");

const res = await fetch("http://localhost:8000/remove-bg", {
  method: "POST",
  body: form,
});

if (!res.ok) {
  throw new Error(`Background removal failed: ${await res.text()}`);
}

await writeFile("product.png", Buffer.from(await res.arrayBuffer()));
console.log("Processing time:", res.headers.get("S-Processing-Time"));

The service does not configure CORS. Calling it directly from a browser page on another origin is blocked by the browser. Call it from your back end, or put it behind a reverse proxy on the same origin. See Deployment.

PHP (cURL extension)

<?php
$ch = curl_init('http://localhost:8000/remove-bg');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => ['file' => new CURLFile('product.jpg', 'image/jpeg')],
    CURLOPT_RETURNTRANSFER => true,
]);

$png = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($status === 200) {
    file_put_contents('product.png', $png);
} else {
    echo "Error: $png";
}

Handling errors

  • 200 — the body is a PNG.
  • 400 — the body is JSON: { "error": "<message>" }.
  • 422 — the file field was missing (FastAPI validation error).

Related

Clone this wiki locally