gpt-image-2.5 API Developer Guide
Version: 1.2 · Updated: 2026-11-07
1. Model and API Overview
This guide covers only gpt-image-2.5. Use this exact value in the model field. Submit a generation request to obtain a task_id, then query it for its status and delivered artifacts.
| Item | Description |
|---|---|
| Model | gpt-image-2.5 |
| Output | Image |
| Input scenarios | Text, single reference image, and multiple reference images |
| Billing method | Per request |
| Method | Path | Success status code |
|---|---|---|
| POST | /api/v1/platform/images/generations | 202 |
| GET | /api/v1/platform/tasks/{task_id} | 200 |
Refer to the console for current model availability, access permissions, and prices.
2. Authentication and Environment Setup
| Header | Required | Description |
|---|---|---|
Authorization | Yes | Bearer <API_KEY>; use a platform API key |
Content-Type | Required for POST | application/json |
Accept-Language | No | zh-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:
export API_BASE_URL=""
export API_KEY=""PowerShell environment variables:
$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.
| Parameter | JSON type | Required | Description |
|---|---|---|---|
model | string | Yes | Must be gpt-image-2.5 |
prompt | string | Yes | Non-empty generation prompt |
resolution | string | Yes | 1K |
ratio | string | Yes | Output aspect ratio; allowed values are listed below. No platform default is inserted. |
images | array<object> | No | Ordered reference images; each item is an object containing url and role |
audios, videos | array<object> | No | Reserved fields; this model does not support non-empty arrays. Omit them. |
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
| Parameter | Required | Allowed values |
|---|---|---|
resolution | Yes | 1K |
ratio | Yes | 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 |
This model supports 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. The only supported role is reference; 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.
resolution and ratio are both required.
Reference media object
| Field | JSON type | Required | Description |
|---|---|---|---|
url | string | Yes | Publicly readable HTTP/HTTPS file URL; HTTPS is recommended |
role | string | Yes | Must 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.
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.5",
"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:
{
"task_id": "550e8400-e29b-41d4-a716-446655440000",
"model": "gpt-image-2.5",
"modality": "image",
"status": "queued",
"artifacts": [],
"failure_code": null,
"failure_reason": null,
"created_at": "2026-11-07 10:00:00",
"updated_at": "2026-11-07 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. Generation Examples
Text-to-image
{
"model": "gpt-image-2.5",
"prompt": "A small orange cat on a clean white background, soft studio lighting.",
"resolution": "1K",
"ratio": "1:1"
}Single reference image
{
"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"
}
]
}Multiple reference images
{
"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"
}
]
}The order of items in images is preserved.
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.
| Field | JSON type | Description |
|---|---|---|
task_id | string | Platform task UUID in canonical lowercase form |
model | string | gpt-image-2.5 |
modality | string | image |
status | string | queued, running, succeeded, failed |
artifacts | array<object> | Complete delivered outputs; empty before delivery or on failure |
failure_code | string / null | Stable code for a confirmed failure |
failure_reason | string / null | Safe failure reason in the language of the current request |
created_at, updated_at | string | YYYY-MM-DD HH:mm:ss; no time-zone offset is included |
artifacts[] fields
| Field | JSON type | Description |
|---|---|---|
artifact_type | string | image, video, audio, or cover; actual outputs depend on the model |
url | string | Resource URL after the platform has completed delivery |
mime_type | string / null | Actual MIME type when available |
size_bytes | integer / null | Actual file size in bytes |
width, height | integer / null | Actual pixel dimensions when known |
duration_seconds | string / null | Actual output duration in seconds as a decimal string; not copied from the requested duration |
Completed delivery example
{
"task_id": "550e8400-e29b-41d4-a716-446655440000",
"model": "gpt-image-2.5",
"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-07 10:00:00",
"updated_at": "2026-11-07 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:
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.
| status | Meaning | Client action |
|---|---|---|
queued | Waiting for submission | Wait, then query again |
running | Generating, delivering, or recovering; the submission outcome may still be awaiting confirmation | Wait, then query again; do not submit a duplicate request |
succeeded | All artifacts have been delivered by the platform | Stop polling and read artifacts |
failed | Confirmed failure | Stop 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
{
"error": {
"message": "Parameter resolution is required",
"type": "invalid_request_error",
"code": "invalid_request"
}
}| HTTP | error.code | Description |
|---|---|---|
| 400 | invalid_request | Invalid JSON, missing required fields, invalid types or specifications, unknown fields, or a delisted model. |
| 401 | unauthorized | Missing, invalid, disabled, or expired API key. |
| 403 | access_denied | User, IP, model permission, balance, or API-key quota restrictions. |
| 404 | task_not_found | The task does not exist or is inaccessible to the current user and the API key that created it. |
| 405 | invalid_request | Unsupported HTTP method. |
| 413 | invalid_request | The raw JSON body exceeds 65535 bytes. |
| 429 | rate_limited | Identity, RPM, or concurrency limit exceeded. |
| 500 | generation_configuration_invalid / internal_error | Unavailable configuration or an internal platform error. |
| 502 | upstream_error | Upstream error status defined by the protocol; asynchronous failures after acceptance are normally reported through task results. |
| 503 | no_available_channel / service_unavailable | Model 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:
{
"task_id": "550e8400-e29b-41d4-a716-446655440000",
"model": "gpt-image-2.5",
"modality": "image",
"status": "failed",
"artifacts": [],
"failure_code": "upstream_rejected",
"failure_reason": "Generation failed. Please try again later.",
"created_at": "2026-11-07 10:00:00",
"updated_at": "2026-11-07 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:
python -m pip install httpxConfigure API_BASE_URL and API_KEY before running. Use parameter values that meet this model’s resolution, aspect ratio, and reference media requirements.
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.5",
"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.
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": "gpt-image-2.5",
"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
| Symptom | What to check |
|---|---|
| Task remains running for a long time | Generation, delivery retries, or an uncertain submission may be involved; keep the task ID and contact support. |
| HTTP 404 after switching API keys | Query using the API key that created the task. |
| Reference media processing fails | Check public accessibility, URL expiry, file validity, media roles, order, and model limits. |
| Metadata is null | Unknown optional metadata remains null; it is not inferred from the requested dimensions or duration. |
| Valid JSON still returns HTTP 400/503 | Check 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.

