DEV Community

Fred Santos
Fred Santos

Posted on

How to Remove Image Backgrounds via REST API in 2 Lines of Code

How to Remove Image Backgrounds via REST API in 2 Lines of Code

Background removal used to require Photoshop, GIMP scripts, or local Python environments with rembg and its model files (~170MB). Today you can do it with a single HTTP request.

This tutorial shows how to remove backgrounds from images using IteraTools' rembg endpoint — no Python environment, no model downloads, no GPU required.

What to Consider When Choosing a Background Removal API

  • Quality on complex edges: Hair, fur, and transparent objects are the real test.
  • Output format: Must return transparent PNG (not JPEG which doesn't support transparency).
  • Input flexibility: Accepts URLs or file uploads.
  • Speed: Batch processing speed for product catalogs matters.
  • Price at scale: Per-image pricing adds up fast for e-commerce use cases.

Comparison Table

Tool Price Quality Input Types Output
IteraTools ~$0.002/image (credits) Good (rembg) URL, file upload Transparent PNG
Remove.bg $0.20/image Excellent URL, file PNG
Clipdrop $0.10–$0.20/image Very Good File PNG
PhotoRoom API $0.10/image Excellent File PNG
BgSub $0.05/image Good File PNG

IteraTools is 50–100x cheaper than premium providers like Remove.bg, making it viable for bulk operations. Quality is solid for most product photography use cases.

Remove Background — 2-line curl

curl -X POST https://api.iteratools.com/v1/image/rembg \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/product.jpg"}' \
  | python3 -c "import sys,json; print(json.load(sys.stdin)['url'])"
Enter fullscreen mode Exit fullscreen mode

That's it. Two commands (one API call + extracting the URL), no installations.

Full response:

curl -X POST https://api.iteratools.com/v1/image/rembg \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/shoe_photo.jpg"
  }'
Enter fullscreen mode Exit fullscreen mode
{
  "url": "https://cdn.iteratools.com/images/rembg/transparent_abc123.png",
  "format": "png",
  "width": 800,
  "height": 600,
  "credits_used": 2
}
Enter fullscreen mode Exit fullscreen mode

Upload a local file:

curl -X POST https://api.iteratools.com/v1/image/rembg \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "file=@product_photo.jpg"
Enter fullscreen mode Exit fullscreen mode

Complete Python Example

import requests
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed

API_KEY = "your_api_key_here"
BASE_URL = "https://api.iteratools.com/v1"

def remove_background_url(image_url: str) -> str:
    """Remove background from image URL, return transparent PNG URL."""
    response = requests.post(
        f"{BASE_URL}/image/rembg",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json={"url": image_url}
    )
    response.raise_for_status()
    return response.json()["url"]

def remove_background_file(image_path: str, output_path: str = None) -> str:
    """Remove background from local file, save transparent PNG."""
    if output_path is None:
        p = Path(image_path)
        output_path = str(p.parent / f"{p.stem}_nobg.png")

    with open(image_path, "rb") as f:
        response = requests.post(
            f"{BASE_URL}/image/rembg",
            headers={"Authorization": f"Bearer {API_KEY}"},
            files={"file": (Path(image_path).name, f)}
        )
    response.raise_for_status()
    data = response.json()

    # Download the transparent PNG
    img_data = requests.get(data["url"])
    Path(output_path).write_bytes(img_data.content)

    return output_path

def batch_remove_backgrounds(image_paths: list[str], max_workers: int = 5) -> dict:
    """Process multiple images in parallel."""
    results = {}

    def process_one(path: str) -> tuple:
        try:
            output = remove_background_file(path)
            return path, output, None
        except Exception as e:
            return path, None, str(e)

    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        futures = {executor.submit(process_one, p): p for p in image_paths}
        for future in as_completed(futures):
            input_path, output_path, error = future.result()
            if error:
                print(f"{input_path}: {error}")
                results[input_path] = {"success": False, "error": error}
            else:
                print(f"{input_path}{output_path}")
                results[input_path] = {"success": True, "output": output_path}

    return results

def process_product_catalog(catalog_dir: str, output_dir: str) -> None:
    """Process all product images in a directory."""
    Path(output_dir).mkdir(parents=True, exist_ok=True)

    image_files = list(Path(catalog_dir).glob("*.jpg")) + \
                  list(Path(catalog_dir).glob("*.png")) + \
                  list(Path(catalog_dir).glob("*.jpeg"))

    print(f"Processing {len(image_files)} images...")

    for img_path in image_files:
        output_path = Path(output_dir) / f"{img_path.stem}_nobg.png"
        remove_background_file(str(img_path), str(output_path))
        print(f"{img_path.name}")

    print(f"\nDone! Transparent PNGs saved to: {output_dir}")

if __name__ == "__main__":
    # Single image
    result_url = remove_background_url(
        "https://images.unsplash.com/photo-1542291026-7eec264c27ff?w=500"
    )
    print(f"Transparent PNG: {result_url}")

    # Local file
    output = remove_background_file("my_product.jpg")
    print(f"Saved to: {output}")

    # Batch process product catalog
    product_images = [
        "products/shoe_01.jpg",
        "products/shoe_02.jpg",
        "products/bag_01.jpg",
    ]
    results = batch_remove_backgrounds(product_images, max_workers=3)
    successful = sum(1 for r in results.values() if r["success"])
    print(f"\nProcessed: {successful}/{len(product_images)} successful")
Enter fullscreen mode Exit fullscreen mode

Combine with Image Generation

One powerful pattern: generate a product image, then immediately remove its background:

# Generate → Remove Background → Resize (all via IteraTools)
def create_product_image(prompt: str) -> str:
    # 1. Generate
    gen = requests.post(
        f"{BASE_URL}/image/generate",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json={"prompt": prompt, "model": "flux"}
    ).json()

    # 2. Remove background
    rembg = requests.post(
        f"{BASE_URL}/image/rembg",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json={"url": gen["url"]}
    ).json()

    # 3. Resize to thumbnail
    thumb = requests.post(
        f"{BASE_URL}/image/resize",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json={"url": rembg["url"], "width": 400, "height": 400}
    ).json()

    return thumb["url"]

url = create_product_image("red leather sneaker, product photography, white background")
print(f"Product ready: {url}")
Enter fullscreen mode Exit fullscreen mode

Conclusion

Background removal via REST API is one of the most practical image processing tasks to offload to a cloud service. IteraTools makes it trivially easy and affordable — especially for bulk e-commerce catalogs where premium services like Remove.bg would cost 50–100x more.

The real advantage: it's part of the same API toolkit as image generation, resizing, OCR, and more — so you can chain operations without juggling multiple API keys.

Try IteraTools rembg — 2¢ per image, no subscription.

Top comments (0)