Tutorial
How to Use kling-4.0-flash Image-to-Video via the HiAPI API: curl and Python
A practical request walkthrough: first-frame image input, async job polling, sync audio, and error triage
- Model
- kling-4.0-flash
On this page
What the kling-4.0-flash image-to-video endpoint does
kling-4.0-flash/image-to-video is an image-conditioned video generation model. You hand it a single image — the first frame — plus a text prompt, and it returns a generated video that starts from that frame and evolves according to your description.
The most important thing to internalize before writing code: this is not a request/response call that returns video bytes in the same HTTP exchange. Generation takes time, so the endpoint follows an asynchronous job model. Your first request submits a job; you then retrieve the result by polling for the job's status until it reaches a terminal state.
Keep these three concepts separate in your head, because they map to different parts of your client:
- Submission — the payload you send: the first-frame image, the prompt, and generation options.
- Task reference — the identifier returned on submission, which you use to look the job up later.
- Result retrieval — repeated status checks that eventually return the finished video (or a failure).
Once you treat the endpoint as a job queue rather than an RPC, the rest of the integration — polling intervals, timeouts, retries — becomes ordinary async plumbing rather than a special case. If you want the broader endpoint reference alongside this walkthrough, keep it open in a second tab while you follow along.
Before you send a request
Three things need to be in place before your first call.
1. API credentials
You need a HiAPI API key. Send it on every request as a bearer token in the Authorization header. Keep it out of source control — read it from an environment variable rather than pasting it into a script.
export HIAPI_API_KEY="your-api-key-here"
2. The endpoint path
All calls go through the unified HiAPI interface. The model identifier you target is kling-4.0-flash/image-to-video. Your submission request and your later status lookups both address the same model namespace, so keep the identifier in one constant in your code rather than scattering string literals.
3. A prepared first-frame image
You need one image to use as the opening frame. Before sending, decide two things:
- How you will pass it — as a publicly reachable URL or as encoded image data, depending on what the endpoint accepts for your use case.
- Whether it is well-formed — correct format, readable, and not so large that the request body becomes unwieldy.
A practical rule: keep the request body small and explicit. If you are passing a URL, make sure it is reachable without authentication from the calling side. If you are passing encoded data, confirm the encoding is exactly what the endpoint expects.
Also prepare a short, concrete prompt. Image-to-video prompts work best when they describe motion and change (what moves, how the camera behaves) rather than restating what is already visible in the frame.
A working curl request
Here is one complete submission call. Replace the placeholder values with your own key, image, and prompt.
curl -X POST "https://api.hiapi.ai/v1/models/kling-4.0-flash/image-to-video" \
-H "Authorization: Bearer $HIAPI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Slow dolly-in on the subject as light shifts across the scene",
"image": "https://your-host.example/first-frame.jpg"
}'
Walking through the pieces:
-X POST— submission is a write operation, not a lookup.- The URL — the model identifier is part of the path on the unified endpoint. This is the only place you name the model.
Authorization: Bearer $HIAPI_API_KEY— the header the shell expands from your environment. Quoting it with double quotes lets the variable expand while keeping the value a single argument.Content-Type: application/json— the body is JSON; without this header some gateways will reject or misparse the payload.-d '{ ... }'— the JSON body.promptdescribes the motion;imagesupplies the first frame. Every field is explicit — nothing is implied by position or defaults you cannot see.
A successful submission returns a JSON body containing a task identifier. Capture it — that value is your handle on the job. If you are exploring interactively, pipe the response through a JSON formatter so the identifier is easy to copy:
curl -s -X POST "https://api.hiapi.ai/v1/models/kling-4.0-flash/image-to-video" \
-H "Authorization: Bearer $HIAPI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"prompt":"Slow dolly-in as light shifts","image":"https://your-host.example/first-frame.jpg"}' | python -m json.tool
Do not assume the video is in this response. It is not — this response only tells you the job was accepted.
The same request in Python
The Python client mirrors the curl payload exactly. The semantics do not change when you switch languages; only the mechanics of sending bytes do. Using requests and reading the key from the environment:
import os
import requests
API_KEY = os.environ["HIAPI_API_KEY"]
MODEL = "kling-4.0-flash/image-to-video"
BASE_URL = "https://api.hiapi.ai/v1/models"
def submit_job(prompt: str, image: str) -> dict:
response = requests.post(
f"{BASE_URL}/{MODEL}",
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
},
json={
"prompt": prompt,
"image": image,
},
timeout=30,
)
response.raise_for_status()
return response.json()
job = submit_job(
prompt="Slow dolly-in on the subject as light shifts across the scene",
image="https://your-host.example/first-frame.jpg",
)
print(job)
Notes on the port:
json=instead of-d— passing a dict letsrequestsserialize the body and set the content type. You get the same wire format as the curl example without hand-writing JSON.raise_for_status()— converts non-2xx responses into exceptions so you do not accidentally treat an error body as a job reference.timeout=30— submission should be fast. A generous timeout guards against a hung connection without masking a genuinely slow call.- One constant for the model — if you later switch models, you change one line.
The returned dict contains the task identifier, which the next section puts to work.
Handling the async job lifecycle
The integration pattern is submit, then poll. Two phases, clearly separated.
Phase 1: submit and capture the reference
Your submit_job call from the previous section returns a JSON body with a task identifier. Store it. Every subsequent status check needs it, and losing it means losing the job.
Phase 2: poll until terminal
Status checks are read requests against the same job. Repeat them on an interval until the job reaches a terminal state — either completed or failed. A simple loop with a bounded number of attempts:
import time
def wait_for_job(task_id: str, attempts: int = 60, interval: float = 5.0) -> dict:
for _ in range(attempts):
response = requests.get(
f"{BASE_URL}/{MODEL}",
headers={"Authorization": f"Bearer {API_KEY}"},
params={"task_id": task_id},
timeout=30,
)
response.raise_for_status()
status = response.json()
state = status.get("status")
if state in ("succeeded", "failed"):
return status
time.sleep(interval)
raise TimeoutError(f"Job {task_id} did not finish in time")
Design decisions worth making deliberately:
- Bound the loop. Never poll forever. A maximum attempt count plus a fixed interval gives you a predictable worst-case wait.
- Sleep between checks, not inside the request. Polling too aggressively wastes quota and can get you rate-limited.
- Treat failure as a terminal state. A failed job will not become a success on the next poll — stop and surface the error.
- Distinguish pending from finished. Only the terminal states end the loop; anything else means keep waiting.
- Persist the task ID. If your process crashes mid-poll, you want to resume rather than regenerate.
For production, move polling out of the request thread — a background worker or queue consumer — so a long generation does not hold a web request open.
Using the synchronous audio option
The endpoint offers a synchronous audio option. In practice this means one thing for your client: if you enable it, expect the call to block until generation finishes rather than returning a task reference you poll.
That changes your design in concrete ways:
- Timeout budgets must grow. A blocking generation call can take far longer than a typical API request. Set the client timeout to cover the full expected duration, not the submission duration.
- You cannot checkpoint mid-flight. With polling you can crash and resume using the task ID. With a blocking call, a dropped connection means you redo the work.
- Thread and connection pool pressure. A blocking call occupies a worker for its entire duration. In a web server, that caps your concurrency fast.
When is a blocking call acceptable? When you are running single-shot scripts, CLI tools, or batch jobs where nothing else waits on the result and simplicity beats throughput. In those contexts, a synchronous call removes the polling machinery entirely and the code gets shorter.
When should you avoid it? In any user-facing request path, in high-concurrency services, or anywhere a client can time out and retry — a retried blocking call can double your work. There, keep the async submit-and-poll pattern from the previous section and leave the synchronous option off.
Troubleshooting common failures
Work through failures in layers. The first error you see is usually the shallowest one, so fix it and re-run rather than guessing at several at once.
Authentication errors
A 401 or 403 means the credential is missing, malformed, or rejected. Check that HIAPI_API_KEY is actually set in the environment your process sees — an exported variable in one shell does not reach a different shell or a container. Verify the Authorization header is Bearer <key> with a single space and no stray quotes carried over from a copy-paste.
Malformed payloads
A 400 usually means the body did not parse or a required field was missing. Re-check that you sent Content-Type: application/json, that the JSON is valid (a trailing comma will sink it), and that prompt and image are both present and non-empty strings. When debugging, dump the exact body you are sending — not the dict you intended to send.
Image input problems
These often surface as validation errors rather than obvious image errors. Check, in order:
- Reachability — if you passed a URL, fetch it from the same network context your request originates from. A URL that works in your browser may be firewalled or auth-protected for the API.
- Format — confirm the image is a supported, non-corrupt file. Re-export it if in doubt.
- Size — an oversized image can fail validation or bloat the request body past limits.
- Encoding — if you are sending encoded data, verify the encoding matches what the endpoint expects exactly; a mismatched prefix or stray whitespace breaks it.
Job-level failures
If submission succeeds but the job ends in a failed state, the request was well-formed but generation did not complete. Re-read the prompt for ambiguity or physically implausible motion, and confirm the first-frame image is actually usable as a starting point. Retry once with a simplified prompt before assuming a systemic problem — and log the task ID alongside the failure so you can correlate later.
Timeouts in the polling loop
A TimeoutError from wait_for_job means your bound was too tight, not that the job died. Increase the attempt count or interval, and check whether you are polling a task ID from an earlier, already-finished run.
Start with a minimal request — one image, one short prompt, no optional fields — and add complexity only once the baseline works. Most integration issues disappear when the payload is small and explicit.
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