Skip to content
Reading settings
Image generation

Image Generation API Developer Guide ​

Version: 1.1 · Updated: 2026-11-05

Latest guides by model

Choose a model under Image generation → GPT Image / Nano Banana in the sidebar, or follow a model link in the table below for its parameters and complete examples.

1. API Overview and Supported Models ​

This guide describes the platform's unified image generation API. Select a model using model, submit a request to obtain a task_id, and query the task for its status and output artifacts.

modelSupported input scenariosBilling method
nano-banana-2.1Text, single reference image, multiple reference imagesPer request
nano-banana-2Text, single reference image, multiple reference imagesPer request
gpt-image-2.6Text, single reference image, multiple reference imagesPer request
gpt-image-2.6-flareText, single reference image, multiple reference imagesPer request
gpt-image-2.6-sunburstText, single reference image, multiple reference imagesPer request
gpt-image-2.5Text, single reference image, multiple reference imagesPer request
gpt-image-2Text, single reference image, multiple reference imagesPer request
MethodPathSuccess status code
POST/api/v1/platform/images/generations202
GET/api/v1/platform/tasks/{task_id}200

Refer to the console for current model availability, permissions, and prices. This guide covers only the models listed above.

2. Authentication and Environment Setup ​

HeaderRequiredDescription
AuthorizationYesBearer <API_KEY>; use a platform API key
Content-TypeRequired for POSTapplication/json
Accept-LanguageNozh-CN (Simplified Chinese), zh-Hant (Traditional Chinese), or en (English); defaults to Simplified Chinese and uses the first language tag

Store your API key in a server environment. Before calling the API, check the account status, model permissions, source IP, balance, and API-key quota.

API_BASE_URL is intentionally blank in the examples. Set it to your service root address. The endpoint paths already include /api/v1/platform; do not add that prefix again.

Bash environment variables:

bash
export API_BASE_URL=""
export API_KEY=""

PowerShell environment variables:

powershell
$env:API_BASE_URL = ""
$env:API_KEY = ""

3. Create a Generation Task: Request Parameters ​

POST /api/v1/platform/images/generations

Send a single JSON object with the parameters directly at the top level.

ParameterJSON typeRequiredDescription
modelstringYesModel identifier; see the supported models table for allowed values
promptstringYesNon-empty generation prompt
resolutionstringYesResolution tier; must be supported by the selected model
ratiostringDepends on the modelOutput aspect ratio; see the model specifications for required fields and allowed values
qualitystringNoOutput quality for the GPT Image 2.6 series. See each model guide for allowed values.
output_formatstringNoOutput format for the GPT Image 2.6 series. See each model guide for allowed values.
imagesarray<object>NoOrdered reference images; each item is an object containing url and role
audios, videosarray<object>NoReserved fields; none of the listed models support non-empty arrays, so omit these fields

The raw request body must not exceed 65535 bytes. Do not add a data or body wrapper. Unknown fields, duplicate JSON keys, and non-finite numeric values are rejected. Omitted parameters remain omitted; the platform does not insert default generation values.

For declared fields, null, empty strings, whitespace-only strings, and the case-insensitive string null are treated as omitted. Required fields still produce a missing-field error; optional fields remain omitted. 0, false, empty arrays, and empty objects are validated according to the original field constraints.

4. Model Specifications and Reference Media ​

modelresolution (required)Is ratio required?Aspect ratio list
nano-banana-2.11K, 2K, 4KNoA
nano-banana-21K, 2K, 4KNoA
gpt-image-2.61KYesB
gpt-image-2.6-flare1K, 2K, 4KYesB
gpt-image-2.6-sunburst1K, 2K, 4KYesB
gpt-image-2.51KYesB
gpt-image-21KYesB

Aspect ratio list A: 1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3, 5:4, 4:5, 21:9, 1:4, 4:1, 1:8, 8:1.

Aspect ratio list B: 1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3, 5:4, 4:5, 21:9, 9:21, 1:2, 2:1.

All models in the table support text-to-image generation and single or multiple reference images. Omitting images or sending an empty array selects text-to-image generation; providing one or more images selects reference-based generation. Image order is preserved. Only the reference role is supported; first-frame and last-frame roles are not supported. The published specifications do not declare a fixed reference-image count limit. Inputs must still comply with the actual model service's media limits and the request body size limit.

Parameter values are case-sensitive. ratio is an aspect ratio, not a pixel size; do not submit width, height, or provider-specific size fields. For the Nano series, the platform does not choose a default ratio when ratio is omitted. For the GPT Image series, both resolution and ratio are required.

Reference media object ​

