Login
Back to Blog
EnglishTutorial

Kling AI API Tutorial: Build AI Video Generation into Your App

"Step-by-step tutorial on using Kling AI API for text-to-video and image-to-video generation. Python code examples, pricing, and production tips."

C
Crazyrouter Team
February 21, 2026 / 1035 views
Share:
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:

python
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#

python
# 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:

python
# 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#

python
# 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#

bash
# 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#

ParameterTypeRequiredOptionsDescription
promptstringYesText description of the video
image_urlstringNoSource image for image-to-video
durationintegerNo5, 10Video duration in seconds
modestringNostandard, professionalQuality mode
aspect_ratiostringNo16:9, 9:16, 1:1Output aspect ratio
negative_promptstringNoWhat to avoid in the video

Mode Comparison#

FeatureStandardProfessional
QualityGoodBest
Speed~2 min~5 min
Cost1x2x
Best ForDrafts, testingFinal output

Prompt Engineering for Kling#

Effective Prompt Structure#

code
[Subject] + [Action] + [Setting] + [Camera] + [Style]

Good prompts:

code
"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:

  1. Describe specific actions, not just scenes
  2. Include camera movement (tracking, dolly, static, aerial)
  3. Mention lighting conditions
  4. Add style keywords (cinematic, documentary, anime)
  5. Use negative prompts to avoid unwanted elements

Pricing#

PlanCost per 5s VideoCost per 10s VideoMode
Kling FreeFree (limited)Free (limited)Standard
Kling Pro ($8/mo)~$0.05~$0.10Standard
Kling Premium ($66/mo)~$0.03~$0.06Professional
Crazyrouter API~$0.08~$0.15Both

Through Crazyrouter, you get pay-as-you-go pricing without monthly commitments — ideal for variable workloads and testing.

Building a Production Video Pipeline#

python
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#

FeatureKling AIRunway Gen-3HailuoSora
Human Motion⭐ ExcellentVery Good⭐ ExcellentVery Good
PhotorealismVery Good⭐ ExcellentVery Good⭐ Excellent
Max Duration10s10s6s60s
Image-to-Video⭐ ExcellentGoodGoodGood
Lip Sync⭐ Built-in
API AccessLimited
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.

Implementation Guides

Related Posts

Pika 2.2 API Integration Guide: Build Video Generation Pipelines in 2026Tutorial

Pika 2.2 API Integration Guide: Build Video Generation Pipelines in 2026

"Step-by-step guide to integrating Pika 2.2's API into production video pipelines. Covers text-to-video, image-to-video, effects, pricing, and multi-model fallback strategies."

Apr 13
AI Face Reading & Personal Color Analysis with GPT-image-2 — Two Viral Use Cases in One GuideTutorial

AI Face Reading & Personal Color Analysis with GPT-image-2 — Two Viral Use Cases in One Guide

Build AI face reading and personal color season analysis tools using GPT-image-2 via Crazyrouter API. Full Python, curl, and Node.js code.

May 1
WAN 2.2 Animate Tutorial for Developers: API Workflows and Production TipsTutorial

WAN 2.2 Animate Tutorial for Developers: API Workflows and Production Tips

A developer-focused WAN 2.2 Animate tutorial covering what it is, how it compares to alternatives, and how to build video generation workflows with Crazyrouter.

Mar 15
Claude API Key: Complete Setup, Security, and Troubleshooting GuideTutorial

Claude API Key: Complete Setup, Security, and Troubleshooting Guide

One wrong header format can turn every Claude request into a 401 “Invalid API key” error in seconds. Most teams assume **claude api key** issues start at the model layer, but the real breakpoints u...

Mar 18
Flux AI Image Generation Guide 2026: Models, API & TutorialTutorial

Flux AI Image Generation Guide 2026: Models, API & Tutorial

"Complete guide to Flux AI image generation models in 2026. Learn about Flux Pro, Dev, Schnell models, API integration, and how to generate stunning images."

Mar 1
Model Distillation Explained: How Small AI Models Learn from GiantsTutorial

Model Distillation Explained: How Small AI Models Learn from Giants

"A complete guide to knowledge distillation in AI. Learn how DeepSeek, GPT-4o-mini, Gemini Flash, and Claude Haiku were built by distilling larger models, and how developers can use distillation to cut costs."

Mar 30