---
title: "Bulk AI product photos with the Herofab API (Python) | Herofab"
description: "A Python script that turns a folder of product photos into finished images with the Herofab batch API: uploads, batches of 100, retries, downloads."
url: https://herofab.app/api/guides/bulk-product-photos
language: en
updated: 2026-11-06
---

# Bulk product photos with one script

This Python script sends a whole folder of product photos through one Herofab tool: it uploads each photo, creates batches of up to 100 jobs, waits for them and saves every finished image under the photo's own name. A ledger file keeps the job ids, so running it again only processes new photos and never pays twice.

- Python 3.9+ and requests
- Batches of 100 jobs
- Safe to run again

## Four steps, all from the public API

### Upload

Each photo goes to POST /api/v1/assets as multipart form data (JPEG, PNG or WebP, up to 25 MB). A photo the checks refuse is skipped with the reason.

### Batch

Up to 100 uploads become one POST /api/v1/batches request. It is all or nothing: if the credits do not cover every job, no job is created and the script stops.

### Wait

GET /api/v1/batches/{id} reports done when no job is left running. A batch.completed webhook can replace the polling loop.

### Save

Each succeeded job's image is downloaded and saved with the photo's file name; a failed job prints its failure code and its credits are returned.

## herofab\_bulk.py

Change TOOL, ROLE and PARAMS to use another tool; each API reference page lists the role and the settings. The Idempotency-Key is a hash of the batch body, so a repeated request returns the batch that already exists instead of a second one.

```
"""Herofab bulk product photos: a folder of product photos in, one finished image per photo out.

pip install requests
HEROFAB_API_KEY=hf_sk_live_... python herofab_bulk.py ./photos ./results
"""
import hashlib, json, os, pathlib, sys, time
import requests

API = "https://app.herofab.app/api/v1"
AUTH = {"Authorization": f"Bearer {os.environ['HEROFAB_API_KEY']}"}
TOOL, ROLE = "ghost_mannequin", "garment"          # the tool and its required input role
PARAMS = {"style": "3d", "backdrop": "white", "aspect_ratio": "1:1"}
CHUNK = 100                                         # POST /batches takes up to 100 jobs

def call(method, path, headers=None, **kw):
    """One API call; waits on 429 (rate limit) and 503 (upload slot busy) as Retry-After says."""
    while True:
        r = requests.request(method, API + path, headers={**AUTH, **(headers or {})}, timeout=120, **kw)
        if r.status_code not in (429, 503):
            return r
        time.sleep(int(r.headers.get("Retry-After", "5")))

src, out = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2])
out.mkdir(exist_ok=True)
ledger = out / "herofab-jobs.json"                  # photo name -> job id: a re-run never pays twice
state = json.loads(ledger.read_text()) if ledger.exists() else {"jobs": {}, "batches": []}
photos = [p for p in sorted(src.iterdir()) if p.suffix.lower() in (".jpg", ".jpeg", ".png", ".webp")]
todo = [p for p in photos if p.name not in state["jobs"]]

for start in range(0, len(todo), CHUNK):
    items, names = [], []
    for photo in todo[start:start + CHUNK]:
        r = call("POST", "/assets", files={"file": (photo.name, photo.read_bytes())})
        asset = r.json()
        if r.status_code != 201 or asset.get("state") != "stored":
            print(f"skipped {photo.name}: {asset.get('rejection') or asset.get('error')}")
            continue
        items.append({"inputs": {ROLE: asset["id"]}, "params": PARAMS})
        names.append(photo.name)
    if not items:
        continue
    body = {"tool": TOOL, "items": items}
    key = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()  # same body, same key
    r = call("POST", "/batches", json=body, headers={"Idempotency-Key": key})
    if r.status_code >= 400:
        sys.exit(r.json()["error"])                 # e.g. insufficient_credit: nothing was reserved
    batch = r.json()
    for name, job in zip(names, batch["jobs"]):     # jobs come back in item order
        state["jobs"][name] = job["id"]
    state["batches"].append(batch["id"])
    ledger.write_text(json.dumps(state, indent=1))
    print(f"batch {batch['id']}: {batch['total']} jobs, {batch['credits_reserved']} credits held")

names = {job_id: name for name, job_id in state["jobs"].items()}
for batch_id in state["batches"]:
    while not (batch := call("GET", f"/batches/{batch_id}").json())["done"]:
        time.sleep(10)
    for job in batch["jobs"]:
        name = pathlib.Path(names.get(job["id"], job["id"])).stem
        if job["state"] != "succeeded":
            print(f"{name}: {job['failure']['code']} (credits returned)")
            continue
        output = job["outputs"][0]
        target = out / f"{name}.{output['content_type'].split('/')[1]}"
        if not target.exists():
            target.write_bytes(call("GET", f"/assets/{output['asset_id']}/content").content)
```

