✳ TUTORIALS · 5 MIN

How to Remove Image Backgrounds with Python

This example sends one local image from a Python server or script. Keep the API key outside source control and check the response before writing output.

Install the dependency

Install requests in your environment with `python -m pip install requests`. Set `BGFREE_API_KEY` in your shell or secret manager before running the script.

Send the request

import os import requests endpoint = "https://api.bgfree.app/v1.0/removebg" headers = {"X-Api-Key": os.environ["BGFREE_API_KEY"]} with open("photo.jpg", "rb") as source: response = requests.post(endpoint, headers=headers, files={"image_file": source}, timeout=90) response.raise_for_status() with open("cutout.png", "wb") as output: output.write(response.content)

Handle errors safely

In production, catch request timeouts and HTTP errors, inspect the JSON error body when present, and retry only transient failures with backoff. Do not print the API key or upload contents into logs. The output filename extension should match the requested format; PNG is the default.