Skip to content
Reading settings
GPT Image

gpt-image-2.6 API Developer Guide ​

Version 1.0 · Updated 2026-11-11

1. Model and API Overview ​

Set model to gpt-image-2.6. The model supports 1K text-to-image and reference-based generation with PNG, GIF, or SVG output. Save the task_id from the submission response to query the task status and its artifacts.

ItemDescription
Modelgpt-image-2.6
OutputImage
Input scenariosText, single reference image, or multiple reference images
Billing methodPer 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, pricing, and quotas.

2. Authentication and Environment Setup ​

HeaderRequiredDescription
AuthorizationYesSend the platform API key as Bearer <API_KEY>.
Content-TypeRequired for POSTapplication/json
Accept-LanguageNozh-CN, zh-Hant, or en. Defaults to Simplified Chinese.

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

Set API_BASE_URL to your API service root. The examples already include the full endpoint paths.

Set the environment variables in Bash.

bash
export API_BASE_URL=""
export API_KEY=""

Set the environment variables in PowerShell.

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

3. Create a Generation Task ​

POST /api/v1/platform/images/generations

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

ParameterJSON typeRequiredDescription
modelstringYesMust be gpt-image-2.6
promptstringYesNon-empty generation prompt.
resolutionstringYesOutput resolution tier. Supports 1K.
ratiostringYesOutput aspect ratio. See the next section for allowed values.
qualitystringNoImage quality. Use auto for automatic quality selection.
output_formatstringNoOutput format. Choose png for a PNG bitmap, gif for a GIF image, or svg for an SVG vector image.
imagesarray<object>NoOrdered reference images. Each item contains url and role.
audios, videosarray<object>NoOmit these fields for this model. Non-empty arrays cause a validation error.

The top-level JSON object must fit in a request body of at most 65535 bytes. The API rejects unknown fields, duplicate JSON keys, and non-finite numbers. If you omit quality or output_format, the platform leaves the corresponding field unset.

For declared fields, null, empty strings, whitespace-only strings, and the case-insensitive string null are treated as omitted. The API reports missing required fields and validates 0, false, empty arrays, and empty objects according to each field's rules.

4. Model Specifications and Reference Media ​

ParameterRequiredAllowed values
resolutionYes1K
ratioYes1: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
qualityNoauto
output_formatNopng, gif, svg

Omit images or send an empty array for text-to-image generation. Provide one or more images for reference-based generation. The API preserves array order and requires reference as the role of each reference image.

The published specifications do not set a fixed limit on the number of reference images. Follow the model service's media limits and the request body size limit.

Parameter values are case-sensitive. Set ratio to an aspect ratio string and resolution to a resolution tier string.

Reference media object ​

FieldJSON typeRequiredDescription
urlstringYesPublicly readable HTTP or HTTPS file URL. HTTPS is recommended.
rolestringYesMust be reference for reference media.

Use public file URLs that the model service can access directly. Signed URLs must remain valid through queueing and media retrieval. Replace the example.com URLs with your own reference 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": "gpt-image-2.6",
  "prompt": "Create a simple vector icon of a small orange cat on a plain white background.",
  "resolution": "1K",
  "ratio": "1:1",
  "quality": "auto",
  "output_format": "svg"
}'

The API returns HTTP 202 when it accepts the task.

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

Save the task_id and use the same API key to query it.

6. Generation Examples ​

Text-to-image ​

json
{
  "model": "gpt-image-2.6",
  "prompt": "Create a simple vector icon of a small orange cat on a plain white background.",
  "resolution": "1K",
  "ratio": "1:1",
  "quality": "auto",
  "output_format": "svg"
}

Single reference image ​

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

Multiple reference images ​

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

The API preserves the order of items in images.

7. Task Response Schema ​

Submission and query endpoints return the same top-level JSON object without a data wrapper, a code/msg envelope, or SSE streaming.

FieldJSON typeDescription
task_idstringLowercase platform UUID.
modelstringgpt-image-2.6
modalitystringimage
statusstringqueued, running, succeeded, failed
artifactsarray<object>List of all delivered artifacts. Empty before delivery or if the task fails.
failure_codestring / nullStable code for a confirmed failure.
failure_reasonstring / nullPublic failure reason in the language of the current request.
created_at, updated_atstringYYYY-MM-DD HH:mm:ss without a time zone offset.

Fields in artifacts[] ​

FieldJSON typeDescription
artifact_typestringThis model returns image.
urlstringURL of the delivered artifact.
mime_typestring / nullActual MIME type, when available.
size_bytesinteger / nullSize in bytes.
width, heightinteger / nullActual dimensions in pixels, when known.
duration_secondsstring / nullArtifact duration in seconds, represented as a decimal string when available.

The artifact MIME types are image/png for png, image/gif for gif, and image/svg+xml for svg. The platform delivers SVG artifacts as attachments.

Successful delivery example ​

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

Optional metadata can be null. When present, duration_seconds is a decimal string. Download the artifact from its url without sending your platform API key.

8. Task Queries and Statuses ​

Set TASK_ID to the task_id from the submission response before querying 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 from the submission response. Use the same API key that created the task. The API returns HTTP 404 if the task does not exist or the key cannot access it.

statusMeaningClient action
queuedQueued for submission.Wait and query again.
runningGenerating, delivering, recovering, or awaiting confirmation of submission.Wait and query again without resubmitting.
succeededThe platform has delivered all artifacts.Stop polling and read artifacts.
failedThe task has failed.Stop polling and read failure_code and failure_reason.

