how-tos

GPT Image 2 API Guide: First Request in cURL and Python

Poyo.ai Team
9 min read
Share:

GPT Image 2 API Guide: First Request in cURL and Python

The GPT Image 2 API on PoYo exposes two model IDs—gpt-image-2 for text-to-image (and optional reference-image-guided generation) and gpt-image-2-edit for image editing—behind one asynchronous submit-and-poll workflow. You send a JSON payload to POST https://api.poyo.ai/api/generate/submit, capture the returned task_id, and retrieve the output image via GET https://api.poyo.ai/api/generate/status/{task_id} or an optional callback_url.

If you want to test prompts visually before writing code, open the GPT Image 2 playground. For the raw OpenAPI schema, see the PoYo GPT Image 2 API documentation, and if you are sorting out OpenAI's consumer versus developer naming, read ChatGPT Images 2.0 vs GPT Image 2 API.

Get a PoYo API key and choose a model ID

All PoYo endpoints authenticate with a Bearer token in the Authorization header. To create a key, sign in to PoYo, open Dashboard -> API Key, generate a new key, and export it into your backend environment as POYO_API_KEY. Never embed the key in browser JavaScript or mobile binaries.

Pick the model ID that matches your workflow:

Model IDPrimary modeimage_urls fieldOutput per request
gpt-image-2Text-to-image and optional reference-guided generationOptional (string[])1 image
gpt-image-2-editNatural-language image editing from one or more source imagesRequired (string[])1 image

Both model IDs hit the same submit and status endpoints and share the same quality, size, and resolution schema.

Send your first GPT Image 2 API request with cURL

Export POYO_API_KEY in your shell and submit a 1K low-quality text-to-image task. Keeping the first test on low and 1K verifies your credentials and payload parsing for 2 credits ($0.01).

curl --fail-with-body https://api.poyo.ai/api/generate/submit \
  -H "Authorization: Bearer $POYO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-image-2",
    "input": {
      "prompt": "A studio product photo of a silver espresso machine on a clean white background, realistic lighting, high detail",
      "quality": "low",
      "size": "1:1",
      "resolution": "1K"
    }
  }'

A successful submission returns JSON with "code": 200 and a data object containing task_id, status (initially not_started), and created_time. Submission does not return the finished image immediately. Poll the status endpoint with the returned task_id:

curl --fail-with-body \
  https://api.poyo.ai/api/generate/status/YOUR_TASK_ID \
  -H "Authorization: Bearer $POYO_API_KEY"

Task statuses progress through not_started, running, and finally either finished or failed. When status becomes finished, read the generated image URL from data.files. If you prefer push notifications over polling, include a top-level callback_url in the submit body; PoYo sends a POST request to that URL when the task reaches finished or failed.

Edit images with gpt-image-2-edit (image-to-image)

For image-to-image editing—such as swapping backgrounds, adjusting lighting, or combining elements from multiple reference photos—set "model": "gpt-image-2-edit" and supply one or more publicly accessible URLs in input.image_urls:

{
  "model": "gpt-image-2-edit",
  "callback_url": "https://your-domain.com/callback",
  "input": {
    "prompt": "Use these reference images together to create a polished product photo: keep the flower subject, use the vase shape from the second image, replace the background with a clean white studio backdrop, and add a soft natural shadow",
    "image_urls": [
      "https://example.com/flower.jpg",
      "https://example.com/vase.jpg"
    ],
    "quality": "high",
    "size": "1:1",
    "resolution": "1K"
  }
}

Make sure every URL in image_urls is directly reachable over HTTPS without login cookies or expiring localhost tunnels. If you want text-to-image generation loosely guided by references rather than a strict edit, you can pass image_urls to gpt-image-2 instead, while keeping gpt-image-2-edit for dedicated edit tasks.

Run a bounded Python polling loop

In production services, always wrap submit and status calls in a helper that checks both the HTTP status code and PoYo's JSON code field. Some validation errors return HTTP 200 with a non-200 business code (such as 400) inside the body. The script below submits a gpt-image-2 request, stores the task_id, and polls with a hard deadline so a slow upstream job cannot hang a worker indefinitely.

import os
import time
import requests

BASE_URL = "https://api.poyo.ai"
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['POYO_API_KEY']}"


def checked(response: requests.Response) -> dict:
    response.raise_for_status()
    body = response.json()
    if body.get("code") != 200:
        err = body.get("error") or {}
        message = err.get("message") or body.get("message") or f"PoYo error code {body.get('code')}"
        raise RuntimeError(message)
    return body["data"]


payload = {
    "model": "gpt-image-2",
    "input": {
        "prompt": "A ceramic pour-over coffee dripper on a warm oak counter, soft window light, editorial product photo",
        "quality": "medium",
        "size": "16:9",
        "resolution": "2K",
    },
}

task = checked(session.post(f"{BASE_URL}/api/generate/submit", json=payload, timeout=60))
task_id = task["task_id"]
print("Submitted task:", task_id, flush=True)

deadline = time.monotonic() + 600
while time.monotonic() < deadline:
    status_data = checked(
        session.get(f"{BASE_URL}/api/generate/status/{task_id}", timeout=60)
    )
    state = status_data["status"]
    if state == "failed":
        raise RuntimeError(status_data.get("error_message") or "Image generation failed")
    if state == "finished":
        files = status_data.get("files") or []
        image_urls = [f["file_url"] for f in files if f.get("file_url")]
        if not image_urls:
            raise RuntimeError(f"Task {task_id} finished with no output file URL")
        print("Output URL:", image_urls[0])
        break
    time.sleep(5)
