Docs · Image Generation API

Image Generation API Integration Guide

One API key gives access to 9 live image generation models across OpenAI GPT Image and Google Gemini Image (Nano Banana) — no complex business verification required, pay-as-you-go from $5 via Stripe, transparent pricing with no monthly lock-in. The two families use different protocol endpoints — select the exact path shown below.

01Model IDs, Endpoint Routing & Billing Rules

Always verify callable model IDs via GET /v1/models and live pricing (per-image or per-token) via the model market, GET /api/pricing, or the console usage ledger. Generating n images in one call bills cumulatively for all n outputs (or corresponding tokens for token-billed models). HTTP 4xx rejections (including 451) are not billed; HTTP 200 responses without an image, early client disconnects, gateway timeouts, or automatic size fallbacks may still incur charges — always refer to the console usage ledger as authoritative.

ModelModel IDProtocol & Endpoint
GPT Image 2.6 Sunburstgpt-image-2.6-sunburstOpenAI compatible
POST /v1/images/generations
POST /v1/images/edits
GPT Image 2.6 Flaregpt-image-2.6-flareOpenAI compatible
POST /v1/images/generations
POST /v1/images/edits
GPT Image 2.6 Sunburst (OpenAI)gpt-image-2.6-sunburst-oaiOpenAI compatible
POST /v1/images/generations
POST /v1/images/edits
GPT Image 2.6 Flare (OpenAI)gpt-image-2.6-flare-oaiOpenAI compatible
POST /v1/images/generations
POST /v1/images/edits
GPT Image 2.5 Sunburst (OpenAI)gpt-image-2.5-sunburst-oaiOpenAI compatible
POST /v1/images/generations
POST /v1/images/edits
GPT Image 2.5 Flare (OpenAI)gpt-image-2.5-flare-oaiOpenAI compatible
POST /v1/images/generations
POST /v1/images/edits
Gemini 3 Pro Image (Nano Banana Pro)gemini-3-pro-imageGemini native: POST /v1beta/models/{model}:generateContent
OpenAI compatible: POST /v1/chat/completions
Gemini Nano Banana 2.1gemini-nano-banana-2.1Gemini native: POST /v1beta/models/{model}:generateContent
OpenAI compatible: POST /v1/chat/completions
Gemini 3.1 Flash Image (Nano Banana 2)gemini-3.1-flash-imageGemini native: POST /v1beta/models/{model}:generateContent
OpenAI compatible: POST /v1/chat/completions

02Text-to-Image: POST /v1/images/generations

Use this endpoint for all gpt-image-* models. Standard OpenAI Python and Node SDKs work by setting base_url to https://tryaiapi.com/v1.

curl · GPT Image text-to-image
curl -sS https://tryaiapi.com/v1/images/generations \ -H "Authorization: Bearer $TRYAIAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-image-2.6-sunburst", "prompt": "Minimalist ceramic coffee cup on a wooden desk in soft morning light", "size": "1024x1024", "quality": "high", "n": 1 }'
Python · OpenAI SDK
import os from openai import OpenAI client = OpenAI( base_url="https://tryaiapi.com/v1", api_key=os.environ["TRYAIAPI_KEY"], timeout=300.0, ) res = client.images.generate( model="gpt-image-2.6-sunburst", prompt="Minimalist ceramic coffee cup on a wooden desk in soft morning light", size="1024x1024", quality="high", ) print(res.data[0].b64_json[:64] if res.data[0].b64_json else res.data[0].url)
ParameterDescription
modelRequired, e.g. gpt-image-2.6-sunburst or gpt-image-2.6-flare.
promptRequired. Describe subject, scene, framing, style, and exclusions clearly.
sizeStandard sizes: 1024x1024, 1536x1024, 1024x1536, auto. gpt-image-2.6-* also supports custom WxH (multiples of 16, aspect ratio 1:3 to 3:1, max side ≤ 3840, total pixels ≤ 3840×2160; above 2560x1440 takes longer). Exact limits depend on the model variant.
qualityStandard values: low / medium / high / auto (default); selected variants also accept xhigh / max (verify per model in the model market).
nNumber of images to generate per call (default 1, max 10).
response_formatSome variants support url or b64_json while others always return b64_json; handle both data[].url and data[].b64_json in your client.
output_formatOutput file format, guaranteed for png (required when background="transparent").
backgroundtransparent / opaque / auto (transparent is supported on selected variants).
moderationContent moderation level: auto (default) or low.
streamStreaming is not supported for image generation; omit or pass false.

