> Source page: https://tryaiapi.com/en/docs/image-model/ (Markdown version of this page)

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.

## 01 Model 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](https://tryaiapi.com/en/models/), `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.

| Model | Model ID | Protocol & Endpoint |
| --- | --- | --- |
| GPT Image 2.6 Sunburst | `gpt-image-2.6-sunburst` | OpenAI compatible<br>`POST /v1/images/generations`<br>`POST /v1/images/edits` |
| GPT Image 2.6 Flare | `gpt-image-2.6-flare` | OpenAI compatible<br>`POST /v1/images/generations`<br>`POST /v1/images/edits` |
| GPT Image 2.6 Sunburst (OpenAI) | `gpt-image-2.6-sunburst-oai` | OpenAI compatible<br>`POST /v1/images/generations`<br>`POST /v1/images/edits` |
| GPT Image 2.6 Flare (OpenAI) | `gpt-image-2.6-flare-oai` | OpenAI compatible<br>`POST /v1/images/generations`<br>`POST /v1/images/edits` |
| GPT Image 2.5 Sunburst (OpenAI) | `gpt-image-2.5-sunburst-oai` | OpenAI compatible<br>`POST /v1/images/generations`<br>`POST /v1/images/edits` |
| GPT Image 2.5 Flare (OpenAI) | `gpt-image-2.5-flare-oai` | OpenAI compatible<br>`POST /v1/images/generations`<br>`POST /v1/images/edits` |
| Gemini 3 Pro Image (Nano Banana Pro) | `gemini-3-pro-image` | Gemini native: `POST /v1beta/models/{model}:generateContent`<br>OpenAI compatible: `POST /v1/chat/completions` |
| Gemini Nano Banana 2.1 | `gemini-nano-banana-2.1` | Gemini native: `POST /v1beta/models/{model}:generateContent`<br>OpenAI compatible: `POST /v1/chat/completions` |
| Gemini 3.1 Flash Image (Nano Banana 2) | `gemini-3.1-flash-image` | Gemini native: `POST /v1beta/models/{model}:generateContent`<br>OpenAI compatible: `POST /v1/chat/completions` |

## 02 Text-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**

```bash
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**

```python
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)
```

| Parameter | Description |
| --- | --- |
| `model` | Required, e.g. `gpt-image-2.6-sunburst` or `gpt-image-2.6-flare`. |
| `prompt` | Required. Describe subject, scene, framing, style, and exclusions clearly. |
| `size` | Standard 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. |
| `quality` | Standard values: `low` / `medium` / `high` / `auto` (default); selected variants also accept `xhigh` / `max` (verify per model in the model market). |
| `n` | Number of images to generate per call (default `1`, max `10`). |
| `response_format` | Some variants support `url` or `b64_json` while others always return `b64_json`; handle both `data[].url` and `data[].b64_json` in your client. |
| `output_format` | Output file format, guaranteed for `png` (required when `background="transparent"`). |
| `background` | `transparent` / `opaque` / `auto` (`transparent` is supported on selected variants). |
| `moderation` | Content moderation level: `auto` (default) or `low`. |
| `stream` | Streaming 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`.

## 03 Image-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**

```bash
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
```

| Field | Requirements & 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). |
| `mask` | Optional PNG (recommended ≤ 4 MB). Must match the first source image dimensions **exactly**; transparent regions mark areas to edit. |
| `prompt` | Required edit instruction (up to 32,000 characters). |
| `input_fidelity` | `high` preserves original subject, product, and brand details; `low` allows more creative freedom (supported on selected variants for edits). |

## 04 Text-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**

```bash
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" }
    }
  }'
```

| Field | Description |
| --- | --- |
| `responseModalities` | Recommended: `["TEXT", "IMAGE"]` (or `["IMAGE"]` only). |
| `imageConfig.imageSize` | Supports `1K` / `2K` / `4K` (actual pixel dimensions follow model output; 4K responses can exceed 20 MB). |
| `imageConfig.aspectRatio` | Supports standard aspect ratios such as `1:1`, `16:9`, `9:16`, `4:3`, `3:4`. |
| Response & safety parsing | Images 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**

```javascript
"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,...)`.

## 05 Common Errors and Production Pitfalls

| Status / Symptom | `error.code` | Cause & 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. |
| `400` | `invalid_request` | Invalid 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`<br>(Safety block) | `content_policy_violation` | Prompt 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<br>(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. |
| `429` | `upstream_capacity_exhausted` | Capacity for this model is currently full; retry later. |
| `429` | `upstream_busy` | Upstream is busy or rate-limiting; use exponential backoff with jitter and cap client burst concurrency. Contact support ahead of sustained high-concurrency workloads. |
| `503` | `model_temporarily_unavailable` | No route is currently available for this model; retry later, or switch to a comparable model from another provider. |
| `503` | `model_not_found` | This model is not available under the API key; check the model name and the key's access, and contact us if it persists. |
| `429` | `resolution_tier_unavailable` | The 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. |
| `503` | `image_resolution_unavailable` | The returned image resolution was lower than the requested tier, so the result was rejected and not billed; retry later. |
| `502` | `upstream_error` | Upstream technical failure; retry later, and switch to another provider if it persists. Check console usage records before retrying to avoid duplicate generation charges. |
| `504` | `upstream_timeout` | Upstream timed out; retry later. Check console usage records before retrying to avoid duplicate generation charges. |
| `only imagen models`<br>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](https://tryaiapi.com/en/docs/video-model/).

## 06 Pre-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](https://tryaiapi.com/en/docs/discovery-test/) to verify billing against published rates.
- **Related guides**: General API reference at [Docs](https://tryaiapi.com/en/docs/), video models at [Video Model Docs](https://tryaiapi.com/en/docs/video-model/), coding clients at [Coding Agents Setup](https://tryaiapi.com/en/docs/coding-agents/), automated agent setup at [/SKILL.md](https://tryaiapi.com/SKILL.md), and logging scope at [Transparency](https://tryaiapi.com/en/transparency/).
