Image API · Developer guide
Process images with one API call
Remove backgrounds, upscale images and generate images over HTTP. Send an image or a prompt, get a job ID straight away, and collect the result when it is ready, by polling or through a webhook.
- Base URL
https://api.imagepresto.com- Authentication
- Bearer API key (
ip_art_...) - Formats
- PNG, JPEG, WebP in · PNG, WebP or JPEG out
- Cost
- From 1 API credit per image (prices)
Open your API dashboardDownload OpenAPI JSONImage API overviewArtwork API guide
Quickstart
No Image Presto subscription required. Use the same API key and API credits as artwork checks. To try an operation without code, use the playground in the Image Jobs tab of the API dashboard.
- Create an API key in the API dashboard and store it as
ARTWORK_API_KEYon your server. - Buy API credits. Credits are reserved when a job is accepted and charged only when it completes.
- Submit a job with an
Idempotency-Key. You get a job ID right away. - Collect the result. Poll the job (or receive a webhook) and download each output from its signed link.
# 1. Submit. Credits are reserved and the job runs in the background.
curl https://api.imagepresto.com/api/v1/images/background-removals \
-H "Authorization: Bearer $ARTWORK_API_KEY" \
-H "Idempotency-Key: order-18422-cutout" \
-F "file=@product.jpg" -F "model=standard"
# 2. Poll until processing_status is "completed" or "failed".
curl https://api.imagepresto.com/api/v1/images/jobs/$JOB_ID \
-H "Authorization: Bearer $ARTWORK_API_KEY"
# 3. Download each output from its signed url (no key needed, valid 1 hour).
curl -o cutout.png "https://api.imagepresto.com$OUTPUT_URL"import os
import time
import uuid
import requests # pip install requests
BASE = "https://api.imagepresto.com"
HEADERS = {"Authorization": f"Bearer {os.environ['ARTWORK_API_KEY']}"}
# 1. Submit. Save the key first: retrying with the same key never charges twice.
idempotency_key = str(uuid.uuid4())
with open("product.jpg", "rb") as image:
response = requests.post(
f"{BASE}/api/v1/images/background-removals",
headers={**HEADERS, "Idempotency-Key": idempotency_key},
files={"file": image},
data={"model": "standard"},
timeout=60,
)
response.raise_for_status()
job_url = BASE + response.json()["job_url"]
# 2. Poll until the job finishes.
for _ in range(120):
job = requests.get(job_url, headers=HEADERS, timeout=30).json()
if job["processing_status"] in ("completed", "failed"):
break
time.sleep(3)
# 3. Save the results through their signed links.
if job["processing_status"] == "completed":
for output in job["outputs"]:
image = requests.get(BASE + output["url"], timeout=60)
image.raise_for_status()
with open(f"cutout-{output['index']}.png", "wb") as file:
file.write(image.content)
print("Charged", job["charged_credits"], "credit(s)")
else:
print("Job failed:", job["error_code"])// Node.js 22+ (built-in fetch and FormData). Save as cutout.mjs
import { randomUUID } from "node:crypto";
import { openAsBlob, writeFileSync } from "node:fs";
const BASE = "https://api.imagepresto.com";
const headers = { Authorization: `Bearer ${process.env.ARTWORK_API_KEY}` };
async function call(url, init) {
const response = await fetch(url, init);
const body = await response.json();
if (!response.ok) {
throw new Error(`${response.status} ${body.error?.code} (request ${body.request_id})`);
}
return body;
}
// 1. Submit. Save the key first: retrying with the same key never charges twice.
const form = new FormData();
form.set("file", await openAsBlob("product.jpg"), "product.jpg");
form.set("model", "standard");
const accepted = await call(`${BASE}/api/v1/images/background-removals`, {
method: "POST",
headers: { ...headers, "Idempotency-Key": randomUUID() },
body: form,
});
// 2. Poll until the job finishes.
let job;
for (let attempt = 0; attempt < 120; attempt++) {
job = await call(BASE + accepted.job_url, { headers });
if (["completed", "failed"].includes(job.processing_status)) break;
await new Promise((resolve) => setTimeout(resolve, 3000));
}
// 3. Save the results through their signed links.
if (job.processing_status === "completed") {
for (const output of job.outputs) {
const image = await fetch(BASE + output.url);
writeFileSync(`cutout-${output.index}.png`, Buffer.from(await image.arrayBuffer()));
}
console.log("Charged", job.charged_credits, "credit(s)");
} else {
console.log("Job failed:", job.error_code);
}Authentication
Send your API key in the Authorization header on every request, over HTTPS:
Authorization: Bearer ip_art_your_key_here- Keys belong to one account and see only that account's jobs. The same keys work for artwork checks.
- Call the API from your server. Never put a key in a browser, a mobile app, a URL or a repository. Keys in query strings are rejected.
- Signed result links (
outputs[].url) need no key, so you can hand them to a browser for up to an hour.
Endpoints
Remove a background
POST/api/v1/images/background-removals
Upload a file as multipart/form-data, or send JSON with an image_url. The result is a transparent PNG or WebP.
| Name | Type | Description |
|---|---|---|
Idempotency-Keyrequired | string | Your unique ID for this job: 1–200 visible ASCII characters. See Idempotency and retries. |
X-Image-Input-Hash | string | Optional. The input_hash from a price quote; send it with X-Image-Expected-Credits. |
X-Image-Expected-Credits | integer | Optional. The credits you agreed to. A mismatch returns 409 quote_changed and nothing is reserved. |
| Name | Type | Description |
|---|---|---|
file | file | PNG, JPEG or WebP up to 25 MiB and 40 megapixels. Use this or image_url. |
image_url | string | JSON only. A public https:// URL, fetched once by Image Presto. The URL is not stored. |
model | string | standard (default, 1 credit), detailed (finer edges, 2 credits) or bria (Bria RMBG 3, trained on licensed images, 3 credits). |
output_format | string | png (default) or webp. |
prompt | string | Optional, bria only. Up to 300 characters describing what the cutout should keep or drop, for example only the chair or the person without the lamp. Leave it out for the main subject. Same price. Sending it with another model returns 422. |
printf 'Authorization: Bearer %s\n' "$ARTWORK_API_KEY" | curl --silent --show-error \
--header @- --header 'Idempotency-Key: order-18422-cutout' \
--form 'file=@/absolute/path/product.jpg' --form model=standard --form output_format=png \
"https://api.imagepresto.com/api/v1/images/background-removals"printf 'Authorization: Bearer %s\n' "$ARTWORK_API_KEY" | curl --silent --show-error \
--header @- --header 'Idempotency-Key: order-18422-cutout' \
--header 'Content-Type: application/json' \
--data '{"image_url": "https://cdn.example.com/product.jpg", "model": "bria"}' \
"https://api.imagepresto.com/api/v1/images/background-removals"{
"id": "7c1d0f0e-2b9a-4b56-9d62-2f0f3f6a8a11",
"operation": "background_removal",
"processing_status": "queued",
"reserved_credits": 1,
"job_url": "/api/v1/images/jobs/7c1d0f0e-2b9a-4b56-9d62-2f0f3f6a8a11"
}Upscale an image
POST/api/v1/images/upscales
Enlarges a PNG, JPEG or WebP image. Same headers, file or image_url input and response as background removal.
| Name | Type | Description |
|---|---|---|
file / image_url | file or string | PNG, JPEG or WebP up to 25 MiB and 12 megapixels. |
model | string | universal (default; 1–6x, keeps transparency) or print (Topaz, 1–4x, for print files). |
scale | number | Upscale factor with up to 2 decimals. Default 2. |
content | string | Print only: cgi (art and graphics, default), text (text and logos), photo, photo_hifi. |
output_format | string | png (default), webp or jpeg (JPEG has no transparency). |
The result is at most 12 megapixels and 6144 px on its longest side. A print upscale of a transparent image takes up to 1.5 megapixels and keeps its transparency.
printf 'Authorization: Bearer %s\n' "$ARTWORK_API_KEY" | curl --silent --show-error \
--header @- --header 'Idempotency-Key: order-18422-upscale' \
--form 'file=@/absolute/path/logo.png' --form model=print --form content=text --form scale=4 \
"https://api.imagepresto.com/api/v1/images/upscales"Generate an image
POST/api/v1/images/generations
Creates images from a text prompt with Z-Image Turbo. Send JSON with the same headers as the other operations. Credits are reserved per requested image; images withheld by the safety filter are not charged, and a job whose images are all withheld fails with content_blocked.
| Name | Type | Description |
|---|---|---|
promptrequired | string | 1–4000 characters. Kept only until the job finishes; never returned or stored with the job. |
width, height | integer | 256–2048 px, multiples of 64. Default 1024 × 1024. |
num_images | integer | 1–4. Default 1. Each delivered image costs 1 credit. |
seed | integer | Optional, 0–2147483647. The seed used is returned in result.seed. |
expand_prompt | boolean | Optional. Let the model add detail to a short prompt. |
output_format | string | png (default), jpeg or webp. |
The provider's safety filter is always on. A completed job lists only the delivered images; result.delivered and result.blocked give the counts and charged_credits the amount charged.
printf 'Authorization: Bearer %s\n' "$ARTWORK_API_KEY" | curl --silent --show-error \
--header @- --header 'Idempotency-Key: campaign-7-hero' \
--header 'Content-Type: application/json' \
--data '{"prompt": "a lighthouse at dusk, oil painting", "width": 1280, "height": 768, "num_images": 2}' \
"https://api.imagepresto.com/api/v1/images/generations"Get a price
POST/api/v1/images/<operation>/quote
Same body as the submission, no Idempotency-Key, no charge. Returns credits, tariff_version and input_hash. To lock the price, send the same file and options with X-Image-Input-Hash and X-Image-Expected-Credits.
/api/v1/images/background-removals/quote/api/v1/images/upscales/quote/api/v1/images/generations/quote
Retrieve a job
GET/api/v1/images/jobs/{id}
Poll every few seconds while processing_status is queued or running, backing off to about 10 seconds. completed and failed are final. A failed job has an error_code and is not charged. Instead of polling, you can add a webhook and receive image_job.completed or image_job.failed.
{
"id": "7c1d0f0e-2b9a-4b56-9d62-2f0f3f6a8a11",
"operation": "background_removal",
"processing_status": "completed",
"reserved_credits": 1,
"charged_credits": 1,
"reservation_status": "settled",
"options": {"model": "standard", "output_format": "png", "source": "upload"},
"outputs": [{
"index": 0,
"url": "/api/v1/images/outputs/eyJrZXki...c3f1",
"url_expires_at": "2026-12-01T15:04:05Z",
"download_url": "/api/v1/images/jobs/7c1d0f0e-2b9a-4b56-9d62-2f0f3f6a8a11/outputs/0",
"width": 2048, "height": 1365,
"content_type": "image/png", "bytes": 3145728
}],
"outputs_expire_at": "2026-12-02T14:04:05Z",
"error_code": null
}Download results
Each output has two download paths, relative to https://api.imagepresto.com:
urlis a signed link that needs no API key, valid untilurl_expires_at(at most one hour). Read the job again for a fresh link.download_urlneeds your API key in theAuthorizationheader.
List jobs
GET/api/v1/images/jobs
Newest first. Filters: operation, status, key_id, created_after, created_before, limit (1–100) and the returned cursor. Artwork checks are listed separately at /api/v1/artwork-checks.
OpenAPI schema
GET/api/v1/images/openapi.json
The machine-readable contract for these endpoints. No key needed. Download OpenAPI JSON.
Guides
Prices and credits
Credits are reserved when a job is accepted, charged when it completes and released if it fails. A quote is always free.
| Operation | Option | Credits |
|---|---|---|
| Background removal | Standard (standard) | 1 per image |
| Background removal | Detailed (detailed) | 2 per image |
| Background removal | Bria RMBG 3 (bria) | 3 per image |
| Upscale | Universal upscaler (universal) | 1 per image |
| Upscale | Print upscaler (print) | 3 per image |
| Image generation | Z-Image Turbo (z-image-turbo) | 1 per generated image |
Idempotency and retries
The Idempotency-Key header makes submitting safe to retry. If a request times out, send it again with the same key:
- Same key, same input: you get the original job back, even if it has already finished. You are never charged twice.
- Same key, different input:
409 idempotency_conflict. Keys share one namespace with artwork checks. - Retry
429and503after theRetry-Afterheader. Do not retry other 4xx errors unchanged.
Errors and limits
Errors use one envelope: {"error": {"code", "message"}, "request_id"}, and every response carries an X-Request-ID header.
| Status | Code | Meaning |
|---|---|---|
| 402 | insufficient_credits | Not enough API credits. Buy a pack in the dashboard; nothing was reserved. |
| 403 | spending_paused | API spending is paused for this account. |
| 403 | operation_unavailable | This operation is not open to your account yet. |
| 409 | idempotency_conflict | The Idempotency-Key was already used with a different file, URL or options. |
| 409 | quote_changed | X-Image-Input-Hash / X-Image-Expected-Credits do not match this request. |
| 413 | payload_too_large | The file is larger than 25 MiB. |
| 422 | unsupported_image | Not a PNG, JPEG or WebP image, or larger than 40 megapixels. |
| 422 | upscale_limit | Upscale input over 12 megapixels, output over 12 megapixels or 6144 px per side, or a transparent print upscale over 1.5 megapixels. |
| 422 | image_url_unavailable | The image_url could not be fetched as a public HTTPS image. |
| 429 | active_limit | Five image jobs are already in progress. Retry after Retry-After seconds. |
| 429 | rate_limited | More than 30 submissions per minute for this operation. |
provider_failed | The image service refused or failed the request. |
|---|---|
provider_timeout | The image service did not finish within 15 minutes. |
provider_output_invalid | The image service returned no usable image. |
content_blocked | The safety filter withheld every result. |
input_expired | The job could not start within 24 hours. |
input_unsupported | The stored input could not be processed. |
retries_exhausted | Processing failed three times. |
Limits: 30 submissions per minute per operation, 5 image jobs in progress per account, and 600 reads per minute shared with artwork checks. Signed result links have their own, larger budget.
Data retention
| Data | Kept for |
|---|---|
| Uploaded image, fetched image_url or prompt | Until the job finishes (at most 24 hours if it never runs) |
| Results | 24 hours after the job completes |
| Job record (status, options, credits) | Kept for your history; never the image, URL or prompt |
Jobs run on a third-party GPU model host. Image Presto sends it only the input the job needs, and keeps no copy after the job ends.
Example clients
Command-line clients for Python 3.10+ and Node.js 22+, with no packages to install. Each submits one job with your ARTWORK_IDEMPOTENCY_KEY, retries lost responses with the same key, polls until the job is final and saves the results through their signed links. Each new key spends credits.
export ARTWORK_API_KEY='ip_art_your_key_here'
export ARTWORK_API_BASE_URL='https://api.imagepresto.com'
export ARTWORK_IDEMPOTENCY_KEY='order-18422-cutout'
python3 image_job.py background-removal product.jpg ./results model=bria
python3 image_job.py upscale logo.png ./results model=print scale=4 content=text
python3 image_job.py generation prompt.txt ./results num_images=2 width=1280 height=768View image_job.py source
#!/usr/bin/env python3
"""Image API example client (Python 3.10+ standard library only).
Submits one image job, polls it to a final state and saves the results.
POST spends API credits; polling and downloads do not.
python3 image_job.py background-removal IMAGE OUT_DIR [model=bria] [output_format=webp]
python3 image_job.py upscale IMAGE OUT_DIR [model=print] [scale=4] [content=text] [output_format=png]
python3 image_job.py generation PROMPT_FILE OUT_DIR [width=1280] [height=768] [num_images=2] [seed=7]
Environment: ARTWORK_API_KEY (the same ip_art_ key as artwork checks),
ARTWORK_API_BASE_URL (HTTPS origin, no path) and ARTWORK_IDEMPOTENCY_KEY
(persist it before running; reuse the same value and inputs after a timeout).
Bounded: at most 5 attempts per request, a shared 15-minute budget, waits
capped at 10 seconds unless Retry-After asks for longer, no redirects.
Exit codes: 0 completed, 2 job failed, 1 request or usage error. Prints only
the job ID, status, credits, error codes, request IDs and saved file paths.
"""
import email.utils
import json
import os
from pathlib import Path
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
ROUTES = {'background-removal': ('background-removals', 'background_removal'),
'upscale': ('upscales', 'upscale'), 'generation': ('generations', 'image_generation')}
INTEGER_FIELDS = {'width', 'height', 'num_images', 'seed'}
EXTENSIONS = {'image/png': 'png', 'image/webp': 'webp', 'image/jpeg': 'jpg'}
BUDGET_SECONDS = 15 * 60
MAX_DOWNLOAD = 64 * 1024 * 1024
class Stop(Exception):
pass
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None
OPENER = urllib.request.build_opener(NoRedirect)
def settings():
key = os.environ.get('ARTWORK_API_KEY', '')
base = os.environ.get('ARTWORK_API_BASE_URL', '')
idem = os.environ.get('ARTWORK_IDEMPOTENCY_KEY', '')
if not re.fullmatch(r'ip_art_[A-Za-z0-9_-]{8,}', key):
raise Stop('Set ARTWORK_API_KEY to your ip_art_ API key')
parsed = urllib.parse.urlsplit(base)
loopback = parsed.hostname in ('127.0.0.1', 'localhost', '::1')
if parsed.scheme not in ('https', 'http') or (parsed.scheme == 'http' and not loopback) or \
parsed.path not in ('', '/') or parsed.query or parsed.fragment or parsed.username:
raise Stop('ARTWORK_API_BASE_URL must be an https:// origin with no path')
if not re.fullmatch(r'[\x21-\x7e]{1,200}', idem):
raise Stop('Set ARTWORK_IDEMPOTENCY_KEY to 1-200 visible ASCII characters and keep it for retries')
return key, base.rstrip('/'), idem
def multipart(raw, fields):
boundary = uuid.uuid4().hex
parts = []
for name, value in fields.items():
parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode())
parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="image"\r\n'
'Content-Type: application/octet-stream\r\n\r\n'.encode() + raw + b'\r\n')
parts.append(f'--{boundary}--\r\n'.encode())
return b''.join(parts), f'multipart/form-data; boundary={boundary}'
def retry_after(headers, attempt):
value = headers.get('Retry-After') if headers else None
if value:
if value.isdigit():
return int(value)
try:
return max(0, email.utils.parsedate_to_datetime(value).timestamp() - time.time())
except (TypeError, ValueError):
pass
return min(10, 2 ** attempt)
def request(method, url, deadline, *, key=None, body=None, headers=None, raw=False):
"""One logical request with bounded retries on connection loss, 429 and 5xx."""
for attempt in range(5):
wait = None
try:
req = urllib.request.Request(url, data=body, method=method, headers=dict(headers or {}))
if key:
req.add_header('Authorization', 'Bearer ' + key)
with OPENER.open(req, timeout=20) as response:
data = response.read(MAX_DOWNLOAD + 1)
if len(data) > MAX_DOWNLOAD:
raise Stop('Response too large')
return (data, response.headers.get('Content-Type', '')) if raw else json.loads(data)
except urllib.error.HTTPError as error:
if 300 <= error.code < 400:
raise Stop('Redirect refused') from None
if error.code != 429 and error.code < 500:
code, request_id = 'http_%d' % error.code, None
try:
payload = json.loads(error.read(65536))
code = payload['error']['code'] if re.fullmatch(r'[a-z_]{1,64}', payload['error']['code']) else code
request_id = payload.get('request_id') if re.fullmatch(r'[0-9a-f-]{36}', payload.get('request_id', '')) else None
except Exception:
pass
raise Stop(f'HTTP {error.code} {code}' + (f' request_id={request_id}' if request_id else '')) from None
wait = retry_after(error.headers, attempt)
except (urllib.error.URLError, TimeoutError, ConnectionError, json.JSONDecodeError):
wait = min(10, 2 ** attempt) # response lost: retry with the SAME idempotency key
if attempt == 4 or time.monotonic() + wait > deadline:
raise Stop('Gave up retrying; rerun later with the same ARTWORK_IDEMPOTENCY_KEY')
time.sleep(wait)
def main(argv):
if len(argv) < 3 or argv[0] not in ROUTES or any('=' not in extra for extra in argv[3:]):
raise Stop(__doc__.split('\n\n')[1])
command, source, out_dir = argv[0], Path(argv[1]), Path(argv[2])
key, base, idem = settings()
path, _ = ROUTES[command]
fields = dict(extra.split('=', 1) for extra in argv[3:])
out_dir.mkdir(parents=True, exist_ok=True)
deadline = time.monotonic() + BUDGET_SECONDS
headers = {'Idempotency-Key': idem}
if command == 'generation':
body = {name: int(value) if name in INTEGER_FIELDS else value for name, value in fields.items()}
body['prompt'] = source.read_text(encoding='utf-8').strip()
data, headers['Content-Type'] = json.dumps(body).encode(), 'application/json'
else:
data, headers['Content-Type'] = multipart(source.read_bytes(), fields)
job = request('POST', f'{base}/api/v1/images/{path}', deadline, key=key, body=data, headers=headers)
job_id = job['id']
if not re.fullmatch(r'[0-9a-f-]{36}', job_id):
raise Stop('Unexpected response')
print(json.dumps({'id': job_id, 'reserved_credits': job.get('reserved_credits')}), flush=True)
delay = 2
while True:
detail = request('GET', f'{base}/api/v1/images/jobs/{job_id}', deadline, key=key)
status = detail.get('processing_status')
if status in ('completed', 'failed'):
break
if time.monotonic() + delay > deadline:
raise Stop(f'Still {status}; resume polling job {job_id} later')
time.sleep(delay)
delay = min(10, delay * 2)
if status == 'failed':
print(json.dumps({'id': job_id, 'processing_status': 'failed', 'error_code': detail.get('error_code')}))
return 2
saved = []
for output in detail.get('outputs', [])[:8]:
url = output.get('url', '')
if not url.startswith('/api/v1/images/outputs/'):
raise Stop('Unexpected output link')
content, content_type = request('GET', base + url, deadline, raw=True) # signed link: no API key sent
extension = EXTENSIONS.get(content_type.split(';')[0].strip())
if extension is None or type(output.get('index')) is not int:
raise Stop('Unexpected output type')
target = out_dir / f'{job_id}-{output["index"]}.{extension}'
target.write_bytes(content)
saved.append(str(target))
print(json.dumps({'id': job_id, 'processing_status': 'completed', 'charged_credits': detail.get('charged_credits'),
'saved': saved}))
return 0
if __name__ == '__main__':
try:
sys.exit(main(sys.argv[1:]))
except Stop as stop:
print(str(stop), file=sys.stderr)
sys.exit(1)
except (OSError, ValueError, KeyError) as error:
print(f'Error: {type(error).__name__}', file=sys.stderr)
sys.exit(1)
View image_job.cjs source
#!/usr/bin/env node
// Image API example client (Node.js 22+, no packages).
//
// Submits one image job, polls it to a final state and saves the results.
// POST spends API credits; polling and downloads do not.
//
// node image_job.cjs background-removal IMAGE OUT_DIR [model=bria] [output_format=webp]
// node image_job.cjs upscale IMAGE OUT_DIR [model=print] [scale=4] [content=text] [output_format=png]
// node image_job.cjs generation PROMPT_FILE OUT_DIR [width=1280] [height=768] [num_images=2] [seed=7]
//
// Environment: ARTWORK_API_KEY (the same ip_art_ key as artwork checks),
// ARTWORK_API_BASE_URL (HTTPS origin, no path) and ARTWORK_IDEMPOTENCY_KEY
// (persist it before running; reuse the same value and inputs after a timeout).
//
// Bounded: at most 5 attempts per request, a shared 15-minute budget, waits
// capped at 10 seconds unless Retry-After asks for longer, no redirects.
// Exit codes: 0 completed, 2 job failed, 1 request or usage error. Prints only
// the job ID, status, credits, error codes, request IDs and saved file paths.
"use strict";
const fs = require("node:fs");
const path = require("node:path");
const ROUTES = { "background-removal": "background-removals", upscale: "upscales", generation: "generations" };
const INTEGER_FIELDS = new Set(["width", "height", "num_images", "seed"]);
const EXTENSIONS = { "image/png": "png", "image/webp": "webp", "image/jpeg": "jpg" };
const BUDGET_MS = 15 * 60 * 1000;
const MAX_DOWNLOAD = 64 * 1024 * 1024;
const USAGE = "node image_job.cjs background-removal|upscale|generation INPUT OUT_DIR [field=value ...]";
class Stop extends Error {}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function settings() {
const key = process.env.ARTWORK_API_KEY || "";
const base = process.env.ARTWORK_API_BASE_URL || "";
const idem = process.env.ARTWORK_IDEMPOTENCY_KEY || "";
if (!/^ip_art_[A-Za-z0-9_-]{8,}$/.test(key)) throw new Stop("Set ARTWORK_API_KEY to your ip_art_ API key");
let url;
try {
url = new URL(base);
} catch {
throw new Stop("ARTWORK_API_BASE_URL must be an https:// origin with no path");
}
const loopback = ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);
if (!(url.protocol === "https:" || (url.protocol === "http:" && loopback)) || url.pathname !== "/" || url.search || url.hash || url.username)
throw new Stop("ARTWORK_API_BASE_URL must be an https:// origin with no path");
if (!/^[\x21-\x7e]{1,200}$/.test(idem))
throw new Stop("Set ARTWORK_IDEMPOTENCY_KEY to 1-200 visible ASCII characters and keep it for retries");
return { key, base: url.origin, idem };
}
function retryAfter(response, attempt) {
const value = response?.headers.get("retry-after");
if (value && /^\d+$/.test(value)) return Number(value) * 1000;
if (value && Number.isFinite(Date.parse(value))) return Math.max(0, Date.parse(value) - Date.now());
return Math.min(10, 2 ** attempt) * 1000;
}
// One logical request with bounded retries on connection loss, 429 and 5xx.
async function request(method, url, deadline, { key, body, headers = {}, raw = false } = {}) {
for (let attempt = 0; attempt < 5; attempt++) {
let wait;
let response;
try {
response = await fetch(url, {
method, body, redirect: "manual", signal: AbortSignal.timeout(20000),
headers: { ...headers, ...(key ? { Authorization: "Bearer " + key } : {}) },
});
} catch {
response = null; // response lost: retry with the SAME idempotency key
}
if (response) {
if (response.status >= 300 && response.status < 400) throw new Stop("Redirect refused");
if (response.ok) {
const data = Buffer.from(await response.arrayBuffer());
if (data.length > MAX_DOWNLOAD) throw new Stop("Response too large");
if (raw) return { data, type: response.headers.get("content-type") || "" };
try {
return JSON.parse(data.toString("utf8"));
} catch {
response = null;
}
} else if (response.status !== 429 && response.status < 500) {
let code = "http_" + response.status;
let requestId = "";
try {
const payload = await response.json();
if (/^[a-z_]{1,64}$/.test(payload.error.code)) code = payload.error.code;
if (/^[0-9a-f-]{36}$/.test(payload.request_id)) requestId = " request_id=" + payload.request_id;
} catch {}
throw new Stop(`HTTP ${response.status} ${code}${requestId}`);
}
}
wait = response ? retryAfter(response, attempt) : Math.min(10, 2 ** attempt) * 1000;
if (attempt === 4 || Date.now() + wait > deadline)
throw new Stop("Gave up retrying; rerun later with the same ARTWORK_IDEMPOTENCY_KEY");
await sleep(wait);
}
}
async function main(argv) {
const [command, input, outDir, ...extras] = argv;
if (!ROUTES[command] || !input || !outDir || extras.some((e) => !e.includes("="))) throw new Stop(USAGE);
const { key, base, idem } = settings();
const fields = Object.fromEntries(extras.map((e) => [e.slice(0, e.indexOf("=")), e.slice(e.indexOf("=") + 1)]));
fs.mkdirSync(outDir, { recursive: true });
const deadline = Date.now() + BUDGET_MS;
let body;
const headers = { "Idempotency-Key": idem };
if (command === "generation") {
const json = Object.fromEntries(Object.entries(fields).map(([k, v]) => [k, INTEGER_FIELDS.has(k) ? Number(v) : v]));
json.prompt = fs.readFileSync(input, "utf8").trim();
body = JSON.stringify(json);
headers["Content-Type"] = "application/json";
} else {
body = new FormData();
for (const [name, value] of Object.entries(fields)) body.append(name, value);
body.append("file", new Blob([fs.readFileSync(input)]), "image");
}
const job = await request("POST", `${base}/api/v1/images/${ROUTES[command]}`, deadline, { key, body, headers });
if (!/^[0-9a-f-]{36}$/.test(job.id)) throw new Stop("Unexpected response");
console.log(JSON.stringify({ id: job.id, reserved_credits: job.reserved_credits }));
let delay = 2000;
let detail;
for (;;) {
detail = await request("GET", `${base}/api/v1/images/jobs/${job.id}`, deadline, { key });
if (["completed", "failed"].includes(detail.processing_status)) break;
if (Date.now() + delay > deadline) throw new Stop(`Still ${detail.processing_status}; resume polling job ${job.id} later`);
await sleep(delay);
delay = Math.min(10000, delay * 2);
}
if (detail.processing_status === "failed") {
console.log(JSON.stringify({ id: job.id, processing_status: "failed", error_code: detail.error_code }));
return 2;
}
const saved = [];
for (const output of (detail.outputs || []).slice(0, 8)) {
if (typeof output.url !== "string" || !output.url.startsWith("/api/v1/images/outputs/")) throw new Stop("Unexpected output link");
const { data, type } = await request("GET", base + output.url, deadline, { raw: true }); // signed link: no API key sent
const extension = EXTENSIONS[type.split(";")[0].trim()];
if (!extension || !Number.isInteger(output.index)) throw new Stop("Unexpected output type");
const target = path.join(outDir, `${job.id}-${output.index}.${extension}`);
fs.writeFileSync(target, data);
saved.push(target);
}
console.log(JSON.stringify({ id: job.id, processing_status: "completed", charged_credits: detail.charged_credits, saved }));
return 0;
}
main(process.argv.slice(2)).then(
(code) => process.exit(code),
(error) => {
console.error(error instanceof Stop ? error.message : "Error: " + (error?.name || "unknown"));
process.exit(1);
},
);
Webhooks
Instead of polling, add up to 3 HTTPS endpoints under Webhooks in your dashboard. Image Presto sends a signed POST with a JSON body each time an image job completes or fails. Each endpoint gets its own signing secret, shown once when you add it or rotate it.
| Name | Type | Description |
|---|---|---|
ImagePresto-Signature | string | t=<unix seconds>,v1=<hex HMAC-SHA256> of <t>.<raw body>. |
ImagePresto-Event-Id | uuid | Same as the body's id. Use it to ignore duplicates. |
ImagePresto-Event-Type | string | Same as the body's type. |
ImagePresto-Delivery-Id | uuid | Changes per endpoint; shown in your delivery history. |
Events
image_job.completed,image_job.failedwebhook.test, sent by Send test in the dashboard
The event carries the job summary, not the images. Fetch data.url with your API key for the full result. A failed job has an error_code and its credits are released.
{
"id": "3f1b8c9e-6a1d-4c58-9b0e-2d4f6a7c8e90",
"type": "image_job.completed",
"created_at": "2026-12-01T14:04:05.123Z",
"data": {
"id": "7c1d0f0e-2b9a-4b56-9d62-2f0f3f6a8a11",
"object": "image_job",
"operation": "background_removal",
"processing_status": "completed",
"source": "api",
"key_id": "0b6c...",
"reserved_credits": 1,
"charged_credits": 1,
"reservation_status": "settled",
"error_code": null,
"created_at": "2026-12-01T14:03:51.002Z",
"completed_at": "2026-12-01T14:04:05.120Z",
"url": "/api/v1/images/jobs/7c1d0f0e-2b9a-4b56-9d62-2f0f3f6a8a11"
}
}Verify signatures
Compute HMAC-SHA256 with your endpoint secret over the timestamp, a period and the exact raw body bytes, and compare it in constant time with v1. Reject timestamps more than 5 minutes old.
import hashlib, hmac, time
def verify(secret: str, header: str, body: bytes, tolerance: int = 300) -> bool:
"""body: the raw request bytes, before JSON parsing."""
try:
parts = dict(item.split("=", 1) for item in header.split(","))
timestamp = int(parts["t"])
except (ValueError, KeyError):
return False
if abs(time.time() - timestamp) > tolerance:
return False
expected = hmac.new(secret.encode(), f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, parts.get("v1", ""))const crypto = require("node:crypto");
// rawBody: the request body as a Buffer, before JSON parsing.
function verify(secret, header, rawBody, toleranceSeconds = 300) {
const parts = Object.fromEntries(header.split(",").map((p) => p.split("=", 2)));
const timestamp = Number(parts.t);
if (!Number.isInteger(timestamp) || Math.abs(Date.now() / 1000 - timestamp) > toleranceSeconds) return false;
const expected = crypto.createHmac("sha256", secret)
.update(Buffer.concat([Buffer.from(timestamp + "."), rawBody])).digest("hex");
const given = Buffer.from(parts.v1 || "", "utf8");
return given.length === expected.length && crypto.timingSafeEqual(given, Buffer.from(expected));
}Retries and rotation
A delivery that does not get a 2xx response is retried after 1, 5, 15 and 30 minutes, then 1, 2, 4 and 6 hours, for at most 10 attempts within 24 hours. Events can arrive more than once or out of order: use the event id and the job's completed_at. You can send a failed delivery again from the dashboard for 30 days.
Rotate secret takes effect immediately: every later delivery, including retries, is signed with the new secret. Deleting an endpoint cancels its pending deliveries.
Support
Email info@imagepresto.com with the request_id or job ID. Never send API keys, images or prompts by email. Balance, purchases, keys and image jobs are in the dashboard.