REST API · Open Source SDKs · Live

Open Source API Example for Background Removal

The fastest way to learn a new API is a complete, runnable open source example. This page is that example — for removing backgrounds from images via a single REST call. $0.0025 per image. Transparent PNG back in under 3 seconds. All SDK code is MIT-licensed. 500 free credits, no credit card. Pick your language below and run it in 60 seconds.

MIT-licensed SDKs $0.0025 / image < 3s typical 500 free credits No credit card 6 languages
Get an API key (free) Quick start See pricing API docs

Open source API example — 6 languages

Sign up, copy your key from the dashboard, and run one of the examples below. The endpoint accepts a multipart/form-data upload or a public image_url, then returns a generation_id. Poll GET /v1/image/{id} until status=completed and download the transparent PNG from output_url. All SDK clients handle the polling loop for you.

# Step 1 — submit the image
curl -X POST https://api.pixelapi.dev/v1/image/remove-background \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "[email protected]"
# {"generation_id": "a1b2c3d4", "status": "queued"}

# Step 2 — poll until completed (usually < 3s)
curl https://api.pixelapi.dev/v1/image/a1b2c3d4 \
  -H "Authorization: Bearer YOUR_API_KEY"
# {"status": "completed", "output_url": "https://cdn.pixelapi.dev/..."}

# Step 3 — download the transparent PNG
curl -o cutout.png "$(curl -s ... | jq -r .output_url)"
# MIT-licensed open source SDK: https://github.com/pixelapi/pixelapi-python
pip install pixelapi
---
import os
from pixelapi import PixelAPI

client = PixelAPI(api_key=os.environ["PIXELAPI_KEY"])

# Remove background — polling handled automatically
result = client.remove_background(image="product.jpg")
result.save("product_cutout.png") # transparent PNG
print("Done:", result.output_url)

# Optional: webhook instead of polling
result = client.remove_background(
    image="product.jpg",
    webhook_url="https://yourapp.example/webhooks/pixelapi"
)

# Optional: get just the alpha mask
result = client.remove_background(image="product.jpg", return_mask=True)
result.save("product_mask.png")
# MIT-licensed open source SDK: https://github.com/pixelapi/pixelapi-js
npm install pixelapi
---
import { PixelAPI } from "pixelapi";
import { writeFileSync } from "fs";

const client = new PixelAPI({ apiKey: process.env.PIXELAPI_KEY });

// Remove background — polling handled automatically
const result = await client.removeBackground({ image: "./product.jpg" });
await result.save("product_cutout.png"); // transparent PNG
console.log("Done:", result.outputUrl);

// Optional: pass a public URL
const result2 = await client.removeBackground({
  imageUrl: "https://example.com/shoe.jpg",
  outputFormat: "webp" // PNG | JPG | WebP
});
await result2.save("shoe_cutout.webp");
# MIT-licensed open source SDK: https://github.com/pixelapi/pixelapi-php
composer require pixelapi/pixelapi
---
<?php
use PixelAPI\Client;

$client = new Client(getenv("PIXELAPI_KEY"));

// Remove background
$result = $client->removeBackground(["image" => "product.jpg"]);
file_put_contents("product_cutout.png", $result->getBody());

// With a solid white background (JPEG output)
$result2 = $client->removeBackground([
    "image" => "product.jpg",
    "output_format" => "jpeg",
    "bg_color" => "#ffffff"
]);
file_put_contents("product_white_bg.jpg", $result2->getBody());
# MIT-licensed open source SDK: https://github.com/pixelapi/pixelapi-ruby
gem install pixelapi
---
require "pixelapi"

client = PixelAPI::Client.new(api_key: ENV["PIXELAPI_KEY"])

# Remove background — polling handled automatically
result = client.remove_background(image: "product.jpg")
File.binwrite("product_cutout.png", result.body)
puts "Done: #{result.output_url}"

# Return just the mask for compositing
mask = client.remove_background(image: "product.jpg", return_mask: true)
File.binwrite("product_mask.png", mask.body)
# MIT-licensed open source SDK: https://github.com/pixelapi/pixelapi-go
go get github.com/pixelapi/pixelapi-go
---
package main

