Tutorial
How to Call gpt-image-2.6-sunburst/text-to-image via the HiAPI API: curl and Python Guide
Authentication, request structure, working curl and Python examples, plus troubleshooting
On this page
What this integration looks like end to end
Every text-to-image call on HiAPI follows the same lifecycle, and it is worth understanding that lifecycle before writing any code. Your application builds a JSON request describing the image you want, sends it to the HiAPI endpoint for gpt-image-2.6-sunburst/text-to-image with your API credential attached, and receives a response containing the generated image data or a URL you can fetch. Once you understand those three stages, the rest of this guide is just filling in the details.
The stages break down like this:
- Authentication — you attach your HiAPI API key to the request, typically as an HTTP header. No per-call token negotiation is required.
- Request construction — you assemble a JSON body containing your prompt, and optionally parameters such as size and number of images.
- Transmission — you POST the body to the endpoint. The call is synchronous, so your client waits for the image to be generated.
- Response handling — the API returns structured JSON. Depending on the endpoint configuration, image data arrives as a URL or as encoded image content that you decode and write to disk.
One detail matters early on: the model identifier gpt-image-2.6-sunburst/text-to-image contains a slash. Treat it as an opaque string. Do not try to split it into a provider name and a model name, and do not URL-encode or normalize it yourself. Copy it exactly as documented, and keep it in one place in your code so you never have to hunt it down later.
The sections below walk through each stage in order. The curl and Python sections deliberately use the same payload so you can compare them line by line, and the troubleshooting section maps the errors you are most likely to encounter back to the specific request field that needs fixing.
Authenticating your HiAPI requests
HiAPI uses an API key–based authentication scheme. You obtain a key from your account dashboard and send it with every request. The standard form is an HTTP header on the request:
Authorization: Bearer YOUR_API_KEY
Some clients prefer to send the key in a dedicated header, but unless your account documentation states otherwise, the Authorization: Bearer form is the one to use, because it matches most HTTP tooling out of the box.
Keep the key out of your source code
The most common security mistake in a first integration is hardcoding the key into a script and committing it. Avoid this from day one:
- Read the key from an environment variable, for example
HIAPI_API_KEY, and fail fast at startup if the variable is missing. - Add your local
.envfile to.gitignorebefore you create it. - In CI or production, inject the key from the platform's secret store rather than from a committed file.
A small helper that reads the key once and raises a clear error if it is absent will save you a confusing debugging session later:
import os
api_key = os.environ.get("HIAPI_API_KEY")
if not api_key:
raise RuntimeError("HIAPI_API_KEY is not set")
Treat the key as a secret at request time too
When investigating a failed call, resist the urge to print the full request object including headers. Log the endpoint, the model identifier, and the status code instead. If you must capture headers for debugging, redact the Authorization value first. Keys that leak into log aggregators are just as exposed as keys committed to a repository.
If you rotate keys, the old key stops working as soon as rotation completes, so make rotation a scheduled operation rather than an emergency one.
Anatomy of a text-to-image request
The request body is a JSON object. For gpt-image-2.6-sunburst/text-to-image the essential fields are small in number, which is why it is worth understanding exactly what each one does rather than copying a payload blindly.
The model field
"model": "gpt-image-2.6-sunburst/text-to-image"
This field selects the model and is required. Keep the string byte-for-byte identical to the documented identifier. A missing slash, an extra space, or a capitalization change will cause the request to be rejected as an unknown model.
The prompt field
"prompt": "A sunlit alpine meadow at golden hour, wildflowers in the foreground, sharp focus"
This is the natural-language description of the image. It is required. Practical guidance for the prompt itself:
- Put the subject first, then setting, then style or lighting cues.
- Prefer concrete nouns over abstractions; "a red ceramic mug on a wooden table" beats "a nice cup scene".
- If you need consistent output across many calls, keep the wording of the non-varying parts stable and interpolate only the changing fragment programmatically.
Optional parameters
Depending on the endpoint, you can also send parameters that control the output shape and quantity, most commonly:
- size — the output dimensions, expressed in the documented format such as
1024x1024. If you omit it, the default applies; if you send an unsupported value, expect a validation error. - n — the number of images to generate for one prompt. Each generated image is billed separately, so keep this at the minimum your workflow needs.
Only send parameters you actually need. An unknown field can cause a strict validation error, and the error will point at a field you did not intend to send at all.
A complete example body
{
"model": "gpt-image-2.6-sunburst/text-to-image",
"prompt": "A sunlit alpine meadow at golden hour, wildflowers in the foreground, sharp focus",
"size": "1024x1024",
"n": 1
}
That is the entire contract. Everything else in this guide is transport, error handling, and lifecycle management around this payload.
A working request with curl
Before building a Python client, confirm the endpoint and credentials work with curl. This isolates authentication problems from code problems.
The call
curl -sS -X POST "https://api.hiapi.ai/v1/images/generations" \
-H "Authorization: Bearer $HIAPI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-image-2.6-sunburst/text-to-image",
"prompt": "A sunlit alpine meadow at golden hour, wildflowers in the foreground, sharp focus",
"size": "1024x1024",
"n": 1
}'
A few notes on the flags:
-sSkeeps the output clean but still surfaces transport errors.-X POSTis the method; the request body travels in-d.- The single quotes around the JSON body prevent the shell from mangling it. On Windows
cmd, JSON quoting rules differ, so usecurl.exewith double quotes and escape the inner quotes, or run the call from a shell script or Python instead.
If you use the exact endpoint path from your account documentation, substitute it here; the shape of the request does not change.
Inspecting the raw response
When something goes wrong, you want the status code and the body. Add -i to include response headers, or -w "\nHTTP %{http_code}\n" to print the status at the end:
curl -sS -o response.json -w "HTTP %{http_code}\n" -X POST "https://api.hiapi.ai/v1/images/generations" \
-H "Authorization: Bearer $HIAPI_API_KEY" \
-H "Content-Type: application/json" \
-d @payload.json
Saving the payload to payload.json and referencing it with @payload.json is worth the extra file: you avoid shell quoting bugs and you can edit the prompt without rewriting the command. Keep that file out of version control if prompts contain sensitive text.
The same call in Python
The Python version keeps the JSON body byte-for-byte identical. Only the transport changes. Using requests adds one dependency but keeps the code readable; it is worth installing for anything beyond a throwaway script.
import os
import requests
api_key = os.environ["HIAPI_API_KEY"]
payload = {
"model": "gpt-image-2.6-sunburst/text-to-image",
"prompt": "A sunlit alpine meadow at golden hour, wildflowers in the foreground, sharp focus",
"size": "1024x1024",
"n": 1,
}
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
response = requests.post(
"https://api.hiapi.ai/v1/images/generations",
headers=headers,
json=payload,
timeout=120,
)
print(response.status_code)
response.raise_for_status()
data = response.json()
print(data)
Why json=payload instead of data=json.dumps(payload): passing a dict to the json keyword argument serializes it and sets the Content-Type header for you. Passing a string to data works too but makes it easy to forget the header, which shows up later as a confusing validation error.
If you prefer the standard library
To avoid a dependency, use urllib.request from the standard library. The payload dictionary is unchanged:
import json, os, urllib.request
payload = {
"model": "gpt-image-2.6-sunburst/text-to-image",
"prompt": "A sunlit alpine meadow at golden hour, wildflowers in the foreground, sharp focus",
}
request = urllib.request.Request(
"https://api.hiapi.ai/v1/images/generations",
method="POST",
headers={
"Authorization": f"Bearer {os.environ['HIAPI_API_KEY']}",
"Content-Type": "application/json",
},
data=json.dumps(payload).encode("utf-8"),
)
with urllib.request.urlopen(request, timeout=120) as response:
data = json.loads(response.read().decode("utf-8"))
Either way, image generation is slower than a typical JSON API call. Set the timeout generously, or you will time out on requests that were about to succeed and pay for them twice on retry.
Handling the response and saving the image
A successful response is JSON. The image output typically arrives either as a URL you fetch separately or as encoded image content inside the payload. Check your endpoint documentation to see which form applies, then handle both shapes defensively, because the exact shape can differ when parameters change.
Reading the response structure
The response is a JSON object containing the generated output and metadata. Inspect it once interactively before writing parsing code:
print(json.dumps(data, indent=2)[:2000])
Look for where the image lives. If you see a URL field, download it. If you see base64 content, decode it. Avoid assuming the URL is permanent — treat it as short-lived and copy the bytes into your own storage immediately.
Saving a URL-based result
image_url = data["data"][0]["url"]
img = requests.get(image_url, timeout=60)
img.raise_for_status()
with open("output.png", "wb") as f:
f.write(img.content)
Saving an encoded result
import base64
encoded = data["data"][0].get("b64_json") or data["data"][0].get("image")
if encoded:
with open("output.png", "wb") as f:
f.write(base64.b64decode(encoded))
Use distinct filenames per call in real workloads — a timestamp, a request ID, or prompt-derived slug. Save the prompt alongside the image in a sidecar JSON file if you intend to regenerate or audit output later.
Handle success in one place
Wrap response parsing in a single function that returns a list of byte strings, one per image. Every caller then writes or uploads the bytes without knowing whether they came from a URL or from encoded content. That abstraction pays off when you switch models later.
Diagnosing common errors
Most first-integration failures fall into a small set of buckets. Match the status code and message to the fix below before changing anything else.
Authentication failures
A request rejected for missing or invalid credentials means the Authorization header is absent, malformed, or carries a revoked key. Check in this order:
- Confirm the header name and value format, including the literal word
Bearerfollowed by a space. - Confirm the environment variable is actually populated in the shell or process that runs the call — a key set in one terminal does not exist in another.
- Confirm the key was not rotated or truncated when copied.
Validation errors on the request body
The API will reject a body that is missing a required field or contains an invalid value. The message normally names the offending field:
- Missing model or prompt — both are required. Send them explicitly on every call rather than relying on defaults.
- Unknown model — recheck the identifier
gpt-image-2.6-sunburst/text-to-image, including the slash and capitalization. Do not interpolate whitespace around it. - Invalid size — use a supported dimension string in the documented format. If you omitted size on purpose, remove it rather than sending
null. - Malformed JSON — usually a shell-quoting problem in curl or a string-encoding issue in Python. Validate with
json.dumps(payload)before sending and inspect what was actually transmitted.
Rate limiting and quotas
If you receive a throttling response, back off and retry with jitter rather than retrying immediately. If the message indicates a quota issue, check your account's plan and usage panel rather than the request body — the payload is likely correct.
Server errors
A 5xx during generation is usually transient. Retry once or twice with exponential backoff. If it persists across prompts and payloads, the problem is not yours to fix; capture the response body and contact support with the request time and the model identifier.
Wrong content type
Sending a body without Content-Type: application/json can produce a confusing validation error because the server cannot parse the payload. In curl, set the header explicitly; in Python, let the json= argument do it.
Making the integration production-ready
The first successful call is the easy part. These adjustments keep the integration cheap to operate and cheap to change.
Make the model identifier configuration
Store the model identifier in one constant or environment-driven config value, never inline in multiple call sites. When you later evaluate a different model, you change one value and rerun your tests. Keep a per-request field in your logs recording which model produced each image, so you can compare quality across swaps without rerunning everything.
Retry deliberately
Retry on network errors, timeouts, and 5xx responses with exponential backoff and jitter. Never retry validation or authentication errors — the request will fail identically and you will only burn rate limit. Cap the number of attempts and log each one with the attempt number and the final status.
Choose timeouts that match the workload
Image generation is slow. A short timeout produces failures on requests that would have succeeded, and if you retry, you may be billed for a generation that already completed. Set a generous per-request timeout and treat timeout-above-threshold as a signal to investigate latency rather than a reason to retry aggressively.
Structure the client in layers
Keep three pieces separate: a payload builder that turns your application inputs into a request dict, a transport function that performs the HTTP call, and a handler that decodes the response into bytes. Testing the builder without a network call is trivial; swapping the transport for a mock is trivial too. This layering also makes model changes a one-file edit rather than a hunt through a codebase.
Log what you will need in a incident
Record the timestamp, the endpoint, the model identifier, the HTTP status, a hash or truncated form of the prompt, and the request duration. Never log the API key or the full request headers. If you store generated images, key your storage paths by request ID so a support ticket can be traced back to an actual call.
With auth handled by an environment variable and the payload isolated in a builder function, the pattern you exercised with gpt-image-2.6-sunburst/text-to-image transfers directly to any other image model on the same HiAPI endpoint.
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