Tuning tip: If the whole image looks soft when zoomed in, increase size first; if resolution is sufficient but faces, hands, text, or fine textures lack detail, raise quality. Output is returned in data[].url or data[].b64_json.

03Image-to-Image & Inpainting: POST /v1/images/edits

Submit source images (and optional mask) as multipart/form-data for multi-image reference or localized editing.

curl · GPT Image edits / inpainting
curl -sS https://tryaiapi.com/v1/images/edits \ -H "Authorization: Bearer $TRYAIAPI_KEY" \ -F model=gpt-image-2.6-sunburst \ -F image=@source.png \ -F mask=@mask.png \ -F prompt="Replace the background with a warm sunset beach while keeping the subject unchanged" \ -F size=1024x1024 \ -F quality=high \ -F input_fidelity=high
FieldRequirements & Notes
image / image[]Required, PNG recommended ≤ 4 MB per image (to avoid 400/413). For multi-image reference, pass multiple image[]=@file parts (up to 16 images).
maskOptional PNG (recommended ≤ 4 MB). Must match the first source image dimensions exactly; transparent regions mark areas to edit.
promptRequired edit instruction (up to 32,000 characters).
input_fidelityhigh preserves original subject, product, and brand details; low allows more creative freedom (supported on selected variants for edits).

04Text-to-Image & Editing: POST /v1beta/models/{model}:generateContent