else:
    raise TimeoutError(f"Timed out waiting for task {task_id}; poll again before resubmitting")

Notice the timeout behavior: if the loop hits deadline, it raises TimeoutError with the saved task_id instead of resubmitting. Resubmitting blindly on a client timeout can create a duplicate billable generation.

Input fields, resolution, and custom-size rules

Validate every request parameter on your server before sending it to PoYo so you avoid avoidable 400 responses and unexpected resolution downgrades.

Complete input schema

FieldTypeDefaultRules and accepted values
promptstringRequiredGeneration or edit prompt, up to 20,000 characters
qualitystring"low""low", "medium", or "high"
sizestring"auto""auto", "1:1", "2:3", "3:2", "4:3", "3:4", "4:5", "5:4", "16:9", "9:16", "21:9", or custom WIDTHxHEIGHT
resolutionstring"1K""1K", "2K", or "4K"
image_urlsstring[]Optional / RequiredOptional on gpt-image-2; required on gpt-image-2-edit; supports multiple URLs

Resolution and custom WIDTHxHEIGHT constraints

Four rules govern how size and resolution interact on PoYo's GPT Image 2 endpoint:

  1. auto or omitted size always uses 1K. Even if you set "resolution": "2K" or "4K", leaving size unset or set to "auto" forces 1K output.
  2. Custom pixel dimensions require 2K or 4K. Passing a custom WIDTHxHEIGHT string (for example, "2304x1536") requires "resolution": "2K" or "4K".
  3. True 4K only applies to specific aspect ratios and edges. "resolution": "4K" applies to 16:9, 9:16, 21:9, or custom sizes that have a 3840-pixel edge. Any other 4K request automatically downgrades to 2K.
  4. Custom WIDTHxHEIGHT geometry limits: Both width and height must be divisible by 16, the maximum edge length is 3840 pixels, the aspect ratio cannot exceed 3:1, and total pixel count must stay between 655,360 and 8,294,400 pixels.

Here is a valid custom-size request body (2304x1536 is divisible by 16, has a 3:2 ratio, and totals 3,538,944 pixels):

{
  "model": "gpt-image-2",
  "input": {
    "prompt": "A minimalist architectural interior with travertine walls and afternoon sunlight",
    "quality": "medium",
    "size": "2304x1536",
    "resolution": "2K"
  }
}

Errors worth handling in production

PoYo returns a business status code in every JSON response alongside standard HTTP status codes. Handle these codes explicitly in your worker queue:

Business codeMeaningRecommended action
400Invalid request parametersFix payload validation (missing image_urls on gpt-image-2-edit, custom size not divisible by 16, or prompt over 20,000 characters). Do not retry unchanged.
401Missing or invalid API keyVerify Authorization: Bearer $POYO_API_KEY and key status in Dashboard -> API Key.
402Insufficient creditsAlert billing or pause non-critical batch jobs until credits are topped up.
403 / 404Permission denied / Resource not foundCheck endpoint path and task_id spelling.
408 / 429Request timeout / Rate limit exceededApply exponential backoff with jitter before retrying submissions.
500 / 502 / 503Internal or upstream service errorRetry with bounded backoff; if a task_id was already issued, poll its status first.

If a task transitions to failed during processing, inspect error_message on the status payload and log the task_id. Failed tasks are refunded automatically on PoYo, so you do not lose credits on upstream generation failures.

How your first bill is calculated

PoYo charges a fixed per-generation rate determined by quality and resolution, where 1 credit equals $0.005 (with an extra 10% off on large top-ups). Each request generates one image, and failed tasks are refunded automatically.

At 1K resolution, your first test call costs:

  • low + 1K: 2 credits ($0.01)
  • medium + 1K: 8.48 credits ($0.0424)
  • high + 1K: 33.76 credits ($0.1688)

Higher resolutions (2K and 4K) carry their own fixed per-image credit rates. For the complete 3 × 3 pricing matrix across low, medium, and high at 1K, 2K, and 4K—plus worked batch estimates—see the GPT Image 2 API pricing guide. If you are optimizing cost and turnaround for new workloads, also compare GPT Image 2.5 vs GPT Image 2 before scaling up batch volume.

Frequently asked questions

Where do I get a GPT Image 2 API key for PoYo? Sign in to your PoYo account, open Dashboard -> API Key, and create a key. Pass it as Authorization: Bearer $POYO_API_KEY on every POST /api/generate/submit and GET /api/generate/status/{task_id} call.

What is the difference between gpt-image-2 and gpt-image-2-edit? Use gpt-image-2 for text-to-image generation and optional reference-image-guided generation. Use gpt-image-2-edit when editing one or more existing images with a text instruction; gpt-image-2-edit requires at least one URL in image_urls.

Can I generate multiple images in a single GPT Image 2 API request? No. Each request to gpt-image-2 or gpt-image-2-edit returns 1 image. To generate multiple variations, submit concurrent tasks from your backend and track each task_id.

Why did my request with size: "auto" ignore resolution: "2K"? By design, omitting size or setting size to "auto" always renders at 1K resolution regardless of the resolution value. Pass an explicit aspect ratio (such as "1:1" or "16:9") or a valid custom WIDTHxHEIGHT string to use 2K or 4K.

Do I need to poll if I configure callback_url? No. When you include a top-level callback_url, PoYo posts the final result to your webhook when the task reaches finished or failed. You can still query GET /api/generate/status/{task_id} as a fallback if your webhook receiver misses a delivery.

Am I billed if a GPT Image 2 API task fails? No. Failed tasks are automatically refunded on PoYo. You only pay the fixed per-image credit rate for completed generations.

Share: