Tutorial
How to Use flux-3 via the HiAPI API: curl, Python, and a Working Request
On this page
What flux-3 Gives You Through HiAPI
flux-3 is an image generation model that handles both text-to-image and image-to-image work. If you are building a product feature, a design tool, or an internal pipeline, the interesting part is rarely the model in isolation — it is how cleanly you can put it behind a stable, predictable interface and keep it there as your needs change.
That is where an aggregated API platform earns its place. Calling flux-3 through HiAPI means you:
- Integrate once. A single base URL, a single authentication scheme, and a consistent request and response shape across the models you use. Swapping or comparing models later is a configuration change, not a rewrite.
- Skip infrastructure work. No model hosting, no GPU capacity planning, no cold starts to manage on your side. You send an HTTP request and handle a response.
- Keep credentials centralized. One API key to provision, rotate, and scope, rather than a separate relationship with every upstream provider.
- Get uniform error semantics. The same status codes and error envelope regardless of which model is behind the call, which makes retry and alerting logic reusable.
For flux-3 specifically, this means you can move from a prototype in a notebook to a production endpoint without changing the shape of your client code. The two generation modes — text-to-image and image-to-image — share a request structure, so supporting both is a matter of which fields you populate, not which SDK you import.
Throughout this post, assume the following conventions:
- Base URL: the HiAPI API endpoint documented in your account console.
- Authentication: a bearer token in the
Authorizationheader. - Content type:
application/jsonfor the request body, with image inputs supplied either as a URL or as base64-encoded data depending on your payload size constraints.
Keep your key in an environment variable — never in source control. The examples below read it from HIAPI_API_KEY, and the model identifier from FLUX_MODEL so you can adjust it without editing code.
With that framing out of the way, the next section breaks down the request body itself.
Request Anatomy: Text-to-Image and Image-to-Image
A flux-3 call has three logical parts: the endpoint path, the authentication headers, and a JSON body. The body is where the two modes diverge, and understanding that split is what lets you reuse one client for both.
The shared skeleton
Every request carries some version of the following:
- model — which model to invoke; here, your flux-3 identifier.
- input — an object holding the generation instructions.
- input.prompt — the natural-language description of what you want. This is required in both modes.
- optional generation settings — things like output dimensions, aspect ratio, or step counts, depending on what the model exposes. Set only what you need; defaults are usually sensible.
- optional async controls — flags or callbacks that change how the job is executed and delivered (covered in the next section).
Text-to-image
In text-to-image mode, prompt is the only substantive field. You describe the image, optionally constrain the output geometry, and submit. There is no source image, so the model has maximal freedom — which also means prompt quality dominates output quality.
A useful habit: write prompts the way you would brief a human illustrator. Subject, composition, lighting, style, and any hard constraints ("no text in the image", "centered subject") in that order. Vague prompts produce visually average results regardless of how many steps you spend on them.
Image-to-image
In image-to-image mode, you add a source image field alongside the prompt, and the prompt now describes a transformation relative to that input rather than a scene from scratch. Depending on the model surface, this can mean supplying an image URL or an encoded image payload, plus any strength or guidance control that governs how far the output may drift from the source.
The practical consequence for your API client is small: same endpoint, same auth, same input object — one additional field. That is the design goal. Your generate() function should accept an optional source image and branch internally, so callers never need to know which mode they triggered.
Response shape
Expect the response to identify the job and, when complete, carry the location of the produced image. Treat that location as opaque: fetch or store it, but do not parse assumptions into it. Some responses are immediate, some are job handles — which is exactly why async handling belongs in your design from day one.
Parameters and Async Mode
Choosing generation settings
Generation settings trade quality against latency and cost. A few principles hold across most image models, flux-3 included:
- Resolution and aspect ratio affect both output usefulness and compute. Generate at the size you will actually ship; downscaling a large render wastes budget, and upscaling a small one wastes the render.
- Step or quality controls improve fidelity up to a point, then plateau. Find your knee empirically with a fixed prompt and stop there.
- Determinism controls (where available) matter for reproducibility. If you need to re-render the same result for QA or user support, record the settings alongside the output.
Do not guess at parameter names or accepted ranges — read them from the model documentation in your console and treat that as the source of truth. If a field is rejected, the error response will tell you which one.
Sync vs. async
Image generation is not an instant operation. Two execution patterns are available:
Synchronous (blocking). You send the request and hold the connection until the image is ready. This is simple and fine for short jobs, scripts, and interactive tools where a user is watching a spinner. It is also fragile: serverless functions, load balancers, and mobile clients all have timeouts, and a long render will hit one of them.
Asynchronous (job-based). You submit the request, receive an identifier immediately, and then poll a status endpoint or receive a callback until the job reports completion. This is the right choice for:
- Serverless and edge runtimes with hard execution ceilings.
- Batch jobs that submit many renders in parallel.
- Any user-facing flow where you want to return control and stream progress.
Design your client around async and wrap it with a synchronous convenience method for the simple cases. Doing it the other way around — bolting async onto a blocking client — rarely ends well.
For polling, use bounded exponential backoff rather than a fixed tight loop, cap total wait time, and treat a job that never reaches a terminal state as an error worth alerting on.
A Working curl Request
Start from the terminal; once the raw HTTP exchange is clear, the code version is trivial.
1. Set your environment
export HIAPI_API_KEY="your-key-here"
export FLUX_MODEL="your-flux-3-model-id"
export HIAPI_BASE="https://your-hiapi-endpoint"
Keep the model identifier in a variable — when you switch models later, one line changes.
2. Send a text-to-image request
curl -sS -X POST "$HIAPI_BASE/v1/images/generations" \
-H "Authorization: Bearer $HIAPI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "'"$FLUX_MODEL"'",
"input": {
"prompt": "A minimal studio photograph of a ceramic mug on a concrete surface, soft side light, shallow depth of field"
}
}'
The -sS flags keep output clean while still surfacing errors. Confirm the exact path against the endpoint documented in your console before running this — paths are versioned, and the docs are authoritative.
3. Read what comes back
Pipe the response through a formatter so it is legible:
... | python -m json.tool
Look for two things: an identifier for the job, and either the image location or a status field telling you the job is still running. If you see a status rather than an image, you are on the async path — note the identifier and move to polling.
4. Try image-to-image
Add the source image to the input object, keeping everything else identical:
curl -sS -X POST "$HIAPI_BASE/v1/images/generations" \
-H "Authorization: Bearer $HIAPI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "'"$FLUX_MODEL"'",
"input": {
"prompt": "Reinterpret as a watercolor painting, keep the composition and shadows intact",
"image": "https://example.com/source.jpg"
}
}'
Because the request differs by one field, your first successful call already proves most of the integration. Everything that remains — retries, storage, UI — is ordinary application work.
The Same Request in Python
The curl call translates directly. Here is a small, reusable client rather than a one-off script.
import os
import time
import requests
BASE = os.environ["HIAPI_BASE"]
MODEL = os.environ["FLUX_MODEL"]
HEADERS = {
"Authorization": f"Bearer {os.environ['HIAPI_API_KEY']}",
"Content-Type": "application/json",
}
def generate(prompt, image=None, timeout=60):
"""Submit a flux-3 generation job. Pass image= for image-to-image."""
payload = {"model": MODEL, "input": {"prompt": prompt}}
if image:
payload["input"]["image"] = image
resp = requests.post(
f"{BASE}/v1/images/generations",
headers=HEADERS,
json=payload,
timeout=timeout,
)
resp.raise_for_status()
return resp.json()
A few deliberate choices:
- One function, two modes. The
imageargument switches behavior, so callers do not branch. - Explicit timeout. The default
requestsbehavior — waiting forever — is how you take down a worker pool. raise_for_status(). Let HTTP-level failures surface as exceptions you can catch in one place.
Adding a poll helper
When the response carries a job identifier instead of a finished image, wait for it:
def wait_for(job_id, timeout=300, initial=1.0, factor=1.6, cap=15.0):
deadline = time.monotonic() + timeout
delay = initial
while time.monotonic() < deadline:
r = requests.get(
f"{BASE}/v1/jobs/{job_id}", headers=HEADERS, timeout=30
)
r.raise_for_status()
data = r.json()
if data.get("status") in ("succeeded", "failed"):
return data
time.sleep(delay)
delay = min(delay * factor, cap)
raise TimeoutError(f"job {job_id} did not finish in {timeout}s")
Adjust the status field names to match the documented response schema. The structure — bounded backoff, a hard deadline, a terminal-state check — is what matters and transfers unchanged if you swap models.
Putting it together
if __name__ == "__main__":
result = generate(
"A minimal studio photograph of a ceramic mug, soft side light"
)
if "id" in result and not result.get("output"):
result = wait_for(result["id"])
print(result)
From here, wrap generate in your own retry and logging layer and the integration is production-shaped.
Cost Control and Common Errors
Keeping spend predictable
Image generation is billed per request, with the exact amount depending on the model and settings — check the live pricing panel in your console rather than hardcoding assumptions. The engineering discipline is what protects the budget:
- Set a per-user and per-job cap in your own code. The platform enforces account-level limits; your application should enforce product-level ones so a single runaway client cannot drain the account.
- Cache aggressively. Hash the normalized prompt plus settings and reuse the stored output. Identical requests are common in editors and previews.
- Generate at shipping resolution. Render the size you will display; skip the expensive-and-downscale pattern.
- Gate regeneration behind explicit user action. Auto-regenerating on every keystroke in a prompt box is the most common accidental cost multiplier.
- Log model, settings, and latency per call. Without this, you cannot tell which feature is expensive.
- Validate inputs before submitting. Reject empty or absurdly long prompts client-side so you never pay for a guaranteed failure.
Debugging the failures you will actually hit
Work down this list in order; it resolves most incidents.
- 401 / 403 — authentication. Is the key loaded into the environment the request actually runs in? A key that works in your shell may be absent in the container. Confirm the
Bearerprefix and that the header name is exact. - 404 — wrong path or model. Versioned paths and model identifiers both change. Compare against the documented endpoint character by character.
- 422 / 400 — payload rejected. The error body names the offending field. Usual suspects: wrong type, missing
prompt, or an unsupported parameter. Remove optional settings and re-send to isolate it. - 429 — rate limited. Back off with jitter and retry; do not retry immediately in a loop. Distinguish this from account-level quota exhaustion, which retrying will not fix.
- Timeouts. If the request runs long, you are blocking where you should be polling. Move to the async flow and set client timeouts deliberately.
- Job stuck pending. Poll with a deadline, and treat expiry as a failure you can alert on rather than an infinite wait.
One habit ties the list together: log the full error body, not just the status code. The body usually tells you precisely which field or limit is at fault, which turns a half-hour investigation into a one-line fix.
Get the curl call working, port it to the client above, and keep polling and error handling in one place — then the rest of your integration is ordinary application code. For the current model surface and pricing, see the flux-3 documentation and pricing panel in your HiAPI console.
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