Text-to-video generation is now reliable enough to build real features on, not just weekend demos. This tutorial walks through a working Python integration from scratch: authentication, sending your first request, checking on the result, downloading the output, and handling the errors that will inevitably show up. By the end, you'll have a small FastAPI service that wraps the whole flow. If you want the concepts first, our explainer on how text-to-video generation works is a good primer, and our complete text-to-video API guide covers the wider landscape before you commit to a model.
What You'll Build
A small backend service that accepts a text prompt, starts a video generation job, and lets a client check on progress until the video is ready to download.
Prerequisites:
- Python 3.9 or later
- An API key from Apiframe (see the getting started guide). The examples use Apiframe's unified video API, but the same pattern applies to any API that runs generation in the background
- The
requestspackage (pip install requests), andfastapiplusuvicornfor the final example (pip install fastapi uvicorn)
How Text-to-Video APIs Differ from Image-to-Video
If you've already built an image-to-video integration, most of the setup here will look familiar, but two differences are worth calling out before you write any code.
Prompt-only input instead of a reference image. Image-to-video starts from a still image and animates it. Text-to-video has nothing to work from but your words, so the model has to invent the scene, the subject, and the motion. That makes the prompt matter more. Vague prompts tend to produce vague, drifting motion.
Duration and camera direction. Text-to-video models let you set the clip length (commonly 5, 6, or 10 seconds depending on the model), and many respond to camera instructions written into the prompt itself, such as a slow zoom or a pan, since there's no starting frame to anchor the shot.
The useful part is that the two modes usually run through the same endpoint, separated only by an image field. If you later want to let users upload a product photo and animate it, almost all of the code in this tutorial carries over.
Step 1: Authentication and Setup
Every request needs your API key in an X-API-Key header. Keep it out of your code and load it from an environment variable instead.
import os
import requests
API_KEY = os.environ["APIFRAME_API_KEY"]
BASE_URL = "https://api.apiframe.ai/v2"
HEADERS = {
"X-API-Key": API_KEY,
"Content-Type": "application/json",
}Store the key in a .env file locally, or in whatever your hosting platform provides for storing passwords. Never write it directly into a file you commit.
Step 2: Sending Your First Text-to-Video Request
Video generation runs in the background. You submit a prompt, and the API responds right away with a job ID and a QUEUED status instead of making you wait for the finished video.
The example below uses Hailuo 02, which produces 6 or 10 second clips at 768p or 1080p. It's a dependable starting point and costs 39 credits ($0.39) for a 6 second clip at 768p. If you want better motion once the integration works, Hailuo 2.3 is the quality upgrade and 2.3 Fast is cheaper and about twice as quick. Both are a one-word change to the model field, and our Hailuo versions comparison explains which one fits which job.
def submit_video_job(prompt: str, duration: int = 6, resolution: str = "768p") -> dict:
payload = {
"prompt": prompt,
"model": "hailuo-02",
"hailuoParams": {
"duration": duration,
"resolution": resolution,
},
}
response = requests.post(
f"{BASE_URL}/videos/generate",
headers=HEADERS,
json=payload,
)
response.raise_for_status()
return response.json()
job = submit_video_job("a paper airplane gliding through a sunlit office, slow motion")
print(job) # {"jobId": "b2c3d4e5-...", "status": "QUEUED"}One constraint to code around: 1080p only supports the 6 second duration, not 10. Validate that combination before you submit if you're exposing these options to users, because the API will reject it. The same limit applies across the whole Hailuo lineup, so switching versions will not get you around it. Apiframe has also added the newer Hailuo 03 model if you want to compare against the latest release.
The prompt field accepts up to 4,000 characters, and model is required on every request. Other models such as Kling, Seedance, and Wan take the same top-level shape but their own parameters object, for example klingParams or seedanceParams. Check the model's reference page for the exact field names before swapping.
Step 3: Checking for Completion
Once you have a job ID, check the jobs endpoint until the status changes to COMPLETED or FAILED. Most video jobs take two to three minutes, so check every 5 to 10 seconds rather than every second or two.
import time
def wait_for_completion(job_id: str, poll_interval: int = 6, timeout: int = 600) -> dict:
elapsed = 0
while elapsed < timeout:
response = requests.get(f"{BASE_URL}/jobs/{job_id}", headers=HEADERS)
response.raise_for_status()
job = response.json()
if job["status"] == "COMPLETED":
return job
if job["status"] == "FAILED":
raise RuntimeError(f"Generation failed: {job.get('error')}")
time.sleep(poll_interval)
elapsed += poll_interval
raise TimeoutError(f"Job {job_id} did not complete within {timeout} seconds")
result = wait_for_completion(job["jobId"])
print(result["result"]) # {"videoUrl": "https://cdn2.apiframe.ai/videos/....mp4"}Checking in a loop works fine for scripts and low-volume use, but at any real scale it's better to have the API come to you. Pass webhookUrl and webhookEvents in the original request (["completed", "failed"]) and the API will send the result to your server the moment the job finishes, rather than your code asking repeatedly. Each delivery is signed, so your server can confirm it genuinely came from the API before acting on it. Our step-by-step callback setup guide covers securing and testing that endpoint.
Step 4: Handling and Storing the Output Video
Once the job is COMPLETED, the result contains a hosted video URL. Download it and confirm you actually received a video before handing it to the rest of your app.
def download_video(video_url: str, output_path: str) -> str:
response = requests.get(video_url, stream=True, timeout=60)
response.raise_for_status()
content_type = response.headers.get("Content-Type", "")
if "video" not in content_type:
raise ValueError(f"Unexpected content type: {content_type}")
with open(output_path, "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
return output_path
video_url = result["result"]["videoUrl"]
download_video(video_url, "output.mp4")Generated files stay on the provider's servers for a limited window (Apiframe keeps results for 90 days), so if your product needs the video long-term, download it and move it to your own storage rather than relying on that link. To plan the budget ahead of time, our AI video API pricing guide lists what each model charges, and our guide on estimating monthly AI video costs works through the math at your own volume.
Step 5: Error Handling and Retries
A few failures show up often enough to handle on purpose rather than letting them crash the request. This wrapper retries on rate limits and timeouts, waiting twice as long after each attempt.
import uuid
def submit_with_retry(prompt: str, max_retries: int = 3, **kwargs) -> dict:
# Reuse one key across retries so a resubmitted request
# does not start (and bill for) a second generation.
idempotency_key = str(uuid.uuid4())
headers = {**HEADERS, "Idempotency-Key": idempotency_key}
for attempt in range(1, max_retries + 1):
try:
response = requests.post(
f"{BASE_URL}/videos/generate",
headers=headers,
json={"prompt": prompt, "model": "hailuo-02", "hailuoParams": kwargs},
timeout=30,
)
if response.status_code == 429:
time.sleep(2 ** attempt)
continue
response.raise_for_status()
return response.json()
except requests.exceptions.Timeout:
if attempt == max_retries:
raise
time.sleep(2 ** attempt)
raise RuntimeError("Max retries exceeded")That idempotency key matters more than it looks. When a request times out, you have no way of knowing whether the server received it. Retrying blindly can start a second generation and bill you twice for one video. Sending the same key on every retry lets the API recognise the repeat and return the original job instead. Confirm the header name against the docs, since it varies between providers.
The failures worth planning for:
- Timeouts: the request itself failing on a slow connection, not the generation. Set a
timeoutvalue, then wait and retry. - Rejected prompts: a
FAILEDjob with an error like"Provider returned an error: content policy violation". The same prompt will not succeed on a retry, so show the error to the user instead of trying again quietly. - Invalid parameters: a
400response with adetailsobject naming the field that failed. The 1080p and 10 second combination lands here. Worth logging in full during development. - Rate limits: a
429response means you have sent more requests than your plan allows in a minute. Wait and retry rather than firing straight back. - Not enough credits: a
402response. Credits come off at submission and are returned automatically if the job fails, so this only appears when your balance genuinely cannot cover the job.
Putting It Together: A Minimal FastAPI Endpoint
Here are all five steps combined into a small service with two endpoints: one to start a generation, one to check on it.
import os
import time
import requests
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
API_KEY = os.environ["APIFRAME_API_KEY"]
BASE_URL = "https://api.apiframe.ai/v2"
HEADERS = {"X-API-Key": API_KEY, "Content-Type": "application/json"}
app = FastAPI()
class GenerateRequest(BaseModel):
prompt: str
duration: int = 6
resolution: str = "768p"
@app.post("/generate")
def generate_video(req: GenerateRequest):
if req.resolution == "1080p" and req.duration == 10:
raise HTTPException(400, "1080p does not support 10 second duration")
payload = {
"prompt": req.prompt,
"model": "hailuo-02",
"hailuoParams": {"duration": req.duration, "resolution": req.resolution},
}
response = requests.post(f"{BASE_URL}/videos/generate", headers=HEADERS, json=payload)
if response.status_code == 402:
raise HTTPException(402, "Insufficient credits")
response.raise_for_status()
return response.json()
@app.get("/status/{job_id}")
def get_status(job_id: str):
response = requests.get(f"{BASE_URL}/jobs/{job_id}", headers=HEADERS)
if response.status_code == 404:
raise HTTPException(404, "Job not found")
response.raise_for_status()
return response.json()Run it with uvicorn main:app --reload, send a prompt to /generate, then have your frontend check /status/{job_id} until the status is COMPLETED. Splitting it into two endpoints like this keeps each request short, which is what you want: holding a request open for the full two to three minutes of generation will time out on most hosting platforms.
Next Steps: Choosing a Model for Text-to-Video
Hailuo 02 is a dependable place to start, but it's one of several models behind the same endpoint, each with its own trade-offs. Our AI video API guide covers how they compare, and our roundup of the best AI video generation APIs ranks them on price and quality.
- Kling: strong all-round quality, and from version 2.6 onward it can generate matching audio alongside the video.
- Seedance: the longest single clips, up to 30 seconds, with several speed tiers if you need to trade quality against cost.
- Hailuo: the best handling of human movement and facial expression, at a moderate price. Version 2.3 is the one to use if people appear in your clips.
- Wan: newer versions handle longer clips and multi-shot sequences, worth a look if one short clip isn't enough.
Because all of these sit behind the same POST /v2/videos/generate endpoint, with the same job and callback pattern, switching models means changing the model field and its matching parameters object. The authentication, status checking, and download code stays exactly as written above.
FAQ
How long does generation take?
It varies by model and settings, but most jobs land between 90 seconds and three minutes. Faster variants finish nearer 90 seconds and the heavier models closer to 180. Check every 5 to 10 seconds, or use a callback, rather than assuming a fixed wait.
Can I add image-to-video later?
Yes. Most models that do text-to-video also do image-to-video through the same endpoint, usually by adding an image URL inside the model's parameters object. Note that the field name differs between model families, so check the reference page rather than assuming. The authentication, status checking, and download code stays the same, and our image-to-video Python tutorial covers that path in full.
What happens if my prompt gets rejected?
You'll get a FAILED job status with an error message explaining the rejection, most often a content policy violation. Credits spent on a failed job are returned automatically, so trying again with a reworded prompt doesn't cost you twice.
Do I need to handle video storage myself?
For anything you want to keep beyond the provider's retention window (90 days on Apiframe), yes. Download the file and store it yourself rather than relying on the hosted link.
What does one video cost?
It depends heavily on the model. A 6 second Hailuo 02 clip at 768p is 39 credits ($0.39), while a 5 second Kling 3.0 pro clip with audio is closer to $2.45. The gap between the cheapest and most expensive option is large enough that your default model choice matters more than any other cost decision. Our AI video API pricing guide has the full breakdown.