
"Kling AI API Tutorial: Build AI Video Generation into Your App"
What Is Kling AI?#
Kling AI is a video generation platform developed by Kuaishou (the company behind Kwai). It's become one of the most popular AI video generators thanks to its exceptional handling of human motion, facial expressions, and realistic physics.
For developers, Kling offers a REST API that enables:
- Text-to-video — generate videos from text descriptions
- Image-to-video — animate static images with motion
- Video extension — extend existing clips
- Lip sync — synchronize mouth movements with audio
- Multiple resolutions — 720p and 1080p output
- Duration control — 5 or 10 second clips
Getting Started#
API Access Through Crazyrouter#
The easiest way to access Kling AI's API is through Crazyrouter, which provides a unified endpoint for Kling alongside 300+ other AI models:
import requests
import time
API_KEY = "your-crazyrouter-key"
BASE_URL = "https://api.crazyrouter.com"
HEADERS = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
Text-to-Video Generation#
# Generate a video from text
response = requests.post(
f"{BASE_URL}/kling/submit/video",
headers=HEADERS,
json={
"prompt": "A barista carefully pouring latte art in a cozy coffee shop, warm morning light streaming through the window, close-up shot",
"duration": 5,
"mode": "standard", # "standard" or "professional"
"aspect_ratio": "16:9"
}
)
task = response.json()
task_id = task["data"]["task_id"]
print(f"Task ID: {task_id}")
# Wait for completion
def wait_for_video(task_id, max_wait=300):
start = time.time()
while time.time() - start < max_wait:
result = requests.get(
f"{BASE_URL}/kling/fetch/{task_id}",
headers=HEADERS
).json()
status = result["data"]["status"]
if status == "completed":
return result["data"]
elif status == "failed":
raise Exception(f"Failed: {result['data'].get('error')}")
print(f" Status: {status}")
time.sleep(10)
raise TimeoutError("Video generation timed out")
result = wait_for_video(task_id)
print(f"Video URL: {result['video_url']}")
Image-to-Video Generation#
Animate a static image — one of Kling's strongest features:
# Animate a product photo
response = requests.post(
f"{BASE_URL}/kling/submit/video",
headers=HEADERS,
json={
"prompt": "The person slowly smiles and turns their head to the right, hair gently moving in the breeze",
"image_url": "https://example.com/portrait.jpg",
"duration": 5,
"mode": "professional",
"aspect_ratio": "9:16" # Portrait for social media
}
)
Lip Sync Video#
# Generate a lip-synced video
response = requests.post(
f"{BASE_URL}/kling/submit/lip-sync",
headers=HEADERS,
json={
"video_url": "https://example.com/talking-head.mp4",
"audio_url": "https://example.com/speech.mp3"
}
)
cURL Examples#
# Text-to-video
curl -X POST https://api.crazyrouter.com/kling/submit/video \
-H "Authorization: Bearer your-crazyrouter-key" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Ocean waves crashing on a rocky shore at sunset, drone shot, 4K cinematic",
"duration": 5,
"mode": "professional",
"aspect_ratio": "16:9"
}'
# Check status
curl https://api.crazyrouter.com/kling/fetch/TASK_ID \
-H "Authorization: Bearer your-crazyrouter-key"
API Parameters Reference#
Video Generation#
| Parameter | Type | Required | Options | Description |
|---|---|---|---|---|
prompt | string | Yes | — | Text description of the video |
image_url | string | No | — | Source image for image-to-video |
duration | integer | No | 5, 10 | Video duration in seconds |
mode | string | No | standard, professional | Quality mode |
aspect_ratio | string | No | 16:9, 9:16, 1:1 | Output aspect ratio |
negative_prompt | string | No | — | What to avoid in the video |
Mode Comparison#
| Feature | Standard | Professional |
|---|---|---|
| Quality | Good | Best |
| Speed | ~2 min | ~5 min |
| Cost | 1x | 2x |
| Best For | Drafts, testing | Final output |
Prompt Engineering for Kling#
Effective Prompt Structure#
[Subject] + [Action] + [Setting] + [Camera] + [Style]
Good prompts:
"A chef flipping a pancake in a modern kitchen, medium shot, warm lighting, slow motion"
"Two friends laughing while walking through autumn leaves in a park, tracking shot, golden hour, cinematic"
"A cat stretching and yawning on a windowsill, close-up, soft natural light, cozy atmosphere"
Tips for better results:
- Describe specific actions, not just scenes
- Include camera movement (tracking, dolly, static, aerial)
- Mention lighting conditions
- Add style keywords (cinematic, documentary, anime)
- Use negative prompts to avoid unwanted elements
Pricing#
| Plan | Cost per 5s Video | Cost per 10s Video | Mode |
|---|---|---|---|
| Kling Free | Free (limited) | Free (limited) | Standard |
| Kling Pro ($8/mo) | ~$0.05 | ~$0.10 | Standard |
| Kling Premium ($66/mo) | ~$0.03 | ~$0.06 | Professional |
| Crazyrouter API | ~$0.08 | ~$0.15 | Both |
Through Crazyrouter, you get pay-as-you-go pricing without monthly commitments — ideal for variable workloads and testing.
Building a Production Video Pipeline#
class KlingVideoClient:
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = "https://api.crazyrouter.com"
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
def generate_video(self, prompt: str, duration: int = 5,
mode: str = "standard", image_url: str = None,
aspect_ratio: str = "16:9") -> dict:
"""Generate a video and wait for completion."""
payload = {
"prompt": prompt,
"duration": duration,
"mode": mode,
"aspect_ratio": aspect_ratio
}
if image_url:
payload["image_url"] = image_url
response = requests.post(
f"{self.base_url}/kling/submit/video",
headers=self.headers,
json=payload
)
response.raise_for_status()
task_id = response.json()["data"]["task_id"]
# Poll for result
for _ in range(60): # Max 10 minutes
result = requests.get(
f"{self.base_url}/kling/fetch/{task_id}",
headers=self.headers
).json()
if result["data"]["status"] == "completed":
return result["data"]
elif result["data"]["status"] == "failed":
raise Exception(result["data"].get("error", "Unknown error"))
time.sleep(10)
raise TimeoutError("Generation timed out")
def batch_generate(self, prompts: list, **kwargs) -> list:
"""Generate multiple videos concurrently."""
import concurrent.futures
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
futures = {
executor.submit(self.generate_video, prompt, **kwargs): prompt
for prompt in prompts
}
results = []
for future in concurrent.futures.as_completed(futures):
try:
result = future.result()
results.append({"prompt": futures[future], "result": result})
except Exception as e:
results.append({"prompt": futures[future], "error": str(e)})
return results
# Usage
kling = KlingVideoClient("your-crazyrouter-key")
# Single video
video = kling.generate_video(
"A time-lapse of a flower blooming, macro shot, studio lighting",
duration=5,
mode="professional"
)
print(f"Video: {video['video_url']}")
# Batch generation
prompts = [
"Sunrise over mountains, aerial drone shot",
"Rain falling on a city street at night, neon reflections",
"A butterfly landing on a flower, macro, slow motion"
]
results = kling.batch_generate(prompts, duration=5)
for r in results:
print(f"{r['prompt'][:50]}... → {r.get('result', {}).get('video_url', r.get('error'))}")
Kling vs Competitors#
| Feature | Kling AI | Runway Gen-3 | Hailuo | Sora |
|---|---|---|---|---|
| Human Motion | ⭐ Excellent | Very Good | ⭐ Excellent | Very Good |
| Photorealism | Very Good | ⭐ Excellent | Very Good | ⭐ Excellent |
| Max Duration | 10s | 10s | 6s | 60s |
| Image-to-Video | ⭐ Excellent | Good | Good | Good |
| Lip Sync | ⭐ Built-in | ❌ | ❌ | ❌ |
| API Access | ✅ | ✅ | ✅ | Limited |
| Price | $$ | $$$ | $$ | $$$$ |
FAQ#
Is Kling AI API free?#
Kling offers a free tier with limited daily credits. For API access with higher limits and professional mode, you'll need a paid plan or use an API provider like Crazyrouter with pay-as-you-go pricing.
How long does Kling video generation take?#
Standard mode: 1-3 minutes. Professional mode: 3-7 minutes. Times vary based on server load and video complexity.
Can Kling generate videos with audio?#
Kling generates silent video by default. For audio, you can use the lip sync feature to add speech, or combine with a separate audio generation tool (like Suno for music).
What resolution does Kling output?#
Standard mode outputs 720p, professional mode outputs up to 1080p. The aspect ratio can be 16:9, 9:16, or 1:1.
Can I use Kling-generated videos commercially?#
Yes, with Kling's paid plans and through API providers like Crazyrouter, generated videos can be used commercially. Check the latest terms for specific restrictions.
Summary#
Kling AI offers one of the best balances of quality, features, and pricing in the AI video generation space. Its standout capabilities in human motion, image-to-video, and built-in lip sync make it a strong choice for developers building video-centric applications.
Get started with Kling AI and 300+ other models at crazyrouter.com — one API key, pay-as-you-go, no subscriptions required.


