Tutorial
How to Call flux-2/text-to-image via the HiAPI API: curl and Python Tutorial
A working request walkthrough: model identifier, prompt and aspect ratio parameters, response fields, and error handling
On this page
What flux-2/text-to-image Exposes Through the API
Before you write a line of code, it helps to know exactly what you are wiring up. On HiAPI, flux-2/text-to-image is not a separate SDK you install or a new service you authenticate against. It is a model identifier you pass to the shared image generation endpoint, alongside a prompt that describes what you want to see.
That mental model matters because it sets the boundary of the integration. Your code needs three things:
- An authentication credential for the HiAPI API.
- The endpoint that accepts image generation requests.
- A JSON payload containing
model(set toflux-2/text-to-image) and aprompt.
Everything else — aspect ratio, output preferences, and any other knobs the model exposes — lives inside that payload as additional fields. This is why switching from another text-to-image model to flux-2/text-to-image is usually a one-line configuration change rather than a rewrite: the request envelope stays the same, and only the model value moves.
The endpoint takes your request, runs it through the model, and returns a structured response containing the generated image (typically as a URL or encoded payload) plus metadata about the job. You do not need to poll a separate job queue for a basic call — the request/response cycle is synchronous from your client's perspective, though the underlying generation still takes time, so your HTTP client's timeout should be generous.
Keep this picture in mind: one endpoint, one payload, one model string. The rest of this tutorial fills in the payload and hardens the call.
Build a Working Request with curl
The fastest way to confirm your credentials and payload shape are correct is a single curl call. Get one successful response in the terminal before you touch Python — it isolates authentication and payload problems from language-level bugs.
Set your key as an environment variable first so it never lands in your shell history as plain text:
export HIAPI_API_KEY="your_api_key_here"
Then send the request:
curl -sS -X POST "$HIAPI_IMAGE_ENDPOINT" \
-H "Authorization: Bearer $HIAPI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "flux-2/text-to-image",
"prompt": "a weathered lighthouse on a granite cliff at dawn, soft fog, wide shot",
"aspect_ratio": "16:9"
}'
A few things to check when you run this:
- Endpoint and key come from your HiAPI account dashboard. Copying the endpoint from the dashboard rather than retyping it avoids the most common silent failure — a request that goes somewhere unexpected.
-sSkeeps the output clean but still surfaces curl-level errors such as DNS or TLS failures.- The
Authorizationheader uses the standard bearer scheme. No trailing spaces, no quotes around the variable expansion. Content-Type: application/jsonis required; without it the body may be rejected before the model ever sees it.
If the call succeeds, you will see a JSON body in your terminal. Pipe it through a formatter for readability:
curl -sS -X POST "$HIAPI_IMAGE_ENDPOINT" \
-H "Authorization: Bearer $HIAPI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"flux-2/text-to-image","prompt":"a red fox in fresh snow, eye level","aspect_ratio":"1:1"}' \
| python3 -m json.tool
Once this works, you have a known-good baseline. Any failure in Python can then be compared against a call you know is valid.
Prompt and Aspect Ratio Parameters
Two request fields change the output more than anything else: prompt and aspect_ratio. Tune them one at a time, or you will not know which one caused the change you are looking at.
Prompt
The prompt is a natural-language description of the image. Write it as a compact scene description rather than a list of keywords — subject, setting, lighting, and framing, in that rough order. Compare:
- Vague:
a lighthouse - Specific:
a weathered lighthouse on a granite cliff at dawn, soft fog, wide shot
Keep the wording explicit and stable while you experiment. If you rewrite the prompt and the aspect ratio in the same iteration, you have two variables and one observation. Freeze the prompt, adjust one word at a time, and note what actually changed.
Practical habits:
- Put the most important subject early in the string.
- Describe lighting and mood with concrete words rather than abstract ones.
- Keep a small set of reference prompts in your codebase and rerun them when you change anything else, so you can tell model-behavior changes from prompt changes.
Aspect ratio
aspect_ratio controls the shape of the output — wide for landscapes and banners, square for avatars and thumbnails, tall for posters and mobile layouts. The model accepts a ratio string such as 16:9, 1:1, or a portrait equivalent; use ratios the model documents rather than inventing arbitrary ones.
Because aspect ratio is a single, discrete field, it is the easiest parameter to sweep. Write a loop that holds the prompt constant and requests the same image at three ratios, then compare the compositions side by side. You will quickly learn which ratios crop your subject and which give it room.
One caution: an aspect ratio changes the effective composition, not just the canvas. A prompt written for a wide shot may look thin in a square frame. After you settle on a ratio, revisit the prompt once to compensate.
Porting the Call to Python
The curl call translates directly into Python. The goal is a small function that takes a prompt and an aspect ratio, reads the key from the environment, and returns parsed JSON — production-shaped, not a throwaway script.
import os
import requests
IMAGE_ENDPOINT = os.environ["HIAPI_IMAGE_ENDPOINT"]
MODEL = "flux-2/text-to-image"
def generate_image(prompt: str, aspect_ratio: str = "1:1", timeout: int = 120) -> dict:
api_key = os.environ["HIAPI_API_KEY"] # fail fast if unset
payload = {
"model": MODEL,
"prompt": prompt,
"aspect_ratio": aspect_ratio,
}
response = requests.post(
IMAGE_ENDPOINT,
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json=payload,
timeout=timeout,
)
response.raise_for_status()
return response.json()
Notes on why it is written this way:
- Environment variables, not literals.
os.environ[...]raisesKeyErrorimmediately if a variable is missing, which is far better than sending an empty bearer token and decoding a confusing auth error later. json=payloadletsrequestsserialize the body and setContent-Typefor you. Do not hand-build a JSON string.- Explicit timeout. Image generation is not instant; a default client timeout will bite you under load. Set it deliberately.
raise_for_status()converts non-2xx responses into exceptions you can catch and classify, instead of silently returning an error body that looks like data.
Call it:
result = generate_image(
"a weathered lighthouse on a granite cliff at dawn, soft fog, wide shot",
aspect_ratio="16:9",
)
print(result)
If you prefer httpx, the shape is identical — swap the import and keep the same headers, json= payload, and timeout argument. The payload is what matters, and it is unchanged from the curl version.
Reading the Response
A successful call returns a JSON object. Rather than guessing at field names, inspect one real response first and then write your parser against what you actually see. Run your function and print the top-level keys:
result = generate_image("a red fox in fresh snow, eye level", "1:1")
print(result.keys())
The fields you will typically work with fall into two groups:
- The image itself. The response carries the generated image — commonly as a URL you can download or serve, sometimes as encoded image data. Read the exact field name from your own response, store the value, and handle it according to which form it takes. If it is a URL, treat it as short-lived: download or copy it to your own storage promptly rather than storing the link in a database and assuming it will still resolve next month.
- Metadata. Expect accompanying fields describing the generation — the model used, the aspect ratio or dimensions requested, and identifiers for the request. Log these alongside the image. When a user reports that an image “looks wrong,” the metadata tells you which prompt and ratio produced it without you re-deriving it from application state.
A safe extraction pattern:
image_ref = result.get("image") or result.get("data")
if not image_ref:
raise ValueError(f"no image in response; keys={list(result.keys())}")
This is defensive on purpose. Field names are stable within a model, but writing the accessor so it fails loudly with the actual key list saves you from a silent None propagating into your UI. Once you have confirmed the field names from a real response, tighten the code to read them directly.
Finally, do not discard the raw response. Store it (or log it for a sample of requests) until your integration is stable — it is the ground truth when something downstream looks off.
Common Errors and How to Fix Them
Most first-run failures fall into a handful of classes. Handle them by HTTP status class, not by string-matching message text, which changes without notice.
Authentication failures (401 / 403)
The key is missing, malformed, or lacks access. Check, in order: that HIAPI_API_KEY is actually set in the environment your process sees; that the header is exactly Authorization: Bearer <key> with no stray whitespace or wrapping quotes; that you are not accidentally sending a key from a different environment. If it worked in curl but not Python, print the header you are sending and compare it character by character.
Malformed payloads (400)
The body was rejected before generation. The usual culprits: invalid JSON (a hand-built string with a trailing comma), a missing prompt, or the wrong Content-Type. Fix by using json=payload in Python and -d with valid JSON in curl. Echo the payload you are about to send in your logs and read it as a human would.
Unsupported or invalid parameters (400 / 422)
A field name or value the model does not accept — a misspelled aspect_ratio, a ratio the model does not document, or an extra field copied from another model's example. Reduce the payload to the minimum (model, prompt) and add fields back one at a time to find the offender.
Rate limits (429)
You are sending requests faster than your account's limits allow. This is transient. Do not retry in a tight loop — back off with increasing delay and a cap on attempts. If you are batching, add a small delay between calls rather than firing them all at once.
Server-side errors (5xx) and timeouts
These are transient and outside your control. Retry with backoff, and make sure your timeout is long enough that slow generations are not misclassified as failures. A read timeout that fires while the model is still working produces a retry that wastes a request.
Putting the classification in one place keeps it maintainable:
def classify(status: int) -> str:
if status in (401, 403):
return "auth" # fix config, do not retry
if status in (400, 422):
return "payload" # fix request, do not retry
if status == 429:
return "rate_limit" # retry with backoff
if status >= 500:
return "server" # retry with backoff
return "other"
Wrapping the Call for Production
The function above works, but a real integration needs three things it does not yet have: retries that distinguish transient from permanent failures, a timeout that reflects reality, and logs that let you reconstruct what happened. A small wrapper covers all three.
import logging
import time
log = logging.getLogger(__name__)
def generate_with_retry(prompt, aspect_ratio="1:1", attempts=3):
delay = 1.0
for attempt in range(1, attempts + 1):
try:
return generate_image(prompt, aspect_ratio)
except requests.HTTPError as exc:
status = exc.response.status_code
kind = classify(status)
log.warning("flux-2 call failed", extra={
"attempt": attempt, "status": status,
"kind": kind, "aspect_ratio": aspect_ratio,
})
if kind in ("auth", "payload"):
raise # retrying will not help
if attempt == attempts:
raise
time.sleep(delay)
delay *= 2
Why each piece earns its place:
- Retry only what is retryable. Auth and payload errors are deterministic — retrying them wastes time and hides the real bug. Rate limits, server errors, and timeouts get exponential backoff.
- Log structured fields, not prose. Attempt number, status, error class, and the parameters used let you group failures later. Never log the API key.
- Cap the attempts. An unbounded retry loop turns an outage into a hung worker.
- Keep the timeout explicit and generous. Pass it through from configuration so you can raise it during known-slow periods without editing code.
Two more habits that pay off: persist a hash of (model, prompt, aspect_ratio) with each generated image so you can reproduce any output, and keep a handful of reference prompts in your test suite that you run after any change to the wrapper. Together they turn a tutorial snippet into something you can operate.
With the request shape settled and the error handling in place, swapping models later is a one-line change to the model field — which is the whole point of calling flux-2/text-to-image through a unified interface.
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