Tutorial
How to Call gpt-image-2.6-flare/text-to-image via the HiAPI API: curl, Python, and a Working Request
On this page
What this tutorial builds
Most text-to-image tutorials stop at a screenshot of a successful response. That is not enough to ship anything. This tutorial takes you from zero to a reusable, working integration with the gpt-image-2.6-flare/text-to-image model through the HiAPI unified API.
By the end you will have three things:
- A single confirmed-working request, first as a
curlcommand and then as an equivalent Python script. - A clear mental model of how HiAPI structures text-to-image calls — the endpoint path, the auth header, the prompt payload, and the response body — so you can adapt the example to your own prompts instead of memorizing it.
- Patterns for scaling that one call into batches and for deciding which failures to retry and which to fix.
We will keep the code minimal and dependency-light. The Python example uses only the standard library so you can run it anywhere Python is installed, and adapt it to requests or an async client later once the request shape is familiar. If you want to jump straight to a runnable call, skip to the curl section and come back for the explanation.
Prerequisites and credentials
Before your first call, confirm you have the following in place:
- A HiAPI account. Sign in to the dashboard so you can generate and manage credentials.
- An API key. Create one in the dashboard's API key section. Treat it like a password: it authorizes every request billed to your account.
- A way to send HTTP requests. Either a shell with
curlinstalled, or Python 3 with the standard library (bothurllibandjsonship with Python).
Handle the key through the environment
Never paste a key directly into source files that get committed. Export it in your shell instead:
export HIAPI_API_KEY="your-api-key-here"
On Windows PowerShell, use $env:HIAPI_API_KEY = "your-api-key-here". In CI, inject it as a secret. In long-running services, load it from a secrets manager at startup.
Know where the base URL lives
HiAPI exposes a single unified API surface, so the base URL is stable across models. Keep it in one configuration value — an environment variable works well — rather than scattering it through your code. That way moving between staging and production, or pointing a test at a mock server, is a one-line change.
The model identifier you will call is gpt-image-2.6-flare/text-to-image. Note that it contains a slash; keep the identifier intact and let it sit in the path position your request builder expects, exactly as shown in the examples below.
With the key exported and the base URL noted, you are ready to look at the request itself.
Anatomy of a text-to-image request
Every HiAPI text-to-image call has the same four moving parts. Once you understand them, switching models or prompts is mechanical.
1. The endpoint path
The request targets the model identifier as part of the path: gpt-image-2.6-flare/text-to-image, appended to your base URL. This is the address that routes your call to the right model behind the unified interface.
2. The auth header
Authentication is a bearer token in the Authorization header:
Authorization: Bearer $HIAPI_API_KEY
This header must be present on every request. A missing or malformed header is the most common cause of a first-call failure.
3. The request body
A text-to-image call is a POST with a JSON body. At its core is the prompt — the natural-language description of the image you want. The body also carries your generation settings. Because HiAPI normalizes the request shape across models, you can reuse a request builder and change the model identifier when you want to compare outputs.
4. The response body
A successful response returns the generated image (or a reference to it) along with metadata about the generation. Your client should check the HTTP status before attempting to parse the image. Treat the response as data, not as something to eyeball — for automation you want the image bytes or URL, and you want any request identifier stored alongside them so you can correlate a file back to the call that produced it.
That is the whole model. Everything after this point is a concrete instantiation of these four parts.
A working request with curl
Here is the complete call. Replace the prompt with your own text and run it:
curl -X POST "$HIAPI_BASE_URL/gpt-image-2.6-flare/text-to-image" \
-H "Authorization: Bearer $HIAPI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "A quiet library at dusk, warm lamp light, deep shadows, cinematic"
}' \
--output response.json
Line by line:
-X POST— generation is a state-changing call, so it uses POST.- The URL — your base URL from the environment, followed by the model identifier and
/text-to-image. Quoting it keeps the shell from misreading any special characters. Authorization: Bearer ...— the credential. The$HIAPI_API_KEYform keeps the literal key out of your shell history.Content-Type: application/json— tells the server to parse the body as JSON. Omitting it is a frequent cause of confusing 4xx errors.-d '{...}'— the JSON payload. Thepromptfield is the one you will vary most; add generation settings here as you refine outputs.--output response.json— writes the body to a file so a binary image payload does not flood your terminal. Open it, or pipe it throughjqif your response is JSON-encoded.
A quick sanity check
If the command returns promptly and response.json is non-empty, you have a working integration. If instead you get a 4xx, inspect the body — HiAPI returns a descriptive error, and the error handling section below covers the usual suspects.
Once this runs, save the command in a shell script next to your project. It is the fastest way to test a credential change or confirm that an outage is on your side or not.
The same request in Python
The curl call translates directly to Python. This script uses only the standard library, reads the key from the environment, and writes the image response to disk:
import json
import os
import urllib.error
import urllib.request
API_KEY = os.environ["HIAPI_API_KEY"]
BASE_URL = os.environ["HIAPI_BASE_URL"]
MODEL = "gpt-image-2.6-flare/text-to-image"
def generate_image(prompt: str, settings: dict | None = None) -> bytes:
payload = {"prompt": prompt}
if settings:
payload.update(settings)
request = urllib.request.Request(
f"{BASE_URL}/{MODEL}",
data=json.dumps(payload).encode("utf-8"),
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
},
method="POST",
)
try:
with urllib.request.urlopen(request, timeout=120) as response:
return response.read()
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", errors="replace")
raise RuntimeError(f"HTTP {exc.code}: {detail}") from exc
if __name__ == "__main__":
body = generate_image("A quiet library at dusk, warm lamp light, deep shadows, cinematic")
with open("output.bin", "wb") as f:
f.write(body)
print(f"wrote {len(body)} bytes")
A few deliberate choices:
- The timeout is generous. Image generation is slower than a text completion; a 120-second ceiling avoids hanging forever while still tolerating a slow-but-successful call.
- The function returns bytes, not a path. That keeps it reusable — you can upload the bytes to object storage or return them from a web handler.
- Errors are wrapped with the response body attached. When something goes wrong, the message tells you what the server said, not just the status code.
- The payload builder accepts optional settings. As you add generation parameters, extend the
settingsdictionary rather than hardcoding them into the function.
Run it with python generate.py after exporting both environment variables. If you prefer requests, swap the request construction for requests.post(url, json=payload, headers=headers); the shape is identical.
Batching and concurrency patterns
One prompt is a demo; many prompts is a job. The transition introduces two problems: throughput and debuggability.
Iterate prompts from a file
Put your prompts in a newline-delimited file or a JSON array. Give every prompt an ID (a slug, an index, or a hash) and name output files after that ID. When a batch of hundreds of images completes, you can map each file back to its prompt without guessing.
prompts = [
("lib-001", "A quiet library at dusk, warm lamp light, cinematic"),
("lib-002", "A lighthouse in fog, long exposure, muted palette"),
]
for prompt_id, text in prompts:
body = generate_image(text)
with open(f"out/{prompt_id}.bin", "wb") as f:
f.write(body)
Control concurrency explicitly
Generation calls are I/O-bound, so concurrency helps throughput — but unbounded concurrency will trip rate limits and bury you in errors. Start sequential, measure how long a single call takes, then raise concurrency with a bounded worker pool. A simple thread pool with a small fixed number of workers (four to eight to start) is usually sufficient.
For larger jobs, use an async client or a queue with a worker fleet. The key discipline is the same: bounded parallelism, one output file per prompt ID, and a log line per request recording the ID, status, and elapsed time.
Keep a manifest
Write a small JSON manifest as the batch runs, recording each prompt ID and its outcome. If the process dies halfway, the manifest tells you what to resume instead of re-billing the whole batch. This single practice saves more time than any clever optimization.
Handling errors and retries
Failures fall into two categories: those you fix and those you retry. Conflating them wastes time and, on retry-storms, money.
Fix these
- 401 / 403 — authentication. The key is missing, expired, or lacks access. Check that
HIAPI_API_KEYis actually exported in the shell running the command — a common trap is exporting it in one terminal and running the script in another. - 400 — malformed payload. Invalid JSON, a missing
prompt, or an unexpected field type. The error body usually names the offending field. Quote your JSON carefully in curl calls. - 404 — wrong path. Verify the model identifier is spelled exactly as documented and that your base URL has no duplicated or missing path segments.
Retry these, with backoff
- 429 — rate limited. Slow down. Respect any retry-after hint in the response, and use exponential backoff with jitter. Long-term, cap your concurrency.
- 5xx — server errors. Usually transient. Retry a bounded number of times (three is a reasonable default) with increasing delays, then fail loudly.
A minimal retry wrapper
import random, time
def with_retries(fn, attempts=3):
for i in range(attempts):
try:
return fn()
except RuntimeError as exc:
if i == attempts - 1:
raise
time.sleep((2 ** i) + random.uniform(0, 0.5))
Use it to wrap generate_image. Crucially, make the operation idempotent from your side: because output files are keyed by prompt ID, a retry overwrites rather than duplicates. Log every failure with the prompt ID and the server's message — when you do escalate, that log is what support needs to reproduce the problem.
Next steps
You now have a request that works, a Python function worth keeping, and patterns for running it at scale. To harden it for production, add structured logging with request IDs, persist the manifest to durable storage so batch jobs resume after crashes, and validate prompts before sending so malformed input fails fast and cheaply.
The most useful next move is to reuse this exact client against other models on the HiAPI API. Because the endpoint path, auth header, and payload shape are shared, adapting the script to a new model usually means changing the model identifier and, occasionally, a setting or two — a small code change for a meaningfully different set of outputs.
Start with one prompt, confirm the file lands, then let the batch runner carry the rest.
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