Tutorial
How to Call flux-1-fill-pro via the HiAPI API: curl, Python, and Async Polling
On this page
What flux-1-fill-pro Does and When to Reach for It
flux-1-fill-pro is a fill-style image editing model. You hand it a source image plus a mask that marks the region you want regenerated, and it produces a new image where that region has been replaced. Everything outside the mask is intended to stay put, which is what separates it from a plain text-to-image model or a full-image restyle.
Reach for it when the edit is local and the surrounding context matters:
- Object removal — mask out an unwanted element and let the model reconstruct what should plausibly sit behind it.
- Object replacement — mask a region and describe the new content in the prompt, keeping the rest of the scene untouched.
- Local touch-ups — fix a texture, a reflection, or a small artifact without regenerating the entire frame.
- Pipeline inserts — programmatically patch product shots, thumbnails, or generated assets where only one region needs a second pass.
It is not the right tool when you want a whole new composition from a prompt, or when your masked area is so large that the model is effectively generating the image from scratch — at that point a standard generation endpoint will behave more predictably.
The rest of this guide is about wiring flux-1-fill-pro into code through the HiAPI API: the request shape, a curl call, a Python equivalent, and the async job handling that most first integrations get wrong.
Prerequisites and Authentication Setup
Before the first request, confirm three things.
An API key
Create a key in your HiAPI account and keep it out of source control. The examples below read it from an environment variable so the snippets stay safe to copy:
export HIAPI_API_KEY="your_key_here"
Load it the same way in Python via os.environ. If you are running in CI, inject it as a secret rather than committing a .env file.
The model identifier
Every request targets a model by name. For this walkthrough that identifier is flux-1-fill-pro. Keep it as a constant in your code rather than scattering string literals — it makes swapping models later a one-line change.
The base URL
All calls go to the HiAPI API base URL documented in the platform reference. Put it in config alongside the key so staging and production environments can differ without code edits.
One structural note before you start: fill requests carry image data. Send them as JSON with base64-encoded images rather than trying to force them through a form upload, and keep your client's request timeout generous — encoding a large image adds latency before the request even leaves your process. Check the platform documentation for the current limits on payload size; if your source image is larger than the documented ceiling, downscale it before encoding rather than letting the request fail at the edge.
How the Inpainting Request Is Shaped
Every flux-1-fill-pro call has the same logical anatomy, regardless of the language you write it in.
Source image
The image you want edited, encoded as a string. It defines the canvas: its dimensions determine the coordinate space your mask lives in, and its content supplies the context the model uses to make the fill believable.
Mask
The mask marks what gets regenerated. This is the single most common source of confusion, so be explicit about the convention your payload uses: the masked region is the area the model is allowed to change. Build the mask as a separate image where the regions to fill are visually distinct from the regions to keep. Inverting the mask is the classic bug — you get a result where the model edited everything except the part you wanted.
The mask must match the source image dimensions exactly. A mask drawn at a different resolution will either be rejected or silently misaligned, and both outcomes waste a round trip.
Prompt
A text description of what should appear in the mask. Keep it concrete and local: describe the content and its lighting or texture relationship to the surroundings, not the whole scene. "A wooden bench continuing the storefront's trim, soft afternoon light from the left" gives the model more to work with than "nicer background."
Optional controls
Depending on the documented parameter set, you may also pass things like a seed for reproducibility or a strength-style control for how far the fill may deviate from the original pixels. Treat any parameter not in the current reference as unsupported rather than guessing at its name.
All four of these — model, prompt, source image, mask — travel in one JSON body. That body is what the next two sections send.
A Working curl Request
Start with curl so you can see the raw envelope before any client library obscures it.
curl -sS -X POST "$HIAPI_BASE_URL/v1/images/edits" \
-H "Authorization: Bearer $HIAPI_API_KEY" \
-H "Content-Type: application/json" \
-d @request.json
Where request.json looks like:
{
"model": "flux-1-fill-pro",
"prompt": "A wooden bench continuing the storefront trim, soft afternoon light from the left",
"image": "<base64-encoded source image>",
"mask": "<base64-encoded mask image>"
}
Two practical tips for building that file. First, generate the base64 payload with a command rather than pasting it:
base64 -w 0 source.png > source.b64
base64 -w 0 mask.png > mask.b64
Then assemble request.json with a small jq or Python step that splices the strings in. Hand-editing a multi-megabyte base64 blob into JSON is how you end up with a truncated payload and a confusing 400.
Reading the response
The response envelope tells you what to do next. A completed job returns the edited image — typically as a URL or a base64 field, matching whatever the current reference specifies. A queued job returns an identifier and a status you then poll (covered below). Do not assume the first response always contains pixels; write the parser to handle both shapes from day one, or you will rewrite it the first time a job queues under load.
Check the HTTP status before parsing the body. A 4xx means the request itself is wrong and retrying will not help; fix the payload instead.
The Same Call in Python
The Python version is the same request with better ergonomics. No SDK is required — requests against the HiAPI endpoint is enough.
import base64
import json
import os
import time
import requests
BASE_URL = os.environ["HIAPI_BASE_URL"]
API_KEY = os.environ["HIAPI_API_KEY"]
MODEL = "flux-1-fill-pro"
def b64(path: str) -> str:
with open(path, "rb") as f:
return base64.b64encode(f.read()).decode("ascii")
def create_fill(source_path: str, mask_path: str, prompt: str) -> dict:
payload = {
"model": MODEL,
"prompt": prompt,
"image": b64(source_path),
"mask": b64(mask_path),
}
resp = requests.post(
f"{BASE_URL}/v1/images/edits",
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
},
data=json.dumps(payload),
timeout=120,
)
if resp.status_code >= 400:
raise RuntimeError(f"HiAPI error {resp.status_code}: {resp.text}")
return resp.json()
The timeout is deliberate. Encoding and uploading a large image takes longer than a typical JSON call, and an unbounded request is how a script hangs silently in a batch job. Raising on 4xx with the response body attached turns a mysterious failure into a readable one.
Keep the model identifier and endpoint in module-level config so a version bump is a single edit. If you are processing many images, reuse a requests.Session so connections are pooled rather than re-established per call.
The parsed dict is either a finished result or a job handle — the next section handles the latter.
Handling Asynchronous Jobs and Polling
Fill requests can be slow, so the API may return a job handle instead of a finished image. The correct pattern is a bounded polling loop, not a fixed sleep and hope.
The loop
def wait_for_result(job: dict, *, interval=2.0, timeout=180.0) -> dict:
deadline = time.monotonic() + timeout
current = job
while time.monotonic() < deadline:
status = current.get("status")
if status in {"succeeded", "completed"}:
return current
if status in {"failed", "canceled", "cancelled"}:
raise RuntimeError(f"Job ended as {status}: {current}")
time.sleep(interval)
interval = min(interval * 1.5, 15.0) # gentle backoff
current = fetch_job(current["id"])
raise TimeoutError(f"Job {job.get('id')} exceeded {timeout}s")
fetch_job is the same request pattern as above, hitting the documented job-status endpoint with the job id and your auth headers.
Why backoff and not a fixed interval
A tight loop against a queue hammers the API for no benefit. Starting at a short interval and multiplying up to a ceiling keeps early completion fast without thousands of wasted polls on a slow job. Cap the interval so you still notice completion within seconds.
Why a timeout is separate from a failure
A timeout means you stopped waiting, not that the job failed. Keep the job id when you raise, so a caller can resume polling later instead of re-submitting and paying for the same work twice. Treat timeout, job failure, and HTTP error as three distinct exceptions in your pipeline — collapsing them into one generic error makes production incidents much harder to triage.
Debugging Common Failures
Most bad responses fall into a handful of buckets. Check these in order.
401 / 403 — authentication
First check: is the header exactly Authorization: Bearer <key>, with no quotes and no stray whitespace from a shell variable that was never exported? An empty $HIAPI_API_KEY produces a Bearer token that is just the word Bearer, which fails the same way as a wrong key.
400 — malformed payload
First check: is the body valid JSON after the base64 strings are spliced in? Dump request.json and run it through python -m json.tool. Leading data:image/png;base64, prefixes on the image fields are a frequent cause — strip them unless the reference explicitly asks for them.
Mask/image mismatch
First check: do the mask and source image share identical pixel dimensions? Then verify polarity — confirm the white region is the region you intend the model to regenerate. A result that looks like the inverse of what you asked for is almost always an inverted mask, not a prompt problem.
Prompt bleed
If unmasked areas changed or the fill looks global, your mask may be too large or your prompt too scene-wide. Narrow both: tighten the mask to the actual edit and describe only the masked content.
Job timeouts
First check: the payload size. Oversized source images are the most common cause of jobs that never finish. Downscale, retry once, and if it still times out, compare a small test image against the reference limits before assuming a service issue.
Empty or missing result field
First check: whether you handled the queued response shape at all. A parser that only reads the completed shape will see nothing on the first call. Log the full envelope during development so the shape is visible before you write defensive code around it.
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