import (
    "fmt"
    "os"
    pixelapi "github.com/pixelapi/pixelapi-go"
)

func main() {
    client := pixelapi.New(os.Getenv("PIXELAPI_KEY"))

    // Remove background — polling handled automatically
    result, err := client.RemoveBackground("product.jpg")
    if err != nil {
        panic(err)
    }
    result.Save("product_cutout.png")
    fmt.Println("Done:", result.OutputURL)
}

How the open source API example works

Every example above follows the same three-step pattern:

  1. POST your image to https://api.pixelapi.dev/v1/image/remove-background — multipart upload or JSON with image_url.
  2. Receive a generation_id and a status of queued or processing.
  3. GET /v1/image/{generation_id} until status=completed, then download from output_url.

The SDK clients wrap steps 2–3 into a single blocking call with exponential backoff. For high-throughput pipelines, pass webhook_url and skip polling entirely — PixelAPI will POST the completed result to your endpoint.

Pricing — half the cost of Photoroom

ProviderFree tierPer-image costOpen source SDK?
PixelAPI 500 credits, no card $0.0025 ✓ MIT-licensed
Photoroom10/mo$0.020 (Basic API)Closed
remove.bg50/mosee remove.bg/pricingClosed
Clipdrop100 (one-time)see clipdrop.co/pricingClosed
cutout.proLimitedsee cutout.pro/pricingClosed
pixelcut / pixaLimitedsee pixa.com/pricingClosed

Photoroom price verified from photoroom.com/api/pricing (May 2026). Other rivals' API prices were not publicly accessible at time of writing — see their pricing pages directly. PixelAPI's per-image price is set at exactly half the cheapest verifiable commercial rival per our pricing principle.

What you get back

Transparent PNG (default)

Alpha channel preserves hair, glass, fur, and lace edges. Works straight into Figma, Shopify, Photoshop, Canva. Pass output_format=png or omit the param.

JPG with solid color

Add output_format=jpeg&bg_color=#ffffff for studio-white marketplace shots. Any hex is accepted.

WebP

Same alpha quality, ~30% smaller file. Pass output_format=webp. Ideal for web-delivery pipelines.

Binary mask only

Pass return_mask=true to receive a grayscale alpha mask — white = foreground. Use for custom compositing in your own renderer.

Full request parameters

ParameterTypeDescription
imagefileMultipart file upload (JPEG, PNG, WebP, BMP, up to 50 MP)
image_urlstringPublic URL of the image — alternative to file upload
output_formatstringpng (default) · jpeg · webp
bg_colorstringHex background for JPEG output, e.g. #ffffff
return_maskboolReturn the alpha mask instead of the composited cutout
webhook_urlstringPOST the result JSON here instead of requiring polling

Common workflows using this open source example

The background removal API underpins a wide range of production image workflows:

E-commerce product photos

Automate studio-white background cuts on hundreds of SKUs. Plug the API into your Shopify webhook pipeline.

Headshot & portrait apps

Build a self-service tool: user uploads a photo, API returns a professional cutout in seconds.

Real estate listings

Batch-process exterior shots. Replace messy backgrounds with clean skies or solid white.

Fashion & eyewear

Preserve reflective edges on glasses and glossy materials — pixel-accurate alpha on every frame.

Marketing agencies

Bulk-process client product catalogs without touching Photoshop. Export straight to Canva or Figma.

Food delivery apps

Cut menu-item photos onto transparent backgrounds for layered app UI cards.

Browse all use cases: industry guides →

Integrations & SDKs

Plug the open source example into your existing stack:

Shopify

Bulk-process product images on upload via webhook.

Zapier

No-code workflow trigger with one click.

Make.com

Drag-and-drop background removal in Make scenarios.

Webflow

CMS auto-cutout for product detail pages.

Next.js

Server-side API route pattern — ready to copy.

Magento

Adobe Commerce / Magento 2 plugin pattern.

Comparison vs alternatives

vs remove.bg

Open source SDKs vs closed client. Webhook support. PNG/JPG/WebP/mask vs PNG/JPG only.

vs Photoroom

2× cheaper per image at $0.01 vs $0.02. MIT-licensed SDK vs proprietary client.

vs Replicate

