Skip to Content
Cheapest Imagen
Guides

Synchronous and asynchronous requests

Two ways to call the image API. Wait for the image in one request, or send async true, get a task id at once, and read one or many tasks with a single polling request or a webhook.

There are two ways to make an image. They take the same parameters, cost the same and share the same limits; pick per request.

Synchronous (default)Asynchronous
HowSend the request and waitAdd async: true, get a task id at once
The answer arrivesIn the same response, after 20 seconds to a few minutesLater: you poll, or we call your webhook
Connection held openUntil the image is readyUnder a second
Longest run7 minutes10 minutes
ReturnsImage data (b64_json) or a link (url)A link (url)
Works withThe OpenAI SDKs and any tool built for the OpenAI Images APIAny HTTP client
Good forScripts, back ends, one image at a timeWeb pages, many images at once, slow models, serverless functions with short time limits

The three calls

CallWhat it does
POST /v1/images/generations or /v1/images/edits with async: trueStarts a task. Answers 202 with the task id
GET /v1/images/tasks?ids=a,b,cThe state of up to 100 tasks in one request
GET /v1/images/tasks/{id}The state of one task

1. Start a task

Add async: true to the body of POST /v1/images/generations, or as a form field on POST /v1/images/edits.

curl https://api.cheapestimagen.com/v1/images/generations \
  -H "Authorization: Bearer YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "gpt-image-2.6", "prompt": "a red fox in the snow", "async": true}'

The answer is 202 Accepted, in well under a second:

{
  "id": "req_33ac10d3e9a8e6f120f4c0d3",
  "object": "image.task",
  "status": "in_progress",
  "created": 1795062073,
  "finished": null,
  "model": "gpt-image-2.6"
}

Keep the id. Three things to know:

  • Links only. The images of a task are returned as links, so leave response_format out or set it to url. b64_json is refused with a 400.
  • Bad requests fail here, not later. A wrong parameter (400), not enough credits (402) or too many requests (429) is answered at once, as with a synchronous request. No task is created.
  • No body field? The header Prefer: respond-async does the same as async: true.

2. Read the tasks

Several tasks in one request

When you are waiting for more than one task, ask for all of them at once. A page that started 10 tasks sends one polling request, not 10.

curl "https://api.cheapestimagen.com/v1/images/tasks?ids=req_33ac10d3e9a8e6f120f4c0d3,req_26e50328772b7d62f59d355a" \
  -H "Authorization: Bearer YOUR_KEY"
{
  "object": "list",
  "data": [
    {
      "id": "req_33ac10d3e9a8e6f120f4c0d3",
      "object": "image.task",
      "status": "succeeded",
      "created": 1795062073,
      "finished": 1795062098,
      "model": "gpt-image-2.6",
      "result": {
        "created": 1795062098,
        "data": [{ "url": "https://img.cheapestimagen.com/g/req_33ac10d3e9a8e6f120f4c0d3/0.png" }]
      }
    },
    {
      "id": "req_26e50328772b7d62f59d355a",
      "object": "image.task",
      "status": "in_progress",
      "created": 1795062074,
      "finished": null,
      "model": "gpt-image-2.6"
    }
  ],
  "not_found": []
}
  • ids takes up to 100 task ids, separated by commas.
  • data holds the tasks in the order you asked for them.
  • An id that is not a task of your account, or whose images are no longer kept, is listed in not_found. It does not fail the request.

One task

curl https://api.cheapestimagen.com/v1/images/tasks/req_33ac10d3e9a8e6f120f4c0d3 \
  -H "Authorization: Bearer YOUR_KEY"

The answer is the task object on its own. An unknown id answers 404.

What a task says

statusMeaningExtra field
in_progressThe image is being madenone
succeededDoneresult: exactly what the synchronous call would have returned, { created, data: [{ url }] }
failedIt did not workerror: exactly the error the synchronous call would have returned

A failed task looks like this:

{
  "id": "req_33ac10d3e9a8e6f120f4c0d3",
  "object": "image.task",
  "status": "failed",
  "created": 1795062073,
  "finished": 1795062110,
  "model": "gpt-image-2.6",
  "error": { "message": "The image provider failed. You were not charged.", "type": "api_error", "param": null, "code": "upstream_error" }
}

A failed task is not charged. The one exception is the same as for synchronous requests: a refusal on the Nano Banana stable channels.

How often to poll

Every 2 to 5 seconds is enough. Reading tasks is free and is not an image request: it does not count against the requests in progress. A task can be read for 72 hours, as long as its images are kept.

