Tutorial

How to Build a Background Removal API: A Step-by-Step Tutorial

This guide shows you how to create a FastAPI-based API that removes image backgrounds using EdenAI. It supports both URL and file uploads, returning base64 images for easy frontend integration.

 How to Build a Background Removal API: A Step-by-Step Tutorial
TABLE OF CONTENTS

In this comprehensive tutorial, we'll walk you through the step-by-step process of creating a fully functional background removal API using FastAPI, one of the fastest and most modern web frameworks for building APIs with Python.

To power the actual background removal, we’ll integrate with EdenAI, a platform that aggregates multiple AI services under a single API.

For a more in-depth explanation, make sure to watch our Youtube tutorial on background removal, where we provide a detailed breakdown of each step.

By following along with the video, you'll gain a complete understanding of the process, ensuring you don't miss any important details.

Whether you're new to Python APIs, background removal, or FastAPI, this hands-on guide is beginner-friendly and practical.

What You'll Build

By the end of this tutorial, you’ll have a working API that:

  • Accepts an image via URL or file upload.
  • Sends the image to EdenAI’s background removal endpoint.
  • Returns a base64 version of the image with the background removed (suitable for displaying in a frontend)

Prerequisites

Before starting, make sure you have the following tools and knowledge:

  • Python 3.7+: Required for compatibility with FastAPI and other libraries.
  • pip: Python’s package manager for installing libraries.
  • EdenAI API Key: You’ll need to create an account on edenai.co and grab your API key.
  • Basic Python knowledge: Especially around functions and JSON.

What is Background Removal API?

Background Removal - Eden AI

Eden AI’s Background Removal API uses AI to automatically remove the background from images, isolating the main subject.

It supports multiple providers (like PhotoRoom and Sentisight) through a single, unified API, making it easy to integrate and switch between services.

Common use cases include e-commerce, design, and social media, helping users create clean, professional visuals without manual editing.

Step-by-Step Guide

Step 1: Project Setup

Start by creating a dedicated folder and setting up a Python virtual environment (best practice for Python projects).


mkdir background_removal_api
cd background_removal_api
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate

A virtual environment ensures your project’s dependencies don't interfere with system-wide packages.

  • mkdir and cd create and move into your project folder.
  • python -m venv venv initializes a virtual environment to isolate your project dependencies.
  • source venv/bin/activate activates the virtual environment so that any installed packages are limited to this project.

Next, install the required dependencies:


pip install fastapi uvicorn python-dotenv requests python-multipart

Here’s what each library does:

  • fastapi: The web framework to build your API.
  • uvicorn: An ASGI server to run your FastAPI app.
  • python-dotenv: Loads environment variables (like your API key) from a .env file.
  • requests: Sends HTTP requests to EdenAI’s API.
  • python-multipart: Enables FastAPI to handle file uploads.

Create a .env file in the root directory and store your EdenAI API key securely:


EDEN_AI_API_KEY=your_edenai_api_key_here

Never upload this file to version control (like GitHub)! It contains your private API credentials.

Step 2: Create the API File

Create a file named main.py and paste in the full FastAPI code.


from fastapi import FastAPI, File, UploadFile, HTTPException, Form
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import requests
import tempfile
import os
from dotenv import load_dotenv
from typing import Optional, List
from pydantic import BaseModel

# Initialize FastAPI app
app = FastAPI(title="Background Removal API")

# Load environment variables
load_dotenv()

# Enable CORS (important if using with frontend apps)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  
    allow_credentials=True,
    allow_methods=["*"],  
    allow_headers=["*"],  
)

# Load your EdenAI API key from the .env
EDENAI_API_KEY = os.getenv('EDEN_AI_API_KEY')
EDENAI_API_ENDPOINT = "https://api.edenai.run/v2/image/background_removal"

Step 3: Add the Model for URL Input

This model is used to define what we expect when a user sends a URL-based background removal request:


class ImageURL(BaseModel):
    file_url: str
    providers: List[str]
    fallback_providers: Optional[List[str]] = None
    response_as_dict: Optional[bool] = True
    attributes_as_list: Optional[bool] = False
    show_base_64: Optional[bool] = True
    show_original_response: Optional[bool] = False
    provider_params: Optional[dict] = None

Step 4: Root Route (Health Check)

This basic route just confirms the API is live:


@app.get("/")
def read_root():
    return {
        "message": "Background Removal API",
        "endpoints": ["/remove-bg/url", "/remove-bg/upload"]
    }

This is a simple GET endpoint to confirm that your API is running. When you visit the root URL, it returns a friendly message.

Step 5: URL-Based Background Removal Endpoint

Now implement an endpoint that receives an image URL and removes the background via EdenAI:


@app.post("/remove-bg/url")
async def remove_background_from_url(data: ImageURL):
    headers = {"Authorization": f"Bearer {EDENAI_API_KEY}"}
    
    json_payload = {
        "providers": ",".join(data.providers),
        "file_url": data.file_url,
        "response_as_dict": data.response_as_dict,
        "attributes_as_list": data.attributes_as_list,
        "show_base_64": data.show_base_64,
        "show_original_response": data.show_original_response
    }

    if data.fallback_providers:
        json_payload["fallback_providers"] = ",".join(data.fallback_providers)
    if data.provider_params:
        json_payload["provider_params"] = data.provider_params

    try:
        response = requests.post(EDENAI_API_ENDPOINT, json=json_payload, headers=headers)
        response.raise_for_status()
        return response.json()
        
    except requests.exceptions.HTTPError as e:
        error_detail = e.response.json() if e.response.content else str(e)
        raise HTTPException(status_code=e.response.status_code, detail=error_detail)
    except requests.exceptions.RequestException as e:
        raise HTTPException(status_code=500, detail=f"Error: {str(e)}")

What this does:

  • Takes a JSON payload with an image URL.
  • Sends it to EdenAI.
  • Returns the base64 image data.

If the request fails (e.g. invalid image), it returns a 500 error.

Step 6: File Upload Background Removal Endpoint

This endpoint handles images uploaded directly as files:


@app.post("/remove-bg/upload")
async def remove_background_from_file(
    file: UploadFile = File(...),
    providers: str = Form(...),
    fallback_providers: Optional[str] = Form(None),
    response_as_dict: Optional[bool] = Form(True),
    attributes_as_list: Optional[bool] = Form(False),
    show_base_64: Optional[bool] = Form(True),
    show_original_response: Optional[bool] = Form(False)
):
    headers = {"Authorization": f"Bearer {EDENAI_API_KEY}"}
    temp_file = None
    file_content = await file.read()
    
    try:
        temp_fd, temp_path = tempfile.mkstemp(suffix=".tmp")
        temp_file = os.fdopen(temp_fd, "wb")
        temp_file.write(file_content)
        temp_file.close()
        
        data = {
            "providers": providers,
            "response_as_dict": str(response_as_dict).lower(),
            "attributes_as_list": str(attributes_as_list).lower(),
            "show_base_64": str(show_base_64).lower(),
            "show_original_response": str(show_original_response).lower()
        }

        if fallback_providers:
            data["fallback_providers"] = fallback_providers
        
        with open(temp_path, "rb") as f:
            files = {
                "file": (file.filename, f, file.content_type or "application/octet-stream")
            }
            response = requests.post(EDENAI_API_ENDPOINT, data=data, files=files, headers=headers)
        
        if response.status_code != 200:
            error_detail = response.json() if response.content else "Unknown error"
            raise HTTPException(status_code=response.status_code, detail=error_detail)
            
        return response.json()
        
    except requests.exceptions.RequestException as e:
        raise HTTPException(status_code=500, detail=f"Request error: {str(e)}")
    finally:
        if temp_file and not temp_file.closed:
            temp_file.close()
        if temp_path and os.path.exists(temp_path):
            try:
                os.unlink(temp_path)
            except Exception as e:
                print(f"Warning: Could not delete temporary file: {e}")

What this does:

  • Accepts an uploaded image file.
  • Temporarily saves it as temp.png.
  • Sends the file to EdenAI for processing using multipart/form-data.
  • Deletes the temporary file afterward to clean up storage.
  • Returns the processed image as a base64 string.

Step 7: Run Your API

Start your FastAPI app using Uvicorn:


uvicorn main:app --reload

Visit http://127.0.0.1:8000 to test the health check route.

Testing the Endpoints

1. URL Test

Send a POST request to /remove-bg/url with a JSON body like:


{
  "file_url": "https://example.com/image.jpg",
  "providers": ["remove_bg"]
}

2. Upload Test (e.g., with Postman or a frontend)

Use Postman or a frontend client to POST to /remove-bg/file with form-data:

  • file: upload an image file
  • providers: remove_bg

Tips and Suggestions

EdenAI supports multiple background removal providers. You can specify fallback_providers to ensure reliability if the primary one fails.

CORS middleware is enabled by default for all origins — making it frontend-friendly.

Always secure your .env files by adding them to .gitignore.

Conclusion

By following this step-by-step tutorial, you've built a powerful and flexible background removal API using FastAPI and EdenAI.

Whether you're working on a web app, mobile app, or internal tool, this API can now handle both image URLs and direct uploads, returning clean, base64-encoded images ready for use.

You've also learned best practices around environment variables, API integration, and modular code design.

From here, you can extend the functionality with more AI services from EdenAI, add user authentication, or deploy your API to a cloud platform like Render, Vercel, or Railway.

Resources

Ready to dive deeper? We've got everything you need to get started.

Background Removal Documentation

Full Code - Github

Start Your AI Journey Today

  • Access 100+ AI APIs in a single platform.
  • Compare and deploy AI models effortlessly.
  • Pay-as-you-go with no upfront fees.
Start building FREE

Related Posts

Try Eden AI for free.

You can directly start building now. If you have any questions, feel free to chat with us!

Get startedContact sales
X

Start Your AI Journey Today

Sign up now with free credits to explore 100+ AI APIs.
Get my FREE credits now