Skip to navigation

Build a Reliable Production Integration

A reliable integration sends each job once, records its generation_id before waiting, collects the result by polling or webhook, downloads the files within 24 hours, and checks what it was charged. This guide walks through that lifecycle and links to the page that covers each step in detail.

1. Choose keys and a workspace

Keys can’t be scoped: a key can call every endpoint its workspace can use and spend that workspace’s balance. Use a separate API team for each environment that needs its own balance or people. If you have an Ideogram subscription, a request uses your monthly credits only when they cover all of it; otherwise the whole request is charged to your API balance. See Authentication and API keys and API Setup.

2. Quote the request

Send the request with dry_run=true to get its price without running it. A quote doesn’t check your balance or your in-flight requests, so the real request can still be rejected. See Price quotes.

3. Submit asynchronously and record the ID

Most image endpoints wait for the result by default. For production jobs, set async or supply a webhook_url: the request returns a generation_id as soon as it is accepted. Store that ID with your own job record before you wait for anything. Video, tool and SVG endpoints, Replace Background, Remove Objects and Reframe with Nano Banana 2 always run asynchronously.

A synchronous request that waits 265 seconds without finishing returns 503. The generation keeps running and is billed when it completes, but the 503 has no generation_id, so you can’t collect the result. That is the main reason to submit production jobs asynchronously.

4. Poll with a deadline, or receive a webhook

Poll GET /v2/generations/{generation_id} every few seconds until status is completed or failed. Set your own deadline. When it passes, keep the ID and check again later rather than resubmitting. Polling is rate limited: on a 429, wait for the seconds in Retry-After. See Rate limits.

With a webhook_url, Ideogram sends the result when the generation completes. Verify the signature, process each generation_id once, and keep polling as a fallback: a failed generation sends no webhook, and a delivery can be dropped after its retries. See Webhooks.

5. Retry without paying twice

The API takes no idempotency key, and every request you send is a new, billed generation. A 429 was rejected before it ran, so retry it after a wait. A 402 also didn’t run, but it fails again until you add credits. Don’t resend a request that timed out or whose response you lost: poll its generation_id instead. See Idempotency and safe retries.

6. Store the files and the metadata

Result links expire after 24 hours, and each poll returns fresh ones. Download every file into your own storage, then keep the generation_id, prompt, seed, resolution, is_image_safe and any asset_id. See Responses and metadata.

7. Reconcile cost

Compare your quotes with what you were charged: usage_cost_usd_micros on a completed generation (when the request uses variable usage-based pricing), GET /v2/account/usage for a date range and GET /v2/account/invoices for invoices.

8. Handle failures

OutcomeWhat to do
400, 401Fix the request or the key. Nothing ran.
402Read reject_reason; add credits for insufficient_funds, then retry. Nothing ran.
403, 404Check access to the endpoint or model, and the IDs and files you sent. Nothing ran.
422The prompt failed the safety check. Change it. Not billed.
429Too many requests in flight. Wait, then retry. Nothing ran.
is_image_safe: falseThat image was withheld. The request was billed.
status: failedRead failure_reason, adjust, resubmit. Not billed.
500 on a synchronous requestThe generation failed. Retry once. Not billed.
503 that says the request took too longThe work continues and is billed, with no ID to collect it. Use asynchronous requests.
503 that says the endpoint is unavailableNothing ran. Retry later.

See Errors and billing for the full table.

9. What the API doesn’t offer

  • No cancel operation. An accepted request runs to completion. See Cancel a request.
  • No idempotency key. Record the generation_id and poll before resubmitting.
  • No scoped keys. Separate environments with separate API teams.
  • No batch endpoint. Send requests with bounded concurrency.
  • No official SDK packages. Use any HTTP library, or generate a client from the OpenAPI specification. See SDKs and client libraries.

A complete example

This Python example quotes a request, submits it asynchronously, records the ID, polls with a deadline and stores the files. JobStore stands in for your own database; replace its methods with real writes.

import email.utils
import os
import time
import requests
API = "https://api.ideogram.ai"
HEADERS = {"Api-Key": os.environ["IDEOGRAM_API_KEY"]}
ENDPOINT = "/v2/image/generate/ideogram-4-5"
BODY = {"prompt": "A ceramic mug on a wooden table, soft window light", "quality": "medium"}
class JobStore:
"""Stands in for your database: one record per generation_id."""
def __init__(self) -> None:
self.jobs: dict[str, dict] = {}
def save(self, generation_id: str, **fields) -> None:
self.jobs.setdefault(generation_id, {}).update(fields)
def save_file(self, generation_id: str, index: int, content: bytes) -> None:
with open(f"{generation_id}-{index}.png", "wb") as file:
file.write(content)
def retry_after_seconds(response: requests.Response, default: float = 5) -> float:
value = response.headers.get("Retry-After")
if value is None:
return default
if value.isdigit():
return float(value)
when = email.utils.parsedate_to_datetime(value) # Retry-After can also be an HTTP date
return max(0.0, when.timestamp() - time.time())
def quote(body: dict) -> dict:
response = requests.post(
f"{API}{ENDPOINT}", params={"dry_run": "true"}, headers=HEADERS, json=body, timeout=30
)
response.raise_for_status()
return response.json() # a PriceQuote: nothing ran, nothing billed
def submit(body: dict, jobs: JobStore) -> str:
while True:
response = requests.post(
f"{API}{ENDPOINT}", headers=HEADERS, json={**body, "async": True}, timeout=30
)
if response.status_code == 429: # rejected before it ran: wait, then retry
time.sleep(retry_after_seconds(response))
continue
if response.status_code == 402: # didn't run; retrying fails until you add credits
raise RuntimeError(response.json().get("reject_reason"))
response.raise_for_status()
generation_id = response.json()["generation_id"]
jobs.save(generation_id, status="pending") # record it before waiting
return generation_id
def wait(generation_id: str, deadline_s: float = 600) -> dict | None:
end = time.monotonic() + deadline_s
while time.monotonic() < end:
response = requests.get(f"{API}/v2/generations/{generation_id}", headers=HEADERS, timeout=30)
if response.status_code == 429:
time.sleep(retry_after_seconds(response))
continue
response.raise_for_status()
generation = response.json()
if generation["status"] != "pending":
return generation
time.sleep(3)
return None # still running: keep the ID and check later; don't resubmit
def store(generation: dict, jobs: JobStore) -> None:
generation_id = generation["generation_id"]
for index, item in enumerate(generation.get("data", [])):
if item.get("url"): # empty when an image failed the safety check
jobs.save_file(generation_id, index, requests.get(item["url"], timeout=60).content)
jobs.save(
generation_id,
status=generation["status"],
failure_reason=generation.get("failure_reason"),
cost_usd_micros=generation.get("usage_cost_usd_micros"),
)
if __name__ == "__main__":
jobs = JobStore()
print("Quoted", quote(BODY)["usd_micros"] / 1_000_000, "USD")
generation_id = submit(BODY, jobs)
generation = wait(generation_id)
if generation is None:
print("Still running; poll", generation_id, "later")
else:
store(generation, jobs)
print(generation["status"], jobs.jobs[generation_id])

Run it with IDEOGRAM_API_KEY set. It prints the quoted price, then the final status and what it stored, and saves each image as <generation_id>-<index>.png.

Moving from v1

The v1 API keeps working. The v1 to v2 endpoint table in API Overview lists each v2 equivalent.