Blog

Tutorial

How to Use gpt-image-2.6-sunburst/image-to-image via the HiAPI API: curl and Python

Submit a reference image, poll the async job, and debug the request end to end

Nov 10, 2026 9 min read
Cover art for a HiAPI tutorial: thin paper layers receding into shallow depth in cream, graphite and one terracotta sheet.
On this page

What gpt-image-2.6-sunburst/image-to-image Is For

Text-to-image gives you whatever the model invents from a prompt. Image-to-image starts from something you already have: you hand the endpoint a reference image plus an instruction, and the model produces a new image derived from that reference. On HiAPI, gpt-image-2.6-sunburst/image-to-image is the endpoint dedicated to that second mode.

Choose it when the source image is part of the specification — restyling an existing asset, adjusting lighting or composition, applying a visual treatment to a product shot, or producing controlled variations of a design. The reference image is the anchor: it carries the subject, palette, and layout, and your prompt describes the transformation rather than describing the scene from scratch. If you have no source asset and just want an image from a description, a text-to-image endpoint is simpler and gives the model more freedom.

Two practical consequences shape everything below. First, the request carries binary-ish input (an image reference), which affects how you build the payload. Second, image generation is not instant, so the endpoint runs as an asynchronous job rather than returning an image inline. Plan for a submit step and a retrieval step, not a single blocking call.

Prerequisites and Auth Setup

Before your first request you need three things: a HiAPI account, an API key, and a way to reference your source image that the endpoint accepts. Create the key in your HiAPI console and treat it like a password — it authorizes every call billed to your account.

Pass the key in the Authorization header as a bearer token. Never hardcode it in source files, notebooks, or commit history. Export it as an environment variable for shell testing and read it from the environment (or a secrets manager) in application code:

export HIAPI_API_KEY="your_api_key_here"

Decide up front how you will supply the reference image. You generally either upload the asset to a temporary location and pass a URL, or send the image as base64-encoded data in the payload. URLs keep requests small and are easier to log; base64 avoids extra hosting but inflates the request body. Whatever you pick, keep files in formats the endpoint supports and check size limits before sending. Also note the base URL of the HiAPI API for your account — you will prefix every path below with it.

Submitting a Reference Image with curl

Start in the shell so you can see exactly what goes over the wire. The shape of the call is a POST to the image-to-image endpoint with a JSON body containing your reference image and your instruction.

curl -X POST "$HIAPI_BASE_URL/v1/images/generations" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-image-2.6-sunburst/image-to-image",
    "image": "https://your-bucket.example.com/reference.png",
    "prompt": "Repaint this scene in warm sunset tones, keep the composition and objects unchanged",
    "n": 1
  }'

Field by field: model selects the endpoint; image carries the reference (a URL here, or a base64 data string if you are not hosting the file); prompt is the edit instruction and should describe the change, not re-describe the subject; n is how many outputs you want. Keep prompt specific and scoped — instructions that contradict the reference image tend to produce muddled results.

Send the request and inspect the response body. With an async endpoint you will not receive the finished image; you will receive a job identifier or status object. Save that response before moving on — it is the handle for everything that follows. A quick sanity check with curl -i shows you the HTTP status code as well, which is the fastest way to tell an auth problem (4xx at submit time) from a content problem.

Doing the Same Call in Python

Once the shell call works, port it to Python. The standard library is enough, but requests keeps the example readable:

import os
import requests

API_KEY = os.environ["HIAPI_API_KEY"]
BASE_URL = os.environ["HIAPI_BASE_URL"]

payload = {
    "model": "gpt-image-2.6-sunburst/image-to-image",
    "image": "https://your-bucket.example.com/reference.png",
    "prompt": "Repaint this scene in warm sunset tones, keep the composition and objects unchanged",
    "n": 1,
}

resp = requests.post(
    f"{BASE_URL}/v1/images/generations",
    headers={"Authorization": f"Bearer {API_KEY}"},
    json=payload,
    timeout=60,
)
resp.raise_for_status()
job = resp.json()
print(job)

The differences from curl are mechanical: the key comes from os.environ, the body is a dict serialized as JSON, and raise_for_status() turns a failed submit into an exception instead of a silent error. That last line matters — most debugging pain comes from treating a 4xx response as success and then polling a job ID that never existed.

