Tutorial
How to Use minimax-h3 via the HiAPI API: curl, Python, and a Working Request
On this page
What minimax-h3 Integration Looks Like End to End
Video generation is not an instant operation. minimax-h3 has to accept a prompt or a source image, schedule work on a GPU pool, encode frames, and assemble an output file. That whole process can take anywhere from several seconds to a few minutes depending on duration and resolution. If the HiAPI endpoint blocked until the file was ready, your HTTP client would sit on an open connection the entire time — fragile under retries, hostile to serverless time limits, and impossible to run in a request/response web handler.
So the integration follows a submit-then-poll shape, which is the standard pattern for async media APIs:
- Submit. You
POSTa JSON payload describing the job (prompt, optional image, duration, aspect ratio, and any model-specific parameters). The API validates it and immediately returns a task identifier plus an initial status. - Poll. You call a task-status endpoint with that identifier on a short interval. The status moves through states such as queued, processing, then succeeded or failed.
- Fetch. Once the status is terminal, the response carries the result — typically a downloadable URL for the generated video.
Three consequences follow from this model, and they shape everything later in this guide:
- The task ID is your only handle. Persist it. If you lose it, you cannot retrieve the job; you can only submit a new one and pay for the work twice.
- Your code has two failure surfaces, not one. Submit can fail (auth, malformed payload), and polling can fail (timeout, transient network error, terminal job failure). Handle them separately.
- Polling cadence is a design decision. Too aggressive and you waste requests; too slow and your users wait on a status that has been ready for a while.
Throughout this article, all calls go to the HiAPI unified API. You will need an API key from your HiAPI account, and you will reference the model as minimax-h3 in the payload. Everything else — authentication headers, base URL, polling endpoint — is shared across the platform, so the patterns you learn here transfer to other models without restructuring your client.
With that mental model in place, the fastest way to confirm your setup is a single curl call.
Your First Working curl Request
Before writing any application code, confirm that your key works and that you can reach the API. A throwaway curl command is the cheapest way to isolate an authentication problem from a payload problem.
Start by exporting your key so it never lands in your shell history as a literal:
export HIAPI_API_KEY="your-api-key-here"
Then submit a minimal text-to-video job:
curl -sS -X POST "https://api.hiapi.ai/v1/video/generations" \
-H "Authorization: Bearer $HIAPI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "minimax-h3",
"prompt": "A slow aerial shot over a fog-covered pine forest at sunrise",
"duration": 5,
"aspect_ratio": "16:9"
}'
A successful response returns a JSON object containing a task identifier and a status. It will look structurally like this:
{
"id": "task_abc123xyz",
"status": "queued",
"model": "minimax-h3",
"created_at": "2024-01-01T00:00:00Z"
}
Note that there is no video URL yet. That is expected — the job has only been accepted. Field names in your actual response may differ slightly from the illustration above; read the response body rather than assuming, and log the whole thing during development.
What each part of the request does
- The URL points at the video generation resource on the HiAPI platform. All model calls share this base, which is why switching models is a payload change rather than a code rewrite.
Authorization: Bearercarries your API key. This is the single most common source of failures, so verify it first when something breaks.Content-Type: application/jsonis mandatory. Without it, servers may reject or misparse the body.modelselects minimax-h3 explicitly. Never omit it — the platform routes on this value.promptis the creative instruction. Be specific about subject, camera movement, and lighting; vague prompts produce vague video.durationandaspect_ratioconstrain the output. Keep them within the model's supported ranges; an out-of-range value is a payload validation error, not a server fault.
Confirm the job exists
Immediately after submitting, fetch the task once to prove the ID is valid:
curl -sS "https://api.hiapi.ai/v1/tasks/task_abc123xyz" \
-H "Authorization: Bearer $HIAPI_API_KEY"
Replacing task_abc123xyz with the ID from the submit response. If this returns a status, your key, endpoint, and task handle are all correct — and you are ready to move into Python.
Two habits worth forming now: run curl with -sS so errors surface instead of being silently swallowed, and always quote the URL. A stray shell expansion inside a JSON payload is a debugging trap that costs more time than the quotes are worth.
Building the Same Request in Python
The curl call proves the contract; Python is where you build something reusable. Rather than jumping straight to a polling loop, start with a small client class that handles submission and result retrieval as two clear methods. That separation keeps the async logic out of your transport layer.
Use requests (or httpx if you prefer async); the shape is the same either way.
import os
import time
import requests
BASE_URL = "https://api.hiapi.ai/v1"
class MiniMaxH3Client:
def __init__(self, api_key: str | None = None):
self.api_key = api_key or os.environ["HIAPI_API_KEY"]
self.session = requests.Session()
self.session.headers.update({
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
})
def submit(self, prompt: str, duration: int = 5,
aspect_ratio: str = "16:9", **extra) -> str:
payload = {
"model": "minimax-h3",
"prompt": prompt,
"duration": duration,
"aspect_ratio": aspect_ratio,
**extra,
}
resp = self.session.post(
f"{BASE_URL}/video/generations",
json=payload,
timeout=30,
)
resp.raise_for_status()
data = resp.json()
return data["id"]
A few deliberate choices here are worth calling out.
A session, not bare requests. Reusing a requests.Session keeps the connection alive across submit and poll calls, which matters when you are polling the same host repeatedly. It also centralizes headers, so the auth header is defined once.
A hard timeout on submit. Thirty seconds is generous for a request that should return almost immediately. Without a timeout, a network hiccup hangs your process indefinitely. Never leave timeout unset on any call to a remote API.
raise_for_status() before parsing. A non-2xx response usually has a different body shape than a success. Checking the status code first means your error handling reads a well-formed error message instead of crashing on a missing id key.
**extra passthrough. Model-specific options evolve. Passing through additional keyword arguments lets you experiment with new parameters without editing the method signature each time.
Using it
client = MiniMaxH3Client()
task_id = client.submit(
"A slow aerial shot over a fog-covered pine forest at sunrise"
)
print(f"submitted: {task_id}")
That is the whole submit path. The client returns a string — the task handle — and nothing else. Resist the urge to make submit also wait for the result. Mixing submission and waiting into one method makes retries ambiguous: on failure, you cannot tell whether a job was created, so you risk duplicate generation. Keep them separate and the caller decides policy.
Polling for Results Without Hammering the API
Polling is the part most likely to be written carelessly. A naive while True loop with no delay will fire hundreds of requests at a job that takes two minutes, and it will keep doing so after the job has already failed.
A correct polling loop has four responsibilities: check status, wait, stop on a terminal state, and give up eventually.
TERMINAL = {"succeeded", "failed", "cancelled"}
def wait_for(self, task_id: str, interval: float = 3.0,
max_wait: float = 600.0) -> dict:
deadline = time.monotonic() + max_wait
while time.monotonic() < deadline:
resp = self.session.get(f"{BASE_URL}/tasks/{task_id}", timeout=30)
resp.raise_for_status()
data = resp.json()
status = data.get("status", "unknown")
if status in TERMINAL:
return data
time.sleep(interval)
raise TimeoutError(f"task {task_id} did not finish in {max_wait}s")
Choosing the interval
For video generation, a fixed few seconds is a sensible default. The job is not going to complete in the first couple of seconds — model load and frame encoding both take real time — so polling every 200 milliseconds gains you nothing but load. If you want to be polite and efficient at once, use exponential backoff with a cap: start at one or two seconds, multiply by roughly 1.5 each round until you hit five or ten seconds, then stay there. Early polls catch fast failures quickly; later polls stay cheap during long renders.
Stopping correctly
Treat any unrecognized status as non-terminal and keep waiting — but only up to a limit. Two stopping conditions matter:
- Terminal status. Return immediately on success. On failure, surface the error message from the response rather than returning an empty result; the reason matters for your logs.
- Wall-clock budget. Use a monotonic clock, not wall time, so a system clock adjustment cannot make your loop exit early or run forever. Pick a ceiling comfortably above the longest realistic job for your chosen duration and resolution, and treat hitting it as an operational error to alert on.
Returning the result
When the status is terminal success, the response carries a URL to the generated video. Download it promptly — result URLs are usually served with an expiry — and store it in your own object storage if you need durable access. Do not pass the vendor URL straight to end users and assume it will live forever.
One more practical note: log every poll with the task ID, status, and elapsed time at debug level, and log the terminal outcome at info level. When a job takes longer than expected, that timeline is the difference between a five-minute diagnosis and an hour of guessing.
Text-to-Video vs Image-to-Video Request Shapes
The two generation modes share most of their payload. What differs is the creative input, and that difference has downstream effects on what kinds of failures you should expect.
Text-to-video
This is the shape shown in earlier sections: a prompt plus output constraints. The model invents everything — composition, motion, lighting, and subject details. Your payload carries:
model:minimax-h3prompt: the scene descriptionduration,aspect_ratio, and any other output controls
Because nothing is anchored, prompt quality dominates the result. Describe camera behavior ("slow dolly in", "static tripod shot") and lighting ("golden hour backlight") rather than piling on adjectives about quality. Vague superlatives do very little; concrete physical description does a lot.
Image-to-video
The image-to-video variant adds a source image reference to the same request. Typically you supply an image URL or an uploaded asset identifier in an image field alongside the prompt, and the model animates from that starting frame.
client.submit(
"Gentle wind moves the hair, subtle camera push forward",
duration=5,
image_url="https://example.com/portraits/source.jpg",
)
The prompt now plays a different role: it directs motion and camera, not content, because the visual content is already fixed by the image. Writing a full scene description is often counterproductive — the model cannot add a location that is not in the frame. Keep motion prompts short and specific.
Check the request reference for the exact field name and accepted image formats in image mode, and for the valid ranges of duration and aspect ratio in both modes. Those constraints are the same ones that drive payload validation errors, so reading them once saves a round of debugging later.
A practical rule of thumb
Choose text-to-video when you need novel scenes — b-roll, mood clips, concept visualization. Choose image-to-video when consistency matters: animating a product photo, bringing a character portrait to life, or turning a storyboard frame into a moving shot. The mode is a payload difference, not an integration difference, so one client class can serve both simply by accepting optional image arguments.
Debugging Common Errors
When a minimax-h3 call goes wrong, the cause is almost always in one of four places. Work through them in this order.
1. Authentication
Symptoms: 401 or 403 responses, or an error body stating the credential is invalid.
- Confirm the
Authorizationheader is present and formatted asBearer <key>with a single space. - Check that the environment variable actually holds a value — a trailing newline pasted into an env var breaks the header in ways that are invisible in logs.
- Verify the key belongs to the same HiAPI project you expect and has not been rotated.
Fastest test: rerun the raw curl from earlier. If curl works and Python does not, the bug is in your client, not your account.
2. Malformed payload
Symptoms: 400 or 422 responses, or validation messages naming a parameter.
- Confirm
Content-Type: application/jsonand that the body is valid JSON — a stray trailing comma is the classic culprit. - Check that
modelis exactlyminimax-h3. - Confirm
durationandaspect_ratiofall within the supported ranges for the model. - In image mode, confirm the image reference is reachable and in an accepted format.
Read the error message literally. Validation errors usually name the offending field; developers often skim past that and start rewriting unrelated parts of the payload.
3. Polling never completes
Symptoms: status stays queued or processing well past a reasonable duration, or loops forever.
- Log the full status response — the status value may not be what your code assumes.
- Check the field you are reading. If your terminal set checks
"completed"but the API returns"succeeded", your loop runs forever. Print one raw response early in development. - Confirm the task ID was copied exactly, with no truncation or whitespace.
- Add a wall-clock deadline; a stuck loop with no ceiling is a bug in your code, not the API.
4. Timeouts and transient network errors
Symptoms: connection errors, read timeouts, or 5xx responses on submit or poll.
- Ensure every call passes an explicit
timeout— the default is none in many clients, meaning a hung socket can block forever. - Distinguish connect timeouts from read timeouts; a submit that times out on read may have actually created a job. Log the request ID from headers if one is returned, and check whether a task appeared before blindly resubmitting.
- For a 5xx on poll, retry — the job may be fine. For a 5xx on submit, verify no task was created to avoid duplicate generations.
A quick triage habit: keep a scratch curl file next to your project with the submit and poll commands pre-filled from environment variables. Reproducing any bug outside your application code takes seconds and immediately tells you whether the problem is transport or logic.
Making It Production-Ready
A working script is not a working service. Video jobs are slow enough that production traffic will overlap, retry, and occasionally fail in ways a single manual run never reveals. Four patterns carry most of the weight.
Retry with backoff — but only where it is safe
Retry policy depends on which call failed:
- Polling is inherently safe to retry. A failed status check has no side effects, so retry with exponential backoff and jitter, capped at a handful of attempts.
- Submission is not safe to retry blindly. A timeout does not mean the job was not created. Before resubmitting, check whether a task for that request already exists (using a request ID from response headers if available, or a short reconciliation window). Alternatively, make your own submission idempotent by caching task IDs keyed on a hash of the payload, so a retried request returns the existing task instead of starting a new render.
- Model-level failures — terminal status
failed— should generally not be retried automatically with an identical payload. The same input tends to fail the same way. Log it, alert, and let a human or a modified prompt take over.
Add jitter to every backoff sleep. Without it, a fleet of workers that retries in lockstep produces synchronized spikes that make a bad situation worse.
Log task IDs everywhere
The task ID is the only durable link between your system and a generated video. Write it to your logs with structured fields — task_id, model, duration, submit timestamp — the moment submission succeeds. When a user reports a missing video, searching by task ID finds the full history in seconds. Also record the terminal status and elapsed time so you can answer "how long does this usually take" with data rather than memory.
Set explicit timeout budgets
Think in terms of a total budget for the whole operation, not just per-request timeouts. A job has three phases — submit, wait, download — and each needs a bound. A reasonable structure:
- Short timeout on submit and poll requests, so a dead connection is detected quickly.
- A total wall-clock cap on polling sized for your longest supported duration and resolution, with margin.
- A bounded download with streaming writes, so a large file does not exhaust memory or hang a worker.
When the budget is exhausted, fail the job cleanly, release the concurrency slot, and report a clear error. A predictable failure beats a request that hangs until the platform restarts your container.
Separate submission from consumption
The submit-then-poll design maps naturally onto a queue architecture: your web handler submits and returns the task ID, a background worker polls and stores the result, and the client polls your status endpoint. This decouples user-facing latency from render time, makes concurrency limits easy to enforce, and means a spike in submissions does not exhaust your web tier's thread pool.
Get these four right and the async shape of minimax-h3 works with you instead of against you: jobs are tracked, retries are safe, failures are visible, and nothing hangs indefinitely.
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