Tutorial
How to Call gpt-image-2.6-flare/image-to-image via the HiAPI API: curl & Python
Reference image upload, sync vs async requests, and debugging a working call
On this page
What this endpoint does and when to use image-to-image
Text-to-image models are great at inventing scenes from scratch, but many production tasks start with an image you already have. gpt-image-2.6-flare/image-to-image is the HiAPI endpoint for those tasks: you send a reference image together with a prompt, and the model returns a transformed image that follows your instructions while staying anchored to the reference.
Typical use cases include:
- Style transfer and restyling — turn a product shot into a stylized illustration, or repaint a photo in a different visual language.
- Edits and touch-ups — adjust lighting, background, or composition on an existing asset without re-shooting.
- Variation generation — produce multiple visual variants of a base design for A/B tests or creative exploration.
- Asset adaptation — resize or re-frame a reference for different channels while preserving its core subject.
If your task is "describe something and get an image," text-to-image is the simpler choice. Reach for image-to-image when the output must visibly derive from a specific input image — that reference is the whole point of the call. In the rest of this guide we'll wire up a real request end to end, first with curl to prove it works, then in Python so you can drop it into a service.
Prerequisites and request anatomy
Before calling the endpoint, make sure you have the following in place:
- A HiAPI account and API key. The key is sent as a bearer token in the
Authorizationheader. Keep it out of source control and load it from an environment variable such asHIAPI_API_KEY. - The model id. Use exactly
gpt-image-2.6-flare/image-to-image— model ids are case-sensitive and the slash is part of the identifier. - The endpoint path. Image generation lives under the image generation route on the HiAPI API host. Check the model page for the current base URL and path rather than hard-coding a host you saw in an old snippet.
- A reference image file in a common format (PNG or JPEG is the safe default). Keep it reasonably sized; oversized files slow down upload and can trip request limits.
A gpt-image-2.6-flare/image-to-image request has three moving parts:
- The model selector — tells HiAPI which model to route to.
- The prompt — a text instruction describing the transformation you want. This is not optional; the prompt is what steers the edit.
- The reference image — the input image the model should work from. How you pass it depends on the request style (see the next section).
Beyond these, only pass parameters that are documented for this model on its HiAPI model page. If you find yourself inventing a field name because it "seems right," stop and check the docs — unknown parameters are a common source of confusing 4xx errors.
How to pass the reference image
Conceptually, the reference image is just another input field in the request body — but its size makes it special. There are two practical ways to get bytes to the API, and the choice affects your client code more than the API itself.
Option A: Inline in the request body
Small images can be embedded directly in the JSON payload, typically as a base64-encoded string. You read the file, encode it, and place the string in the image field of the request. This keeps everything in one request and works well for thumbnails, icons, and test fixtures.
The trade-offs: base64 inflates the payload by roughly a third, JSON encoders can choke on very large strings, and debugging a multi-megabyte body in logs is painful. Inline is for convenience, not for large assets.
Option B: Upload first, reference by URL
For anything beyond small images, upload the file to storage you control, then pass its URL as the reference. Your request body stays tiny, retries are cheap, and the same image can be reused across many calls without re-uploading each time.
A few things to watch for with URLs:
- The URL must be publicly reachable by the API — not behind auth, not on localhost, not an expiring signed link that dies mid-request.
- Use a content-type the model accepts; a URL that serves HTML instead of an image will fail validation.
- Prefer a stable filename so you can correlate logs between your storage and your HiAPI requests.
Whichever route you pick, the reference image and the prompt travel in the same request. There is no separate "upload then generate" handshake required by the API — the model call is a single logical operation.
Synchronous versus asynchronous calls
Image generation takes time, which is why many image APIs expose an asynchronous job style alongside a synchronous one. The same trade-off applies here.
Synchronous
You send the request and hold the connection open until the image comes back. Your code is a single straight line: build request, POST, read response, done.
Use synchronous calls when:
- You're prototyping or debugging and want to see the full result in one step.
- The request runs in a context where blocking for a while is acceptable (a CLI tool, a background worker).
- You want the simplest possible client with no polling logic.
The downside is that long generations mean long-held connections, and any proxy or load balancer between you and the API may impose its own timeout.
Asynchronous
You submit the request as a job, get back a job identifier immediately, and then poll (or receive a callback) until the job completes. Your client needs a small state machine: submit, wait, fetch result, handle failure.
Use asynchronous calls when:
- You're serving user-facing traffic and can't afford to block a request thread.
- You're batching many generations and want to fan them out and collect results.
- Your infrastructure has short request timeouts that you don't control.
How to choose: if a human is waiting on the result in a web request, go async. If a script or worker is doing the waiting offline, sync is fine and simpler. Don't over-engineer: start sync, and move to async when a real timeout or concurrency constraint forces it.
The rest of this guide uses the synchronous style because it makes each step visible, but the request body you build is the same in either mode — only the surrounding plumbing changes.
A working curl request
Let's build the call from a terminal. Set your key first:
export HIAPI_API_KEY="your-api-key-here"
Step 1: Prepare the reference image
Start with a small, known-good image so failures are unambiguous:
ls -lh reference.png
file reference.png
file should report PNG image data or JPEG image data. If it says anything else, fix that before continuing.
Step 2: Send the request
The request is a POST to the image generation endpoint, with a JSON body containing the model, your prompt, and the reference image. Depending on which upload route you chose, the image field is either a URL or a base64 string.
curl -sS -X POST "$HIAPI_BASE_URL/images/generations" \
-H "Authorization: Bearer $HIAPI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-image-2.6-flare/image-to-image",
"prompt": "Recreate this scene as a flat vector illustration with a muted palette",
"image": "https://your-storage.example.com/reference.png"
}'
Notes on the flags:
-sSsilences the progress meter but still shows errors — good for scripts.Authorization: Bearer $HIAPI_API_KEYkeeps the secret out of the command itself.$HIAPI_BASE_URLis set from the model page; don't guess the host.- The
imagefield here uses the URL route; for inline images, replace it with the base64 string.
Step 3: Read the response
Add -i to include response headers and -w '\nHTTP %{http_code}\n' to print the status. A successful call returns the image (or a link to it, depending on response format) alongside metadata. On failure you'll get a 4xx or 5xx with a JSON error body — read the message field before changing anything else.
Step 4: Pipe the output to a file
For a clean artifact, redirect stdout to a file and check it with file again. If the response is JSON containing a URL, extract that URL and download it with a second curl. Always verify the downloaded bytes are actually an image before wiring this into anything automated.
The same request in Python
The curl baseline translates directly to Python. This example uses only the standard library plus requests:
import os
import requests
API_KEY = os.environ["HIAPI_API_KEY"]
BASE_URL = os.environ["HIAPI_BASE_URL"]
payload = {
"model": "gpt-image-2.6-flare/image-to-image",
"prompt": "Recreate this scene as a flat vector illustration with a muted palette",
"image": "https://your-storage.example.com/reference.png",
}
response = requests.post(
f"{BASE_URL}/images/generations",
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
},
json=payload,
timeout=120,
)
response.raise_for_status()
data = response.json()
print(data)
Handling the response
The response format varies — it may contain the image directly or a URL. Write a small helper that normalizes both cases, so downstream code doesn't care which:
def extract_image(data):
if "url" in data:
return requests.get(data["url"], timeout=60).content
if "image" in data:
import base64
return base64.b64decode(data["image"])
raise ValueError(f"Unexpected response shape: {list(data)}")
Handling errors
Don't let raise_for_status() be your only error path. Wrap the call and surface the API's error message:
try:
response = requests.post(url, headers=headers, json=payload, timeout=120)
response.raise_for_status()
image_bytes = extract_image(response.json())
except requests.HTTPError as e:
print("HTTP", e.response.status_code, e.response.text)
raise
except requests.Timeout:
print("Request timed out; consider the async job route instead")
raise
Async variant
For the asynchronous style, submit the job with the same payload, read the job id from the response, then poll the job status endpoint with a short sleep between attempts. Cap the number of polls and treat an exhausted budget as a failure — never poll forever in a request handler.
Troubleshooting common errors
Most failures fall into a handful of buckets. Work through this checklist in order; each step isolates one variable.
Authentication errors (401 / 403)
- Is
HIAPI_API_KEYactually set in the shell or process?echo $HIAPI_API_KEYshould print it. - Is the header exactly
Authorization: Bearer <key>— capital A, capital B, one space? - Has the key been revoked or rotated? Regenerate it and retry with a minimal request.
Invalid reference image payload
This is the most common failure and it usually isn't the model's fault:
- URL unreachable: open the image URL in a browser on a different network. If it 404s or redirects to a login page, the API can't reach it either.
- Wrong content type: a URL that returns HTML or JSON will be rejected. Confirm with
curl -I <url>that the response isContent-Type: image/.... - Corrupt or unreadable file: run
file reference.pnglocally. Verify the base64 string decodes back to the same bytes. - Too large: check the documented size limits on the model page; downscale before retrying.
Malformed parameters
- Model id typos:
gpt-image-2.6-flare/image-to-imagemust match exactly, including the slash. - Missing prompt: the text instruction is required, not optional.
- Extra fields: remove any parameter you can't find in the docs. Unknown keys often trigger a 4xx.
- JSON syntax: validate your body with
jq . <<< "$BODY"before sending.
Timeouts
If the request dies before an image returns, the connection was held too long. Shorten the prompt, downscale the reference, raise your client timeout, and if it persists, switch to the asynchronous job style — long generations are exactly what async is for.
Debugging strategy
Change one variable per attempt. Start with a tiny known-good reference image and a one-sentence prompt to prove the plumbing works, then reintroduce your real inputs. Log the full response body on every failure; the message field usually names the offending part of the request directly.
Wiring it into your pipeline
Once the baseline works, a few habits keep gpt-image-2.6-flare/image-to-image reliable in production.
Validate inputs before the call. Check that the reference image is a supported format, within size limits, and reachable if it's a URL. Reject bad inputs at your own boundary instead of paying for a failed round trip.
Validate outputs after the call. Confirm the response contains actual image bytes (check the magic number) rather than an HTML error page that got through. A cheap header check saves a lot of confused debugging downstream.
Retry with backoff, but only on the right errors. Transient 5xx and network timeouts deserve retries with exponential backoff and jitter; 4xx errors from bad parameters will fail identically every time, so fix the request instead of retrying it.
Prefer async for user-facing work. If a person is waiting on a page, submit a job and poll from the client — don't hold a web request open for a long generation.
Keep the model id in config. Model ids change over time. Read them from a single configuration point so swapping models is a one-line change rather than a search-and-replace.
Compose with other HiAPI models. This endpoint pairs naturally with text-to-image for hybrid flows (generate a base, then edit it), and with upscaling or background-removal steps if your pipeline needs them. Because everything goes through the same HiAPI interface and auth, adding a step is another call with the same key.
Start with the curl baseline, port it to Python, and move to async once your traffic demands it. The model page has the current request parameters and limits — check there before assuming a field name or size cap.
Related articles
View all articles →-
Tutorial
gpt-6.2-sol in Practice: 5 High-Value Uses of a Text Model in Business
-
Tutorial
gpt-6.2-astra Practical Guide: Integration and Implementation Key Points for 5 High-Value Text Scenarios
A Developer's Checklist from Scenario Selection to Engineering Implementation
-
Tutorial
Tripo H3.1 Practical Application Scenarios: 5 High-Value Use Cases and Implementation Essentials
From text-to-3D to multiview reconstruction: choosing the right mode and parameters by business scenario