For binary inputs, read the file, base64-encode it, and put the string in image instead of a URL. Everything else in the payload stays the same, so you can switch styles without touching your request logic.

Handling the Async Job Lifecycle

Image generation takes time, so the endpoint follows a submit-then-poll pattern. Understand the three states and the rest is bookkeeping.

1. Submit and capture the job

Your POST returns a job identifier. Extract it immediately and persist it somewhere durable — a database row, a queue message, a log line you can query. If your process crashes between submit and poll, that identifier is the only way to recover the work you have already paid for.

2. Poll until the job is done

Poll a status endpoint with the job ID at a fixed interval. Start conservative — a couple of seconds between checks — and back off gradually for longer jobs so you do not hammer the API. Stop on a terminal state: success, failure, or a timeout you impose yourself. Never poll in a tight loop.

import time

def wait_for_job(job_id, base_url, api_key, timeout=300, interval=2):
    deadline = time.time() + timeout
    while time.time() < deadline:
        r = requests.get(
            f"{base_url}/v1/images/jobs/{job_id}",
            headers={"Authorization": f"Bearer {api_key}"},
            timeout=30,
        )
        r.raise_for_status()
        data = r.json()
        if data["status"] in ("succeeded", "failed"):
            return data
        time.sleep(interval)
        interval = min(interval * 1.5, 15)
    raise TimeoutError(f"job {job_id} not finished in time")

3. Fetch and store the result

On success, the response points at the generated image. Download it promptly if the URL is temporary, and write it to your own storage with a name you control, so downstream consumers never depend on a transient link. Record the job ID alongside the stored asset — it is the cheapest debugging aid you will have.

For production, drive polling from a background worker rather than a request handler. A web request that blocks for the length of an image generation is fragile and ties up a connection for no reason.

Common Errors and How to Fix Them

Work this list top-down when a call fails; the first item catches most problems.

401 / 403 at submit time

Auth. Check that the key is present in the Authorization header, uses the Bearer scheme, and has no stray whitespace or newline from a copy-paste. Confirm the environment variable is actually set in the shell or process that runs the request.

400 / 422 on the payload

The body is malformed or a field is wrong. Common culprits: a JSON syntax error from manual curl strings, an image value that is neither a reachable URL nor valid base64, a missing prompt, or an unsupported image format. Validate the JSON locally and confirm the reference actually loads in a browser.

404 on the model or path

A path or model-name typo. Model identifiers are exact strings — gpt-image-2.6-sunburst/image-to-image is not the same as a text-to-image variant, and case matters.

Timeouts and hung polls

Distinguish a slow job from a broken one. Set a timeout on every HTTP call, impose your own overall deadline, and log the last observed job status when you give up. If jobs routinely exceed your deadline, raise it rather than switching to a tight retry loop.

Empty or unusable output

The job succeeded but the image is not what you wanted. This is usually a prompt problem: instructions too vague, or ones that conflict with the reference. Make the edit instruction more specific about what should change and what must stay identical.

Production Tips for Image-to-Image Pipelines

Once the prototype works, the remaining work is reliability and predictability.

  • Retry only what is retryable. Retry failed submits on 5xx and network errors with exponential backoff; do not blindly retry 4xx, which will just fail again. Track idempotency yourself by keying jobs to your own request IDs so a retry does not duplicate work.
  • Separate submit from poll. Put submission and polling in different workers or stages. This keeps latency in your API independent of generation time and lets you scale polling separately.
  • Own your storage. Download results into your own bucket as soon as a job completes. Treat returned URLs as ephemeral.
  • Keep prompts under version control. Prompts are production artifacts. Store the prompt, reference image, and job ID with every output so you can reproduce or explain a result months later.
  • Watch latency and spend. Image jobs are billed by output, so cap concurrency per user and log usage per job. Monitor p95 latency from submit to stored asset — that is the number your users feel.

With the request shape and lifecycle settled, the rest is ordinary engineering. You can find the model details in the HiAPI documentation and wire the endpoint into your pipeline from there.

Related articles

View all articles →

Start building with persistent AI artifacts

Get your API key and call image, video and audio models through one task-based API.

Read the API docs