FieldJSON typeRequiredDescription
urlstringYesPublicly readable HTTP/HTTPS file URL; HTTPS is recommended
rolestringYesMust be reference, meaning reference media

The model service must be able to read the media directly without a browser login session. Signed URLs must remain valid throughout queueing and media retrieval. Base64, data URIs, local paths, form file uploads, and inline binary data are not accepted. The example.com addresses in this guide are placeholders; replace them with real media URLs.

5. Quickstart ​

The following cURL example uses Bash syntax.

bash
curl --request POST "${API_BASE_URL}/api/v1/platform/images/generations" \
  --header "Authorization: Bearer ${API_KEY}" \
  --header "Content-Type: application/json" \
  --header "Accept-Language: en" \
  --data-raw '{
  "model": "nano-banana-2.1",
  "prompt": "A small orange cat on a clean white background, soft studio lighting.",
  "resolution": "1K",
  "ratio": "1:1"
}'

A successfully accepted request returns HTTP 202:

json
{
  "task_id": "550e8400-e29b-41d4-a716-446655440000",
  "model": "nano-banana-2.1",
  "modality": "image",
  "status": "queued",
  "artifacts": [],
  "failure_code": null,
  "failure_reason": null,
  "created_at": "2026-11-05 10:00:00",
  "updated_at": "2026-11-05 10:00:00"
}

HTTP 202 means the request has been accepted locally; generation may still be queued or running. Save the returned task_id immediately, and use the same API key for subsequent queries. HTTP 202 does not mean generation is complete.

6. Model and Use-Case Examples ​

nano-banana-2.1: Text-to-image ​

json
{
  "model": "nano-banana-2.1",
  "prompt": "A small orange cat on a clean white background, soft studio lighting.",
  "resolution": "1K"
}

nano-banana-2.1: Multiple reference images ​

json
{
  "model": "nano-banana-2.1",
  "prompt": "Keep the reference subject consistent and create a clean, naturally lit scene.",
  "resolution": "1K",
  "images": [
    {
      "url": "https://example.com/media/reference_1.jpg",
      "role": "reference"
    },
    {
      "url": "https://example.com/media/reference_2.jpg",
      "role": "reference"
    }
  ]
}

nano-banana-2: Text-to-image ​

json
{
  "model": "nano-banana-2",
  "prompt": "A small orange cat on a clean white background, soft studio lighting.",
  "resolution": "1K"
}

nano-banana-2: Multiple reference images ​

json
{
  "model": "nano-banana-2",
  "prompt": "Keep the reference subject consistent and create a clean, naturally lit scene.",
  "resolution": "1K",
  "images": [
    {
      "url": "https://example.com/media/reference_1.jpg",
      "role": "reference"
    },
    {
      "url": "https://example.com/media/reference_2.jpg",
      "role": "reference"
    }
  ]
}

gpt-image-2.5: Text-to-image ​

json
{
  "model": "gpt-image-2.5",
  "prompt": "A small orange cat on a clean white background, soft studio lighting.",
  "resolution": "1K",
  "ratio": "1:1"
}

gpt-image-2.5: Multiple reference images ​

json
{
  "model": "gpt-image-2.5",
  "prompt": "Keep the reference subject consistent and create a clean, naturally lit scene.",
  "resolution": "1K",
  "ratio": "1:1",
  "images": [
    {
      "url": "https://example.com/media/reference_1.jpg",
      "role": "reference"
    },
    {
      "url": "https://example.com/media/reference_2.jpg",
      "role": "reference"
    }
  ]
}

gpt-image-2: Text-to-image ​

json
{
  "model": "gpt-image-2",
  "prompt": "A small orange cat on a clean white background, soft studio lighting.",
  "resolution": "1K",
  "ratio": "1:1"
}

gpt-image-2: Multiple reference images ​

json
{
  "model": "gpt-image-2",
  "prompt": "Keep the reference subject consistent and create a clean, naturally lit scene.",
  "resolution": "1K",
  "ratio": "1:1",
  "images": [
    {
      "url": "https://example.com/media/reference_1.jpg",
      "role": "reference"
    },
    {
      "url": "https://example.com/media/reference_2.jpg",
      "role": "reference"
    }
  ]
}

For a single reference image, keep only one item in images. For multiple references, submit the images in the intended array order.

7. Task Response Schema ​

Submission and query responses use the same top-level object. There is no data wrapper, no code/msg envelope, and no SSE stream.