Poll every 3 seconds and set a maximum wait time. A query for a failed task still returns HTTP 200, so read status to determine the outcome. If the client times out, keep the task_id to resume polling later.

9. HTTP Errors and Task Failures ​

HTTP error schema ​

json
{
  "error": {
    "message": "The resolution parameter is required.",
    "type": "invalid_request_error",
    "code": "invalid_request"
  }
}
HTTPerror.codeDescription
400invalid_requestInvalid request format or parameters, or the model has been withdrawn.
401unauthorizedThe API key is missing, invalid, disabled, or expired.
403access_deniedAccess is blocked by account, IP, model permission, balance, or API key quota restrictions.
404task_not_foundThe task does not exist or does not belong to the current user and API key that created it.
405invalid_requestThe HTTP method is unsupported.
413invalid_requestThe raw JSON body exceeds 65535 bytes.
429rate_limitedAn identity-based rate limit, requests-per-minute limit, or concurrency limit was reached.
500generation_configuration_invalid / internal_errorUnavailable configuration or an internal platform error.
502upstream_errorUpstream service error. Asynchronous failures after acceptance appear in the task status.
503no_available_channel / service_unavailableModel maintenance, no available provider channel, or a temporarily unavailable dependency.

error.message is localized. error.type and error.code are stable identifiers. The API returns HTTP 400 for validation errors, including unsupported quality or output_format values.

Asynchronous task failure ​

If a task fails after acceptance, the query response shows failed and includes the failure code and reason.

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

failure_code identifies the confirmed failure, and failure_reason uses the language of the current request. Both fields are null in other task states.

10. Python Complete Example ​

Use Python 3.11+ with httpx.

bash
python -m pip install httpx

Set API_BASE_URL and API_KEY before running the example. Use values that meet this model's 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": "gpt-image-2.6",
    "prompt": "Create a simple vector icon of a small orange cat on a plain white background.",
    "resolution": "1K",
    "ratio": "1:1",
    "quality": "auto",
    "output_format": "svg"
}
MAX_WAIT_SECONDS = 1800  # Maximum time the client waits for the task.


def main():
    if not BASE_URL or not API_KEY:
        raise RuntimeError("Set API_BASE_URL and API_KEY.")
    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("The client stopped waiting. The task continues on the server.")
                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 unknown. Do not resubmit automatically.") from None
                    if attempt == attempts - 1:
                        raise RuntimeError("The query failed temporarily. Save the task ID and try again later.") from None
                else:
                    if response.status_code == (202 if method == "POST" else 200):
                        try:
                            return response.json()
                        except ValueError:
                            raise RuntimeError("Could not parse the response. Do not resubmit automatically. "
                                               "If you have a task ID, continue polling.") 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 retries exhausted. Save the task ID.")

        # Set TASK_ID to resume querying an existing task.
        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 the ID in your application 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"Unknown task status:{status}")
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                raise TimeoutError(f"Task {task_id} is still in progress. Resume polling later.")
            time.sleep(min(3.0, remaining))
            task = request_json("GET", f"/api/v1/platform/tasks/{task_id}")


if __name__ == "__main__":
    main()

11. JavaScript Complete Example ​

Use the built-in fetch in Node.js 18+. Save the code as an .mjs file and run it on the server. Set 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.");
const payload = {
  model: "gpt-image-2.6",
  prompt:
    "Create a simple vector icon of a small orange cat on a plain white background.",
  resolution: "1K",
  ratio: "1:1",
  quality: "auto",
  output_format: "svg",
};
const deadline = Date.now() + 1800 * 1000; // Maximum time the client waits for the task.

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("The client stopped waiting. The task continues on the server.");
    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 unknown. Do not resubmit automatically.");
      if (attempt === attempts - 1)
        throw new Error("The query failed temporarily. Save the task ID and try again later.");
    }
    if (response) {
      if (response.status === (method === "POST" ? 202 : 200)) {
        try {
          return await response.json();
        } catch {
          throw new Error(
            "Could not parse the response. Do not resubmit automatically. If you have a task ID, continue polling.",
          );
        }
      }
      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 retries exhausted. Save the task ID.");
}

// Set TASK_ID to resume querying an existing task.
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 the ID in your application records immediately.
while (["queued", "running"].includes(task.status)) {
  const remaining = deadline - Date.now();
  if (remaining <= 0)
    throw new Error(`Task ${taskId} is still in progress. Resume polling 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(`Unknown task status:${task.status}`);
for (const artifact of task.artifacts)
  console.log(artifact.artifact_type, artifact.url);

12. FAQ ​

SymptomWhat to check
Task stays runningThe platform may still be generating, delivering, or confirming submission. Keep the task ID and contact support.
Query returns 404 with a different API keyQuery with the API key that created the task.
Reference media processing failsCheck public access, URL expiry, file validity, role, order, and model limits.
Metadata is nullUnknown optional metadata stays null. The platform does not infer it from requested dimensions or duration.
Valid JSON still returns 400 or 503Check the model identifier and whether the model is withdrawn, under maintenance, or currently unavailable.

13. API Compatibility and Versioning ​

The API uses the platform's asynchronous protocol. SDKs should handle HTTP 202, task polling, and the response schemas in this guide.