Tutorial
How to Use kling-3.0/motion-control via the HiAPI API: curl and Python
On this page
What kling-3.0/motion-control does and when to choose it
Motion control is the part of video generation where you hand the model a reference clip and let it drive motion, timing, and framing in the output instead of describing movement in a text prompt alone. With kling-3.0/motion-control on the HiAPI API, the reference video is the primary input: it anchors how things move, and your other parameters shape what gets generated around that motion.
Choose this model when the motion itself is the hard part. Examples that fit well:
- You have a short clip whose camera movement or subject motion you want to reproduce with different content.
- You want predictable movement rather than a prompt-and-pray text-to-video result.
- You are building a pipeline where motion is a reused asset across many generations, so it should be an input rather than a sentence.
If you only need text-to-video with no movement reference, motion control adds an upload step and a stricter input contract for no benefit. Likewise, if your reference clip is very long or has unstable framing, expect more retries. The rest of this guide assumes you have decided motion control is the right tool and want a reliable, copyable integration.
Prerequisites and endpoint setup
Before your first call, get three things in order.
1. An API key
Create a key in your HiAPI.ai account dashboard and store it in an environment variable rather than in source code:
export HIAPI_API_KEY="your_api_key_here"
Every request sends it as a bearer token: Authorization: Bearer $HIAPI_API_KEY.
2. A base URL convention
All HiAPI calls share one base URL and a versioned path prefix. Keep the base URL in configuration so you can change environments without touching call sites:
export HIAPI_BASE_URL="https://api.hiapi.ai"
3. The model identifier
The model is selected per request via the model field, using the exact identifier kling-3.0/motion-control. Do not hardcode it in many places — pass it as a constant so a future model swap is a one-line change.
You also need somewhere to host your reference video that the API can fetch. A signed, time-limited URL is the usual approach; make sure it is reachable without custom headers or cookies.
Once those three pieces exist, the remaining work is request shape and job lifecycle.
Supplying the reference video and motion parameters
A motion-control request has two conceptual halves: the motion source (your reference video) and the generation settings (what the model should produce).
The reference video
You supply the reference video as a URL in the request body, not as raw bytes in the JSON payload. Two practical rules:
- Use a URL that stays valid long enough for the job to be queued and processed. Expiring signed URLs are a common cause of jobs that fail minutes after submission.
- Keep the clip short and visually stable. Long, shaky, or heavily cut reference footage gives the model an ambiguous motion signal.
If your asset lives in private storage, generate a signed URL with a generous expiry window at submission time rather than at upload time.
Motion and output parameters
The parameters you will typically set alongside the reference video:
- A text prompt describing the target content that should be animated by the reference motion.
- Output aspect and duration settings, so the generated clip matches where you will display it.
- Any motion-strength or adherence-style setting the model exposes, to trade off between faithfulness to the reference and freedom for the prompt.
Treat these as a small, explicit config object in your client rather than spreading them across function arguments. That makes it easy to log exactly what was submitted, which is the single most useful debugging artifact for this model.
Finally, validate before you submit: the reference URL responds with a media content type, the prompt is non-empty, and any numeric settings are within documented ranges. A local check costs milliseconds; a rejected async job costs a round trip and confusion.
Async jobs: submit, poll, and read the result
Motion control does not return a video in the submit response. It returns a task you then track. Build your client around that lifecycle from the start.
Step 1 — Submit
POST the job to the model endpoint. A successful submission returns a task identifier. Persist that ID immediately — it is your only handle on the job, and you will need it for polling and for support requests.
Step 2 — Poll
GET the task status using the ID. The status field tells you which of three situations you are in:
- Pending or queued: accepted, not started. Keep waiting.
- Processing or running: work in progress. Keep waiting, but with backoff.
- Terminal: succeeded or failed. Stop polling.
Your loop should check for terminal states explicitly, not just for the presence of an output field. A failed task has no result, and treating "no result yet" as "still running" produces infinite loops.
Step 3 — Read the result
On success, the response carries the output location, typically a URL to the generated video. Download it to your own storage promptly — generated assets behind temporary URLs should not be treated as permanent.
Polling hygiene
Two rules keep this reliable in production:
- Back off between polls (start around a second or two, then increase) instead of hammering the endpoint.
- Cap total wait time and surface a timeout as an error you can retry, rather than blocking a worker forever.
Record the task ID, the submitted parameters, and the final status for every run. When something looks wrong, that log answers most questions before you need to ask anyone.
A working curl request
Here is the full flow in shell. It submits a job, extracts the task ID, then polls until the task reaches a terminal state.
#!/usr/bin/env bash
set -euo pipefail
BASE="$HIAPI_BASE_URL"
MODEL="kling-3.0/motion-control"
# 1) Submit the job
SUBMIT=$(curl -sS -X POST "$BASE/v1/videos/generations" \
-H "Authorization: Bearer $HIAPI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "kling-3.0/motion-control",
"prompt": "a paper boat drifting through a rainy city street, cinematic",
"reference_video_url": "https://your-bucket.example.com/refs/pan-left.mp4",
"duration": 5,
"aspect_ratio": "16:9"
}')
echo "$SUBMIT"
TASK_ID=$(echo "$SUBMIT" | python3 -c 'import sys,json; print(json.load(sys.stdin)["id"])')
echo "task: $TASK_ID"
# 2) Poll until terminal
while true; do
STATUS_JSON=$(curl -sS "$BASE/v1/videos/generations/$TASK_ID" \
-H "Authorization: Bearer $HIAPI_API_KEY")
STATUS=$(echo "$STATUS_JSON" | python3 -c 'import sys,json; print(json.load(sys.stdin)["status"])')
echo "status: $STATUS"
case "$STATUS" in
succeeded) echo "$STATUS_JSON"; break ;;
failed|cancelled) echo "$STATUS_JSON" >&2; exit 1 ;;
esac
sleep 3
done
Two notes on adapting this. First, keep the model identifier and endpoint paths in variables so the script stays readable. Second, the jq-free parsing above uses Python only because it is near-universally available; swap in jq if that is your preference. The important behavior is the same either way: extract the task ID from the submit response, then poll its status until you see a terminal value.
The same request in Python
The Python client below mirrors the curl flow, with the polling loop hardened: exponential-ish backoff, an overall timeout, and explicit handling of every terminal state.
import os
import time
import requests
BASE = os.environ["HIAPI_BASE_URL"]
KEY = os.environ["HIAPI_API_KEY"]
MODEL = "kling-3.0/motion-control"
HEADERS = {
"Authorization": f"Bearer {KEY}",
"Content-Type": "application/json",
}
TERMINAL = {"succeeded", "failed", "cancelled"}
def submit_job(prompt: str, reference_video_url: str, duration: int = 5) -> str:
payload = {
"model": MODEL,
"prompt": prompt,
"reference_video_url": reference_video_url,
"duration": duration,
"aspect_ratio": "16:9",
}
r = requests.post(
f"{BASE}/v1/videos/generations",
headers=HEADERS,
json=payload,
timeout=30,
)
r.raise_for_status()
return r.json()["id"]
def wait_for_job(task_id: str, timeout_s: int = 600) -> dict:
deadline = time.time() + timeout_s
delay = 2.0
while time.time() < deadline:
r = requests.get(
f"{BASE}/v1/videos/generations/{task_id}",
headers=HEADERS,
timeout=30,
)
r.raise_for_status()
data = r.json()
status = data.get("status")
if status in TERMINAL:
return data
time.sleep(delay)
delay = min(delay * 1.5, 15.0)
raise TimeoutError(f"task {task_id} did not finish in {timeout_s}s")
if __name__ == "__main__":
task_id = submit_job(
prompt="a paper boat drifting through a rainy city street, cinematic",
reference_video_url="https://your-bucket.example.com/refs/pan-left.mp4",
)
print("submitted:", task_id)
result = wait_for_job(task_id)
if result["status"] == "succeeded":
print("output:", result.get("output"))
else:
print("job did not succeed:", result)
The pieces worth keeping when you adapt this: the terminal-state set, the capped backoff, and the separate submit and wait functions. In a real service you would split those across two processes — submit from the request handler, store the task ID, and let a worker poll — so a slow job never blocks an HTTP response.
Common failure points and how to debug them
Most integration problems with kling-3.0/motion-control fall into a small number of categories. Check these in order.
Authentication and model errors
A 401 almost always means the bearer token is missing, truncated, or taken from the wrong environment. A model-not-found error means the model string does not match exactly — it is a slash-separated identifier, so transposed characters or stray whitespace will fail silently in config and loudly at the API.
Reference video unavailable
The job is accepted, then fails minutes later because the references URL could not be fetched. Causes, in order of frequency: the signed URL expired before processing, the URL requires authentication headers the service does not send, or the URL returns HTML (a login page or error page) instead of a video. Test the URL with a plain curl from outside your network and confirm the content type.
Malformed or out-of-range parameters
Duration and aspect settings outside documented ranges are rejected at submission, which is the good case — you get an immediate error. Validate these locally before sending so a typo does not require a round trip to discover.
Polling bugs
The two classic ones: looping forever because the loop only checks for an output field and never for failed, and rate-limiting yourself by polling in a tight loop with no sleep. Add explicit terminal-state checks and backoff, and always send the task ID in error reports so a job can be looked up rather than reconstructed.
Result URL expiry
You generated the video but stored only the temporary output URL. Download outputs to your own storage as soon as a job succeeds; treat the returned URL as a fetch handle, not as durable storage.
Start every debugging session by logging the exact request body and the raw response JSON. Almost every issue above is visible in those two artifacts. When you are ready to go further, explore the other video models and endpoint reference in the HiAPI.ai docs and keep the same submit-then-poll client shape.
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