FieldJSON typeDescription
task_idstringPlatform task UUID in canonical lowercase form
modelstringPlatform model name
modalitystringimage or video
statusstringqueued, running, succeeded, failed
artifactsarray<object>Complete delivered outputs; empty before delivery or on failure
failure_codestring / nullStable code for a confirmed failure
failure_reasonstring / nullSafe failure reason in the language of the current request
created_at, updated_atstringYYYY-MM-DD HH:mm:ss; no time-zone offset is included

artifacts[] fields ​

FieldJSON typeDescription
artifact_typestringimage, video, audio, or cover; actual outputs depend on the model
urlstringResource URL after the platform has completed delivery
mime_typestring / nullActual MIME type when available
size_bytesinteger / nullActual file size in bytes
width, heightinteger / nullActual pixel dimensions when known
duration_secondsstring / nullActual output duration in seconds as a decimal string; not copied from the requested duration

Completed delivery example ​

json
{
  "task_id": "550e8400-e29b-41d4-a716-446655440000",
  "model": "nano-banana-2.1",
  "modality": "image",
  "status": "succeeded",
  "artifacts": [
    {
      "artifact_type": "image",
      "url": "https://example.com/outputs/result.png",
      "mime_type": "image/png",
      "size_bytes": 2073482,
      "width": null,
      "height": null,
      "duration_seconds": null
    }
  ],
  "failure_code": null,
  "failure_reason": null,
  "created_at": "2026-11-05 10:00:00",
  "updated_at": "2026-11-05 10:01:00"
}

Optional metadata may be null. When present, response duration_seconds is a decimal string. Output dimensions, duration, image count, or audio tracks are not inferred or guaranteed from the request parameters. Do not attach your platform API key when downloading artifacts from a resource host.

8. Query Tasks and Interpret Status ​

Set TASK_ID to the task_id returned by submission, then query the task:

bash
curl --request GET "${API_BASE_URL}/api/v1/platform/tasks/${TASK_ID}" \
  --header "Authorization: Bearer ${API_KEY}" \
  --header "Accept-Language: en"

GET /api/v1/platform/tasks/{task_id}

The path parameter is the lowercase UUID returned by submission. You must use the same API key that created the task. Another key cannot read the task, even if it belongs to the same user. A task that does not exist or is inaccessible returns HTTP 404. Queries still enforce authentication and basic identity rate limits, but do not recheck the model's sale status or recalculate the task price.

statusMeaningClient action
queuedWaiting for submissionWait, then query again
runningGenerating, delivering, or recovering; the submission outcome may still be awaiting confirmationWait, then query again; do not submit a duplicate request
succeededAll artifacts have been delivered by the platformStop polling and read artifacts
failedConfirmed failureStop polling and read failure_code and failure_reason

Poll at a controlled interval, such as the 3 seconds used in the examples. A query for a failed task still returns HTTP 200; inspect status to determine the outcome. Stop on succeeded or failed, and set a finite client waiting budget for queued or running. A client timeout does not mean the task was cancelled, the upstream service did not execute it, or a refund was issued automatically. Keep the task ID for later queries and support. Contact support if the task remains unresolved; polling indefinitely does not guarantee automatic recovery.

The current API does not provide a task cancellation operation or completion callback parameter.

9. HTTP Errors and Task Failures ​

HTTP error schema ​

json
{
  "error": {
    "message": "Parameter resolution is required",
    "type": "invalid_request_error",
    "code": "invalid_request"
  }
}
HTTPerror.codeDescription
400invalid_requestInvalid JSON, missing required fields, invalid types or specifications, unknown fields, or a delisted model.
401unauthorizedMissing, invalid, disabled, or expired API key.
403access_deniedUser, IP, model permission, balance, or API-key quota restrictions.
404task_not_foundThe task does not exist or is inaccessible to the current user and the API key that created it.
405invalid_requestUnsupported HTTP method.
413invalid_requestThe raw JSON body exceeds 65535 bytes.
429rate_limitedIdentity, RPM, or concurrency limit exceeded.
500generation_configuration_invalid / internal_errorUnavailable configuration or an internal platform error.
502upstream_errorUpstream error status defined by the protocol; asynchronous failures after acceptance are normally reported through task results.
503no_available_channel / service_unavailableModel maintenance, no available channel, or temporarily unavailable infrastructure dependencies.

error.message is localized; error.type and error.code are stable identifiers. Error bodies do not expose raw upstream errors or contain a parameter-details array. error.type values are invalid_request_error, authentication_error, permission_error, not_found_error, rate_limit_error, and server_error. Parameter validation errors use HTTP 400, not 422. Task failures are expressed by the query response's status; handle HTTP parameter errors and task failures separately.

Asynchronous task failure ​

An accepted request may fail later. Query it with GET; do not expect the original HTTP 202 response to change to HTTP 502:

