How to Remove Backgrounds in Bulk: API Guide for Developers
When You Need Batch Background Removal
Manual background removal — even with AI tools — hits a wall around 50-100 images. Beyond that volume, you need automation. E-commerce platforms onboarding new vendors with thousands of product images, marketing teams preparing campaign assets across dozens of products, and SaaS applications offering image editing as a feature all require programmatic background removal.
The solution is an API-based workflow: write a script that reads images from your source (local directory, database, cloud storage), sends each to a background removal API, and saves the processed results. A well-structured batch script can process thousands of images overnight with minimal monitoring, turning what would be days of manual work into a fully automated pipeline.
This guide walks through the complete implementation: API setup, batch processing patterns with concurrency control, error handling and retry logic, and production optimization. We provide complete code examples in Node.js and Python that you can adapt to your specific use case.
API Setup and Authentication
Before writing any code, you need an API key. Sign up at bgeraser.ink, navigate to your Dashboard, and generate an API key. The key is a Bearer token included in the Authorization header of every request. Store it in an environment variable (BGERASER_API_KEY) rather than hardcoding it in your scripts.
The background removal endpoint accepts multipart form data with the image file. Here's the minimal cURL example: curl -X POST https://bgeraser.ink/api/tools/bg-removal -H 'Authorization: Bearer $BGERASER_API_KEY' -F '[email protected]' -o output.png. The response includes the processed image URL, dimensions, and processing time. Download the image from the returned URL and save it to your destination.
Free accounts get 15 credits per month. For batch processing, you'll need a paid plan. Check your current credit balance via the dashboard or the /api/account endpoint before starting a large batch to avoid hitting limits mid-run. The API returns an INSUFFICIENT_CREDITS error (HTTP 402) when credits are exhausted.
Node.js Implementation
Here's a complete Node.js batch processing script. The core logic reads image files from a source directory, sends each to the API with concurrency control, and saves results to an output directory. Key dependencies: node-fetch (or built-in fetch in Node 18+) for HTTP requests, and p-limit for concurrency control.
The processing function for a single image: create a FormData instance, append the image as a readable stream, POST to the API endpoint with your API key, parse the JSON response, download the processed image from the returned URL, and save it to disk. Wrap this in a try-catch to handle failures gracefully without crashing the entire batch.
For concurrency, use p-limit to restrict parallel requests to your plan's rate limit (typically 10 concurrent for standard plans). Without concurrency control, you'll hit rate limits (HTTP 429) and slow down overall throughput due to retries. The sweet spot is usually 5-8 concurrent requests, which maximizes throughput while staying safely under rate limits: const limit = pLimit(8); const tasks = files.map(f => limit(() => processImage(f))); await Promise.all(tasks);
Add progress tracking by logging completed/total counts after each image. For large batches (1000+ images), write progress to a log file so you can resume from the last successful image if the script is interrupted. A simple JSON checkpoint file that records processed filenames enables reliable resume functionality.
Python Implementation
Python developers can use the requests library for synchronous processing or aiohttp with asyncio for concurrent processing. The synchronous approach is simpler: iterate over files, send each to the API via requests.post() with the file in the files parameter, and save the result. This works well for small batches (under 100 images) where total processing time is acceptable.
For larger batches, use asyncio with aiohttp for concurrent processing. Create an asyncio.Semaphore to limit concurrency, define an async function that processes a single image, and gather all tasks: semaphore = asyncio.Semaphore(8); tasks = [process_image(sem, f) for f in files]; results = await asyncio.gather(*tasks, return_exceptions=True). This pattern provides the same throughput benefits as the Node.js p-limit approach.
Error handling in Python should catch both network errors (requests.ConnectionError, asyncio.TimeoutError) and API errors (non-200 status codes). Implement exponential backoff for rate limit errors (HTTP 429): wait 1 second after the first 429, 2 seconds after the second, 4 seconds after the third, and so on. Cap the maximum wait at 60 seconds and retry up to 5 times before marking the image as failed.
For production scripts, use Python's logging module instead of print statements. Log each processed image with its filename, processing time, and output path. Log errors with the full response body for debugging. Write failed filenames to a separate file so you can re-run only the failures after fixing any issues.
Error Handling and Retry Patterns
Robust batch processing requires handling three categories of errors: transient failures, permanent failures, and rate limits. Transient failures (network timeouts, 500 server errors) should be retried with exponential backoff. Permanent failures (invalid image format, file too large, authentication errors) should be logged and skipped. Rate limits (HTTP 429) are a special case of transient failure — the Retry-After response header tells you exactly when to retry.
Implement a retry wrapper that handles all three categories. On a transient error, wait and retry up to 3-5 times. On a permanent error, log the failure and continue to the next image. On a rate limit, respect the Retry-After header. This wrapper should be generic enough to apply to any API call, making it reusable across your codebase.
For batch jobs processing thousands of images, implement a checkpoint/resume mechanism. After each successful image, append its filename to a 'completed' list. When restarting the script, read this list and skip already-completed images. This prevents re-processing (wasting credits) and allows you to stop and resume the batch without losing progress.
Monitor your credit balance throughout the batch. After every N images (say, every 100), check your remaining credits via the API and log the balance. If credits drop below a threshold, pause the batch and alert the operator rather than continuing until the API starts returning 402 errors. This proactive monitoring prevents wasted time on failed requests.
API Comparison: bgeraser vs Remove.bg vs PhotoRoom
Three APIs dominate the background removal space for developers. bgeraser's API covers 7 tools (not just background removal) with a single API key, flat-rate pricing on paid plans, and sub-3-second processing times. Remove.bg's API is the most established, with excellent documentation, SDKs in multiple languages, and pay-per-image pricing ($0.20-$0.90 per image depending on volume). PhotoRoom's API offers background removal plus template-based image generation, useful for creating styled product images programmatically.
On pricing, bgeraser is most cost-effective for high volumes due to its credit-based model where paid plans include large credit allocations. Remove.bg's per-image pricing favors low-volume use (under 200 images/month) but becomes expensive at scale — 10,000 images at $0.20 each is $2,000/month. PhotoRoom's pricing is competitive for users who also need its template features.
On quality, all three produce excellent results on standard images. Edge cases (hair, transparency, low contrast) show minor differences — bgeraser and Remove.bg are slightly ahead of PhotoRoom on complex edges in our testing. On speed, all three are comparable at 1-4 seconds per image. On developer experience, Remove.bg has the most mature documentation and SDKs, while bgeraser offers the broadest tool coverage from a single API.
Our recommendation for developers: if you only need background removal, Remove.bg's mature ecosystem is a safe choice. If you need background removal plus other AI editing operations (upscaling, generative fill, canvas expansion), bgeraser's unified API avoids integrating multiple services. If you need template-based image generation alongside removal, PhotoRoom fills that niche uniquely.
Production Optimization Tips
Resize images before sending to the API. If your source images are 6000x4000 pixels but your output only needs to be 2000x2000, resize locally before uploading. This reduces upload time, processing time, and bandwidth costs. Most background removal models produce identical quality at 2000-3000px as they do at 6000px — there's no benefit to sending oversized images.
Use parallel processing wisely. Start with 5 concurrent requests and increase gradually while monitoring for 429 errors. The optimal concurrency depends on your plan's rate limit, your network bandwidth, and the API's current load. Measure throughput (images/minute) at different concurrency levels and use the one that maximizes throughput without triggering rate limits.
Cache processed results aggressively. Store a hash of each input image alongside the output URL or file path. Before processing an image, check if you've already processed an identical file. This prevents duplicate processing when re-running batch scripts on directories that contain previously processed images. Even a simple MD5 hash comparison saves significant credits and time.
For recurring batch jobs (like processing new product uploads nightly), implement a delta processing pattern. Track which images are new or modified since the last run and only process those. Combine this with the checkpoint/resume mechanism for bulletproof batch processing that handles interruptions, avoids duplicates, and runs efficiently on incremental workloads.
Try bgeraser Tools
Related Posts
Introducing bgeraser: 7 AI Image Editing Tools in One Platform
We built bgeraser because image editing shouldn't require five different apps, three subscriptions, and a design degree. Today we're launching 7 AI-powered tools in a single platform with a generous free tier.
How to Remove Backgrounds from Product Photos (Complete Guide)
Clean product photos on white or transparent backgrounds convert better on every marketplace. This guide covers the complete workflow — from shooting photos that cut out cleanly to batch-processing your entire catalog via API.