The fastest way to integrate BackgroundErase in Python is with a simple multipart upload script. You do not need requests, Pillow, or any other third-party package. The example below uses only the Python standard library.
Quick summary: Get an API key, save the helper script as background_erase.py, call background_removal(src, dst), and your output will be written to disk as a processed image.
Prerequisites
Before you begin, make sure you have:
- Python 3.7 or higher
- An API key from your account dashboard
- An active Business or Enterprise subscription with API access
Authentication
API access requires an active business subscription. After subscribing:
- Go to your account dashboard.
- Find the API Access section.
- Generate a new token and store it securely.
No-dependency quickstart
Save the following as background_erase.py. This helper uploads an image to the API and writes the processed result to the output path you specify.
import http.client, os, uuid, mimetypes
API_KEY = "YOUR_API_KEY"
def background_removal(src, dst):
fname = os.path.basename(src)
ctype = mimetypes.guess_type(src)[0] or "application/octet-stream"
boundary, CRLF = "----%s" % uuid.uuid4().hex, "\r\n"
with open(src, "rb") as f: data = f.read()
body = (
f"--{boundary}{CRLF}"
f'Content-Disposition: form-data; name="image_file"; filename="{fname}"{CRLF}'
f"Content-Type: {ctype}{CRLF}{CRLF}"
).encode() + data + f"{CRLF}--{boundary}--{CRLF}".encode()
headers = {
"Content-Type": f"multipart/form-data; boundary={boundary}",
"x-api-key": API_KEY,
"Content-Length": str(len(body))
}
conn = http.client.HTTPSConnection("api.backgrounderase.com")
conn.request("POST", "/v2", body=body, headers=headers)
resp = conn.getresponse()
out = resp.read()
if resp.status == 200:
with open(dst, "wb") as f: f.write(out)
print("✅ Saved:", dst)
else:
print("❌", resp.status, resp.reason, out.decode(errors="ignore"))
conn.close()Basic usage example
Create a second file called example.py:
from background_erase import background_removal
INPUT_PATH = "./input.jpg"
OUTPUT_PATH = "./output.png"
background_removal(INPUT_PATH, OUTPUT_PATH)Then run it with:
python example.pyUsing an environment variable
Instead of hardcoding your API key, you can store it in an environment variable and read it in Python. This is the recommended approach for local development and production deployments.
import os
API_KEY = os.getenv("BACKGROUND_ERASE_API_KEY")Tip: Keeping the key outside your source code makes rotation easier and helps prevent accidental exposure.
Optional: low-latency JSON mode
If you need faster round-trips, the JSON mode client reduces payload size by downscaling your image to 1024×1024 before sending it. The API returns a grayscale mask, and the client upscales that mask back to your original dimensions and composites it onto the source PNG locally.
This preserves the original pixels while keeping requests lightweight, which makes it a strong choice for:
- Real-time UIs
- Bulk jobs on constrained networks
- Faster perceived time-to-first-pixel
- Workflows where the client can composite locally
Prefer to keep everything no-deps? Stick with the multipart example above. When you want to optimize further for latency, move to the JSON mode client.
Why start with multipart?
- It is the simplest way to get working quickly.
- It uses only the Python standard library.
- You receive the processed file directly and save it to disk.
- It is easy to debug and adapt to your own codebase.
