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.
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.
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:
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.