Important: Do not send gemini-3-pro-image, gemini-nano-banana-2.1, or gemini-3.1-flash-image to /v1/images/generations (that returns only imagen models are supported). Use the Gemini native generateContent endpoint (accepts both Authorization: Bearer and Gemini SDK's x-goog-api-key header; set Gemini SDK base URL to https://tryaiapi.com without /v1beta), or call /v1/chat/completions in OpenAI-compatible mode.

curl · Gemini native text-to-image
curl -sS "https://tryaiapi.com/v1beta/models/gemini-3.1-flash-image:generateContent" \ -H "Authorization: Bearer $TRYAIAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "contents": [{ "role": "user", "parts": [{ "text": "A clean architectural sketch of a sunlit courtyard" }] }], "generationConfig": { "responseModalities": ["TEXT", "IMAGE"], "imageConfig": { "aspectRatio": "16:9", "imageSize": "2K" } } }'
FieldDescription
responseModalitiesRecommended: ["TEXT", "IMAGE"] (or ["IMAGE"] only).
imageConfig.imageSizeSupports 1K / 2K / 4K (actual pixel dimensions follow model output; 4K responses can exceed 20 MB).
imageConfig.aspectRatioSupports standard aspect ratios such as 1:1, 16:9, 9:16, 4:3, 3:4.
Response & safety parsingImages are usually Base64 in candidates[0].content.parts[].inlineData.data (check inlineData.mimeType); parsers should also handle parts[].fileData.fileUri. If HTTP 200 returns no image in parts, inspect candidates[0].finishReason (e.g. IMAGE_SAFETY) or promptFeedback.blockReason.

Image-to-image editing: Append an inlineData part with mimeType (image/png or image/jpeg) and raw Base64 in data (without any data:image/...;base64, prefix). For large Base64 payloads, write the JSON to a file and pass curl -d @body.json:

JSON · Gemini inlineData edit snippet
"parts": [ { "text": "Restyle this photo into warm golden hour lighting" }, { "inlineData": { "mimeType": "image/png", "data": "<RAW_BASE64_WITHOUT_PREFIX>" } } ]

OpenAI-compatible chat endpoint: You can also call POST /v1/chat/completions with "model": "gemini-3.1-flash-image"; the generated image is returned inline as ![image](data:image/png;base64,...).

05Common Errors and Production Pitfalls

Status / Symptomerror.codeCause & Recommended Action
401—Missing, invalid, or disabled API key; verify Authorization: Bearer or x-goog-api-key.
403—The API key is not allowed to access the requested resource; contact us to confirm its permissions.
400invalid_requestInvalid parameter format, missing required field, unsupported image format, non-compliant reference image, or mask dimensions mismatch with the first source image. An oversized request body can also return this error; compress reference images or send fewer. Fix the request and resend.
413—Payload too large (often caused by sending multiple uncompressed high-res reference images). Resize/compress reference images before encoding.
451
(Safety block)
content_policy_violationPrompt or reference image triggered safety or copyright filtering. Revise the prompt or input image before resending; retrying unchanged will not help. Not billed.
200 no-image
(Gemini native)
—The response has no error field; If candidates[0].finishReason is IMAGE_SAFETY, or promptFeedback.blockReason is PROHIBITED_CONTENT, it is also a safety block. Billing follows the console ledger; do not auto-retry identically in a loop. If text-only is returned with finishReason=STOP and no safety block, revise the prompt to request image output explicitly.
429upstream_capacity_exhaustedCapacity for this model is currently full; retry later.
429upstream_busyUpstream is busy or rate-limiting; use exponential backoff with jitter and cap client burst concurrency. Contact support ahead of sustained high-concurrency workloads.
503model_temporarily_unavailableNo route is currently available for this model; retry later, or switch to a comparable model from another provider.
503model_not_foundThis model is not available under the API key; check the model name and the key's access, and contact us if it persists.
429resolution_tier_unavailableThe requested resolution tier (for example 4K) has no available route right now; the request is not sent upstream and is not billed. Retry later, or use a lower tier (1K/2K) in the meantime.
503image_resolution_unavailableThe returned image resolution was lower than the requested tier, so the result was rejected and not billed; retry later.
502upstream_errorUpstream technical failure; retry later, and switch to another provider if it persists. Check console usage records before retrying to avoid duplicate generation charges.
504upstream_timeoutUpstream timed out; retry later. Check console usage records before retrying to avoid duplicate generation charges.
only imagen models
error
—Gemini Nano Banana model was sent to /v1/images/generations; switch to /v1beta/models/{model}:generateContent or /v1/chat/completions.
  • Set client HTTP timeout to at least 180–300 seconds: Typical generation takes ~25–50s median, while high-resolution (2K/4K), high-quality, or peak-hour tail requests can take 90–150s+ (occasionally 2–3 minutes). Avoid tight 60–90s client timeouts.
  • Early client disconnects can still be billed: Once accepted, if the client aborts or times out early, generation may still complete and bill on the server while the response cannot be delivered. Always use generous timeouts and inspect console logs before re-submitting.
  • Allow ≥ 50 MB response buffers: Gemini native Base64 responses are typically 1.5–5 MB and can exceed 20 MB at 4K. Ensure HTTP clients and reverse proxies permit ≥ 50 MB JSON payloads.
  • Out-of-range size substitution: Passing an unsupported size (such as 4096x4096) to GPT Image returns 400 on some variants and may silently fall back to 1024x1024 and bill on others; stick to standard sizes or the variant rules above.
  • Omit unnecessary tool fields: When calling Gemini image models without needing web search grounding, omit google_search tools to avoid extra latency and cost.
  • Unsupported modes: Image endpoints do not support async polling jobs or streaming responses. For async video jobs, see the Video Model Docs.

06Pre-Flight Checklist

  • Free connectivity check: Run curl -sS https://tryaiapi.com/v1/user/balance -H "Authorization: Bearer $TRYAIAPI_KEY" (read-only, zero cost) to confirm your key and balance before generating images.
  • Live catalog & billing parity: Fetch live pricing from GET /api/pricing and structured specs from GET /catalog.json. See Public price and API response consistency check to verify billing against published rates.
  • Related guides: General API reference at Docs, video models at Video Model Docs, coding clients at Coding Agents Setup, automated agent setup at /SKILL.md, and logging scope at Transparency.

Last updated: 2026-11-27