json
{
  "task_id": "550e8400-e29b-41d4-a716-446655440000",
  "model": "nano-banana-2.1",
  "modality": "image",
  "status": "failed",
  "artifacts": [],
  "failure_code": "upstream_rejected",
  "failure_reason": "Generation failed. Please try again later.",
  "created_at": "2026-11-05 10:00:00",
  "updated_at": "2026-11-05 10:01:00"
}

Declared failure_code values are content_policy, upstream_rejected, internal_error, unknown_error, timeout, and cancelled. These compatibility enum values do not imply that cancellation or automatic timeout refunds are available. Failure fields are null for non-failed states.

10. Complete Python Example ​

Use Python 3.11+ and install httpx:

bash
python -m pip install httpx

Configure API_BASE_URL and API_KEY before running. When changing models, also check the resolution, aspect ratio, and reference media requirements.

python
import json
import os
import random
import time

import httpx

BASE_URL = os.getenv("API_BASE_URL", "").rstrip("/")
API_KEY = os.getenv("API_KEY", "")
PAYLOAD = {
    "model": "nano-banana-2.1",
    "prompt": "A small orange cat on a clean white background, soft studio lighting.",
    "resolution": "1K",
    "ratio": "1:1"
}
MAX_WAIT_SECONDS = 1800  # Client waiting budget, not a service completion SLA.


def main():
    if not BASE_URL or not API_KEY:
        raise RuntimeError("Set API_BASE_URL and API_KEY before running.")
    deadline = time.monotonic() + MAX_WAIT_SECONDS
    with httpx.Client(follow_redirects=False) as client:
        def request_json(method, path, content=None):
            attempts = 3 if method == "GET" else 1
            for attempt in range(attempts):
                remaining = deadline - time.monotonic()
                if remaining <= 0:
                    raise TimeoutError("Client wait ended; the task is not cancelled.")
                headers = {"Authorization": f"Bearer {API_KEY}",
                           "Accept-Language": "en"}
                if content is not None:
                    headers["Content-Type"] = "application/json"
                try:
                    response = client.request(method, BASE_URL + path,
                        headers=headers, content=content,
                        timeout=min(30.0, remaining))
                except httpx.TransportError:
                    if method == "POST":
                        raise RuntimeError("Submission outcome is uncertain; do not automatically resubmit.") from None
                    if attempt == attempts - 1:
                        raise RuntimeError("Query temporarily failed; keep the task ID and query again later.") from None
                else:
                    if response.status_code == (202 if method == "POST" else 200):
                        try:
                            return response.json()
                        except ValueError:
                            raise RuntimeError("Cannot parse the response; do not automatically resend a submission. "
                                               "Query the existing task ID if available.") from None
                    if (method != "GET" or response.status_code not in (429, 500, 502, 503)
                            or attempt == attempts - 1):
                        try:
                            error = response.json().get("error", {})
                        except ValueError:
                            error = {}
                        raise RuntimeError(f"HTTP {response.status_code}; "
                                           f"code={error.get('code')}; "
                                           f"message={error.get('message')}")
                time.sleep(min(2 ** attempt + random.random(),
                               max(0, deadline - time.monotonic())))
            raise RuntimeError("Query retry budget exhausted; keep the task ID.")

        # Set TASK_ID to resume an existing task without creating another one.
        existing_task_id = os.getenv("TASK_ID", "").strip()
        if existing_task_id:
            task = request_json("GET", f"/api/v1/platform/tasks/{existing_task_id}")
        else:
            body = json.dumps(PAYLOAD, ensure_ascii=False,
                              allow_nan=False).encode("utf-8")
            task = request_json("POST", "/api/v1/platform/images/generations", body)
        task_id = task["task_id"]
        print("task_id:", task_id, flush=True)  # Save this to your business records immediately.
        while True:
            status = task["status"]
            if status == "succeeded":
                for artifact in task["artifacts"]:
                    print(artifact["artifact_type"], artifact["url"])
                return
            if status == "failed":
                raise RuntimeError(f"{task_id}: {task['failure_code']}; "
                                   f"{task['failure_reason']}")
            if status not in ("queued", "running"):
                raise RuntimeError(f"Unexpected task status: {status}")
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                raise TimeoutError(f"Task {task_id} is still pending; query again later.")
            time.sleep(min(3.0, remaining))
            task = request_json("GET", f"/api/v1/platform/tasks/{task_id}")


if __name__ == "__main__":
    main()

11. Complete JavaScript Example ​

Use Node.js 18+ with built-in fetch. Save the code as a .mjs file and run it on your server. Use the same environment variables as in the Python example.