## Or download a batch as one ZIP, sized for a marketplace

GET /api/v1/batches/{id}/outputs.zip streams every finished image of a batch. platform fits each image to a channel's size without cropping and at no extra credit; format=jpg converts them to JPEG.

```
# Every finished image of one batch in a single ZIP, fitted to Amazon's 1,600 × 1,600 px and converted to JPEG
curl -L "https://app.herofab.app/api/v1/batches/BATCH_ID/outputs.zip?platform=amazon&format=jpg" \
  -H "Authorization: Bearer $HEROFAB_API_KEY" -o amazon.zip
```

| platform | Channel | Size (px) |
| --- | --- | --- |
| `amazon` | Amazon | 1,600 × 1,600 |
| `amazon_clothing` | Amazon (clothing) | 1,500 × 2,000 |
| `walmart` | Walmart | 2,200 × 2,200 |
| `ebay` | eBay | 1,600 × 1,600 |
| `etsy` | Etsy | 2,000 × 2,000 |
| `shopify` | Shopify | 2,048 × 2,048 |
| `google_shopping` | Google Shopping | 1,500 × 1,500 |
| `tiktok_shop` | TikTok Shop | 1,600 × 1,600 |
| `mercado_livre` | Mercado Livre | 1,200 × 1,200 |
| `shopee` | Shopee | 1,600 × 1,600 |
| `wayfair` | Wayfair | 2,000 × 2,000 |
| `faire` | Faire | 2,000 × 2,000 |
| `faire_apparel` | Faire (clothing) | 1,800 × 2,400 |
| `zalando` | Zalando | 1,801 × 2,600 |
| `about_you` | ABOUT YOU | 1,500 × 2,000 |
| `otto` | OTTO | 2,000 × 2,000 |
| `kaufland` | Kaufland | 2,048 × 2,048 |
| `bol` | bol | 2,000 × 2,000 |
| `galaxus` | Galaxus | 2,000 × 2,000 |
| `trendyol` | Trendyol | 1,200 × 1,800 |

Sizes: packages/tools/platforms.json, each with the channel's official source on its marketplace guide. Batch, ZIP and limit details: Herofab OpenAPI document, read 3 November 2026.

## Bulk script questions

**How many photos can one request take?**

A batch takes up to 100 jobs; the script splits a larger folder into several batches. vary is the other batch form: one photo, one setting with 2 to 10 values, one job per value.

**What does a batch of 100 cost?**

100 times the tool's credits, held when the batch is created and charged per delivered image; failed jobs return their credits. The ghost mannequin settings in the script cost 4 credits per image.

**Does it upload in parallel?**

No. Multipart uploads are taken one at a time per workspace and a second one gets 503 with Retry-After, which the script waits out. For very large files, the upload intent form of POST /api/v1/assets sends the bytes straight to storage.

Related

[Virtual try-on API](https://herofab.app/api/virtual-try-on) · [Marketplace image rules](https://herofab.app/guides/marketplace-image-rules) · [Webhooks](https://herofab.app/api/webhooks) · [Shopify product images](https://herofab.app/api/guides/shopify-product-images) · [WooCommerce product images](https://herofab.app/api/guides/woocommerce-product-images) · [API overview: upload, poll, download](https://herofab.app/api)
