Tutorial
How to Call wan2.7-video text-to-video via the HiAPI API: curl and Python
On this page
What this tutorial builds
By the end of this walkthrough you will have a small, working pipeline that submits a text-to-video job to wan2.7-video/text-to-video through the HiAPI API — once with curl, once with Python — and then waits for the finished video.
The two calls are deliberately equivalent. The curl version is the reference you can paste into a terminal to confirm your credentials and payload are correct. The Python version wraps the same request in a function you can drop into a script or service, with polling, error handling, and sensible defaults.
Because video generation takes far longer than a chat completion, the flow is asynchronous: you submit a job, receive an identifier, then poll until the job reports a terminal status. Everything below is organized around that lifecycle, so the structure carries over if you later move to image-to-video or a different video model on the same endpoint family.
Before you send your first request
Three things need to be true before your first call can succeed.
Credentials
You need a HiAPI API key, sent as a bearer token in the Authorization header. Keep it in an environment variable rather than in source:
export HIAPI_API_KEY="your-key-here"
A known model identifier
Model identifiers are exact strings. For this tutorial the value is wan2.7-video/text-to-video — including the task suffix. A near-miss such as wan2.7-video or wan2.7/text-to-video will be rejected, so copy the identifier from the model listing rather than typing it from memory.
A prompt you can evaluate
Video generation is expensive to iterate on blindly. Write one concrete prompt up front (subject, action, camera behavior, lighting, style) so that when a clip comes back you can judge whether the settings — not the wording — need to change.
You also want an HTTP client and a way to read JSON. curl plus jq covers the shell side; Python with requests covers the scripted side.
Anatomy of the request body
A text-to-video request is a single JSON object. The fields fall into three groups.
Identity
model— the exact model identifier,wan2.7-video/text-to-video.
Content
prompt— the text describing the video you want. This is the field that does most of the work; be specific about motion, framing, and style rather than piling on adjectives.negative_prompt— optional. Describes what should not appear. Useful for suppressing common artifacts, but not a substitute for a well-written prompt.
Generation settings
duration— how long the output clip should be.resolution— the output dimensions/size tier.seed— optional. Fix it when you want to compare two prompts or two setting changes against a stable starting point.
A minimal payload only needs model and prompt; the platform applies defaults for the rest. But defaults are not the same as choices — see the duration and resolution section below for why you should set them explicitly in production.
Keep the body shallow and flat. Nesting only the fields that genuinely belong to a sub-object keeps the request readable and makes schema errors easier to spot.
Submitting the job with curl
Here is a complete submission. The endpoint accepts JSON and returns a job handle rather than the video itself.
curl -X POST "$HIAPI_BASE_URL/v1/video/generations" \
-H "Authorization: Bearer $HIAPI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "wan2.7-video/text-to-video",
"prompt": "A slow tracking shot through a rain-soaked neon alley at night, reflective puddles, shallow depth of field, cinematic color grade",
"duration": 5,
"resolution": "720p"
}'
A successful submission returns an object that includes a job or task identifier and a status. The shape is roughly:
{
"id": "job_abc123",
"status": "queued",
"model": "wan2.7-video/text-to-video"
}
Two things to note. First, status is not succeeded — nothing has been rendered yet. Second, the response contains no video URL. That URL appears only after the job reaches a terminal state.
If you want to keep the identifier in your shell session for the polling step:
JOB_ID=$(curl -s -X POST "$HIAPI_BASE_URL/v1/video/generations" \
-H "Authorization: Bearer $HIAPI_API_KEY" \
-H "Content-Type: application/json" \
-d @payload.json | jq -r '.id')
echo "$JOB_ID"
Moving the body into payload.json keeps the command short and makes it easy to tweak the prompt between runs.
Submitting the job in Python
The Python version is the same request with better ergonomics. Everything that was a header or a JSON key in curl becomes a keyword argument.
import os
import time
import requests
BASE_URL = os.environ["HIAPI_BASE_URL"]
API_KEY = os.environ["HIAPI_API_KEY"]
HEADERS = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
}
payload = {
"model": "wan2.7-video/text-to-video",
"prompt": (
"A slow tracking shot through a rain-soaked neon alley at night, "
"reflective puddles, shallow depth of field, cinematic color grade"
),
"duration": 5,
"resolution": "720p",
}
resp = requests.post(
f"{BASE_URL}/v1/video/generations",
headers=HEADERS,
json=payload,
timeout=30,
)
resp.raise_for_status()
job = resp.json()
print(job["id"], job["status"])
The mapping from the shell version is one-to-one:
-H "Authorization: ..."→ theHEADERSdict.-d '<json>'→json=payload. Passing a dict rather than a string meansrequestshandles serialization, so you cannot accidentally ship malformed JSON.- The
.idextracted withjq→job["id"].
Two Python-specific habits are worth adopting now. Always set a timeout on the submit call — the request is small and should return quickly, so a long hang means something is wrong with the connection, not the render. And call raise_for_status() before reading the body, so an HTTP-level failure produces a clear traceback instead of a confusing KeyError on job["id"].
Handling the asynchronous job and polling
Polling is where most integrations either become robust or become flaky. The job has a lifecycle — typically queued, then processing, then a terminal state of succeeded or failed — and your loop must handle all three.
def wait_for_job(job_id, interval=5, max_attempts=120):
url = f"{BASE_URL}/v1/video/generations/{job_id}"
for attempt in range(max_attempts):
r = requests.get(url, headers=HEADERS, timeout=30)
r.raise_for_status()
data = r.json()
status = data.get("status")
if status == "succeeded":
return data
if status in ("failed", "cancelled"):
raise RuntimeError(f"Job {job_id} ended as {status}: {data.get('error')}")
time.sleep(interval)
raise TimeoutError(f"Job {job_id} still not finished after {max_attempts} polls")
A few design points in that loop matter more than they look:
Check the terminal status explicitly. Treating anything that is not succeeded as "keep waiting" means a failed job silently burns your entire retry budget. Match on the failure states and raise.
Choose the interval deliberately. Video rendering takes tens of seconds to minutes. Polling every 200 ms adds load and tells you nothing new. Start around 5 seconds; if your jobs routinely run long, increase the interval rather than the attempt count.
Always bound the loop. A max_attempts cap converts an infinite hang into a diagnosable TimeoutError. Log the job ID with it — that is the value you need when investigating.
Respect rate limits. If you submit batches, do not fire all polls at once. A shared poller on a fixed interval, or simple client-side throttling, keeps you inside the limits.
On success, the response carries the location of the finished asset. Download it immediately rather than treating the job record as permanent storage.
Choosing duration and resolution
These two settings shape the output more than any other parameter, and both affect how long the job runs and what it costs. Billable usage is measured in output seconds, and resolution drives the amount of work per second — so treat both as intentional choices per use case rather than as fields to leave at defaults.
Duration
Longer clips give motion room to develop, but every extra second is more rendering and more cost, and long generations are also where coherence problems appear. Practical guidance:
- Short (a few seconds) — social loops, product hero shots, b-roll. Cheapest to iterate, easiest to judge.
- Medium — narrative beats, establishing shots.
- Long — only when the story genuinely needs it. If you need a long video, consider generating several short clips and editing them together; it is usually cheaper and gives you more control than one long render.
While you are iterating on a prompt, generate the shortest clip the model allows. Judge composition and motion at that length, then extend once you are happy.
Resolution
Higher resolution means more pixels per frame, a longer render, and more cost. It also matters less than you might expect on small screens. A 1080p master is right for a client deliverable; a 720p (or lower) draft is right for deciding whether the prompt works at all.
The efficient pattern is a two-stage workflow: lock the prompt and duration at low resolution, then re-run the final job once at delivery resolution. Do not iterate at maximum settings — you will spend most of your budget on takes you discard.
Debugging common errors
Most failures are about how you shaped the request, not about the model. Work through these categories in order before concluding anything about the model's capability.
401 / 403 — credentials
Check that the key is set in the environment the process actually sees (a key exported in one shell is invisible to a systemd service), that the header is Authorization: Bearer <key>, and that there is no trailing whitespace in the variable. Print the first few characters of the key when debugging, never the whole thing.
404 — wrong path or model
The endpoint path and the model identifier are separate things and both must be exact. Confirm the URL you are posting to and confirm wan2.7-video/text-to-video is copied character-for-character from the model listing. A valid key with a wrong model string still returns a not-found-style error.
400 — malformed body
This is the most common category. Frequent causes: a numeric field like duration sent as the string "5", a prompt sent as a list instead of a string, or a payload accidentally double-encoded. The quickest triage is to re-send the exact curl command — if the shell call succeeds and the Python call does not, the bug is in how your script builds the dict, not in the request.
422 / validation errors
A syntactically valid body with a semantic problem: a duration outside the supported range, an unknown resolution tier, or a missing required field. Read the message — it usually names the offending field.
Job fails after submission
The submit call succeeded but the render did not. This can be a content-policy rejection or a transient rendering failure. Log the job ID and the error payload; if it is transient, resubmitting the same payload is a reasonable first move. If it recurs on the same prompt, vary the prompt wording or generation settings rather than hammering the same request.
Polling never resolves
If the job stays in processing far longer than comparable jobs, stop polling, log the job ID, and treat it as a failed job. Long tails are rare enough that a bounded timeout with a clear error is better than an open loop.
Start with the curl reference for every new problem: it removes your code from the equation and isolates whether the issue is the request or the client.
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