Flat $0.0025/image vs per-second compute billing. Predictable cost for bulk jobs.

vs Clipdrop

Public per-image pricing vs contact-sales model. Open source SDK vs closed API.

Rate limits & error handling

Default rate limits: 60 requests/minute on the free tier, 600 requests/minute on paid tiers. Need more? Email [email protected] with your expected volume.

When the limit is exceeded, the API returns HTTP 429 with a Retry-After header. Recommended strategy: exponential backoff starting at 2s, doubling on each retry up to 30s. The Python and Node.js SDKs implement this automatically.

# Python SDK — automatic retry on 429
from pixelapi import PixelAPI

client = PixelAPI(api_key="...", max_retries=4) # 4 retries with backoff
result = client.remove_background(image="bulk.jpg")

# Node.js SDK — same behavior
const client = new PixelAPI({ apiKey: "...", maxRetries: 4 });
const result = await client.removeBackground({ image: "./bulk.jpg" });

Common HTTP error codes:

CodeMeaningAction
400Bad request — unsupported format or missing paramsCheck the image format and required fields
401Unauthorized — invalid or missing API keyVerify Authorization: Bearer YOUR_KEY header
402Payment required — credits exhaustedTop up at pixelapi.dev/app or add auto_recharge=true
413Payload too large — image exceeds 50 MPDownscale input or use image_url for large files
429Rate limitedRetry after Retry-After seconds with backoff
500Internal errorRetry once; if persistent, email [email protected]

If a completed job has a blank or corrupted output, the job is flagged by the output-quality layer and credits are auto-refunded — you never pay for a broken result.

Frequently asked questions

What is an open source API example for background removal?

A complete, runnable code sample that shows how to call a background-removal REST API and get back a transparent PNG — with no black-box SDK required. PixelAPI publishes MIT-licensed client libraries for Python, Node.js, PHP, Ruby, and Go so you can read, fork, and contribute to the integration code alongside the raw HTTP examples on this page.

How do I use the API for free?

Sign up at pixelapi.dev/app — no credit card required. You receive 500 free credits on signup. Each background removal call costs 10 credits ($0.0025). That gives you 50 free removals to validate on real data before paying anything.

Which programming languages have open source examples?

cURL (raw HTTP), Python (pip install pixelapi), Node.js / TypeScript (npm install pixelapi), PHP (Composer), Ruby (Gem), and Go (go get). All SDK source is MIT-licensed on GitHub — fork it, adapt it, embed it in your product.

What does the API cost after the free tier?

$0.01 per image — exactly half the price of Photoroom's Basic API tier ($0.02). There are no subscriptions or monthly minimums; you only pay for successful completions. Failed or rejected jobs are auto-refunded.

What does the API return?

A transparent PNG with a clean alpha channel by default. You can also request JPG with a solid background color (any hex), WebP for ~30% smaller file sizes, or just the binary cutout mask for compositing pipelines. All formats are available via the output_url field in the completed job response.

What image formats are supported as input?

JPEG, PNG, WebP, and BMP. Images up to 50 megapixels are supported. You can POST the file as multipart/form-data or pass a public URL via the image_url parameter — useful when the image is already in cloud storage.

Can I use this in a commercial project?

Yes. The SDK code is MIT-licensed — use it in any commercial product, SaaS, or internal tool. The API itself is a commercial service billed per image processed, with no restriction on what you build with the output.

How do I handle rate limits and errors?

HTTP 429 with a Retry-After header when you exceed 60 req/min (free) or 600 req/min (paid). The Python and Node.js SDKs handle retry-with-backoff automatically (set max_retries=4). For raw HTTP, implement exponential backoff: start at 2s, double up to 30s.

Is there a webhook option instead of polling?

Yes. Pass a webhook_url in your POST request. When the job completes, PixelAPI POSTs the full result JSON (including output_url) to your endpoint — no polling loop needed. This is the recommended pattern for batch pipelines and serverless functions.

Can I get the cutout mask instead of the full composited image?

Yes — add return_mask=true to your request. The response includes a mask_url pointing to a grayscale PNG where white = foreground, black = background. Use this to composite the subject onto any background in your own rendering pipeline.

Start free — 500 credits, no card Read full API docs Compare all plans