Example: a web page that starts 10 images

One request per image to start them, then one request every 3 seconds for all of them.

const API = "https://api.cheapestimagen.com/v1";
const headers = { Authorization: "Bearer YOUR_KEY", "Content-Type": "application/json" };

// Start 10 tasks.
const prompts = Array.from({ length: 10 }, (_, i) => `a red fox in the snow, variation ${i + 1}`);
const started = await Promise.all(prompts.map((prompt) =>
  fetch(`${API}/images/generations`, {
    method: "POST", headers,
    body: JSON.stringify({ model: "gpt-image-2.6", prompt, async: true }),
  }).then((r) => r.json())
));

// Poll all of them with one request until none is in progress.
let waiting = started.map((t) => t.id);
const done = {};
while (waiting.length) {
  await new Promise((r) => setTimeout(r, 3000));
  const { data } = await fetch(`${API}/images/tasks?ids=${waiting.join(",")}`, { headers }).then((r) => r.json());
  for (const task of data) if (task.status !== "in_progress") done[task.id] = task;
  waiting = waiting.filter((id) => !done[id]);
}

for (const task of Object.values(done)) {
  console.log(task.status === "succeeded" ? task.result.data[0].url : task.error.message);
}

Do not put your API key in a public web page. Call the API from your own server and let the page talk to that.

Example: Python

import time, requests

API = "https://api.cheapestimagen.com/v1"
HEADERS = {"Authorization": "Bearer YOUR_KEY"}

ids = [
    requests.post(f"{API}/images/generations", headers=HEADERS, json={
        "model": "gpt-image-2.6", "prompt": f"a red fox in the snow, variation {i}", "async": True,
    }).json()["id"]
    for i in range(10)
]

done = {}
while len(done) < len(ids):
    time.sleep(3)
    waiting = [i for i in ids if i not in done]
    tasks = requests.get(f"{API}/images/tasks", headers=HEADERS, params={"ids": ",".join(waiting)}).json()["data"]
    done.update({t["id"]: t for t in tasks if t["status"] != "in_progress"})

for t in done.values():
    print(t["result"]["data"][0]["url"] if t["status"] == "succeeded" else t["error"]["message"])

With the OpenAI SDK, pass the field through extra_body={"async": True} and read the tasks with a plain HTTP request.

Webhook instead of polling

Add webhook_url and we POST the finished task to it:

{ "model": "gpt-image-2.6", "prompt": "a red fox in the snow", "async": true, "webhook_url": "https://example.com/hooks/images" }
  • The address must be https:// on a public host name.
  • The body is the task object, the same JSON as GET /v1/images/tasks/{id}.
  • Answer with any 2xx within 10 seconds. Otherwise we try twice more, after 3 and 15 seconds, and then stop.
  • To have the call signed, send a secret of your own as webhook_secret (16 to 128 characters) with the request. Without it the call is not signed: treat it as a notice, take the id from it and read the task with your key before you trust the content.
  • The task stays readable whether or not the webhook arrived, so a missed call loses nothing.

Check the signature

With webhook_secret, the call carries the header x-webhook-signature: t=1763560000,v1=5f2b…. t is the time of the call in Unix seconds, and v1 is the HMAC-SHA256, in hex, of the text <t>.<body> made with your secret. Compute the same value from the raw request body and compare; refuse calls whose t is more than a few minutes old.

import hashlib, hmac, time

def is_ours(secret: str, header: str, raw_body: bytes) -> bool:
    parts = dict(p.split("=", 1) for p in header.split(","))
    signed = parts["t"].encode() + b"." + raw_body
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts["v1"]) and abs(time.time() - int(parts["t"])) < 300
import { createHmac, timingSafeEqual } from 'node:crypto';

function isOurs(secret, header, rawBody) {
  const { t, v1 } = Object.fromEntries(header.split(',').map((p) => p.split('=')));
  const expected = createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex');
  return expected.length === v1.length && timingSafeEqual(Buffer.from(expected), Buffer.from(v1)) && Math.abs(Date.now() / 1000 - Number(t)) < 300;
}

Use the body exactly as it arrived, before any JSON parsing. The secret is used for this one request and is not stored with your account.

Limits

An asynchronous request counts like a synchronous one: 300 requests a minute and 50 in progress per account. A request sent while 50 are running is refused with 429; wait for one to finish. Reading tasks is not counted.

Idempotency-Key works the same way: while a request with that key is running or after it succeeded, a repeat answers 409.

On this page