javascript
import { setTimeout as sleep } from "node:timers/promises";

const baseUrl = (process.env.API_BASE_URL || "").replace(/\/+$/, "");
const apiKey = process.env.API_KEY || "";
if (!baseUrl || !apiKey)
  throw new Error("Set API_BASE_URL and API_KEY before running.");
const payload = {
  model: "nano-banana-2.1",
  prompt:
    "A small orange cat on a clean white background, soft studio lighting.",
  resolution: "1K",
  ratio: "1:1",
};
const deadline = Date.now() + 1800 * 1000; // Client waiting budget, not a service completion SLA.

async function requestJson(method, path, requestBody) {
  const attempts = method === "GET" ? 3 : 1;
  for (let attempt = 0; attempt < attempts; attempt++) {
    const remaining = deadline - Date.now();
    if (remaining <= 0)
      throw new Error("Client wait ended; the task is not cancelled.");
    const headers = {
      Authorization: `Bearer ${apiKey}`,
      "Accept-Language": "en",
    };
    if (requestBody !== undefined) headers["Content-Type"] = "application/json";
    let response;
    try {
      response = await fetch(baseUrl + path, {
        method,
        headers,
        body: requestBody,
        redirect: "error",
        signal: AbortSignal.timeout(Math.max(1, Math.min(30000, remaining))),
      });
    } catch {
      if (method === "POST")
        throw new Error(
          "Submission outcome is uncertain; do not automatically resubmit.",
        );
      if (attempt === attempts - 1)
        throw new Error(
          "Query temporarily failed; keep the task ID and query again later.",
        );
    }
    if (response) {
      if (response.status === (method === "POST" ? 202 : 200)) {
        try {
          return await response.json();
        } catch {
          throw new Error(
            "Cannot parse the response; do not automatically resend a submission. Query the existing task ID if available.",
          );
        }
      }
      if (
        method !== "GET" ||
        ![429, 500, 502, 503].includes(response.status) ||
        attempt === attempts - 1
      ) {
        const data = await response.json().catch(() => ({}));
        throw new Error(
          `HTTP ${response.status}; code=${data.error?.code}; ` +
            `message=${data.error?.message}`,
        );
      }
    }
    await sleep(
      Math.min(
        1000 * (2 ** attempt + Math.random()),
        Math.max(0, deadline - Date.now()),
      ),
    );
  }
  throw new Error("Query retry budget exhausted; keep the task ID.");
}

// Set TASK_ID to resume an existing task without creating another one.
const existingTaskId = (process.env.TASK_ID || "").trim();
let task = existingTaskId
  ? await requestJson("GET", `/api/v1/platform/tasks/${existingTaskId}`)
  : await requestJson(
      "POST",
      "/api/v1/platform/images/generations",
      JSON.stringify(payload),
    );
const taskId = task.task_id;
console.log("task_id:", taskId); // Save this to your business records immediately.
while (["queued", "running"].includes(task.status)) {
  const remaining = deadline - Date.now();
  if (remaining <= 0)
    throw new Error(`Task ${taskId} is still pending; query again later.`);
  await sleep(Math.min(3000, remaining));
  task = await requestJson("GET", `/api/v1/platform/tasks/${taskId}`);
}
if (task.status === "failed") {
  throw new Error(`${taskId}: ${task.failure_code}; ${task.failure_reason}`);
}
if (task.status !== "succeeded")
  throw new Error(`Unexpected task status: ${task.status}`);
for (const artifact of task.artifacts)
  console.log(artifact.artifact_type, artifact.url);

12. Frequently Asked Questions ​

SymptomWhat to check
Task remains running for a long timeGeneration, delivery retries, or an uncertain submission may be involved; keep the task ID and contact support.
HTTP 404 after switching API keysQuery using the API key that created the task.
Reference media processing failsCheck public accessibility, URL expiry, file validity, media roles, order, and model limits.
Metadata is nullUnknown optional metadata remains null; it is not inferred from the requested dimensions or duration.
Valid JSON still returns HTTP 400/503Check the model name and whether the model is delisted, under maintenance, or currently unavailable.

13. API Compatibility and Version Notes ​

This version uses the platform's own asynchronous protocol. Similar endpoint names do not imply drop-in compatibility with third-party synchronous image or video SDKs. When adapting an SDK, check HTTP 202 handling, task polling, and the response schema in this guide. Public request bodies do not accept stream, n, seed, provider routing fields, custom storage parameters, or webhook/callback parameters. Unknown parameters fail validation.

Model specifications reflect the published public rules as of the document date. Availability, prices, and quotas may change independently. Check the current model page before updating your integration, and retain task IDs for requests already in progress.