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 / 548 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

Qwen2.5 Omni API Guide 2026: Multimodal Development TutorialTutorial

Qwen2.5 Omni API Guide 2026: Multimodal Development Tutorial

A developer guide to Qwen2.5 Omni in 2026, covering what it is, how it compares with multimodal alternatives, code examples, pricing considerations, and production tips.

Mar 17
How to Build an AI-Powered Discord Bot with Multiple LLMsTutorial

How to Build an AI-Powered Discord Bot with Multiple LLMs

Complete guide to building a Discord bot that uses GPT-5, Claude, Gemini, and other AI models. Includes code examples, best practices, and cost optimization strategies.

Mar 12
CTutorial

Claude Code Pricing Guide 2026: Team Agent Budgets, API Fallbacks, and Cost Control

If you searched for **claude code pricing**, you probably do not need another shallow feature list. You need to know what Claude Code is, how it compares with alternatives, how to use it in a develope...

May 26
OpenClaw Architecture: How OpenClaw Works Under the Hood in 2026Tutorial

OpenClaw Architecture: How OpenClaw Works Under the Hood in 2026

A technical deep dive into OpenClaw architecture exploring the Gateway layer, Agent Runtime, Markdown-based memory system, plugin slots, and complete message lifecycle. Learn how OpenClaw processes AI assistant requests from send to reply.

Mar 7
AI Image API Playground: Test GPT Image, Imagen, Qwen Image and FLUX OnlineTutorial

AI Image API Playground: Test GPT Image, Imagen, Qwen Image and FLUX Online

A practical guide for developers who need to compare AI image generation models before building production code. Learn how to test GPT Image, Imagen, Qwen Image, FLUX, and DALL-E style workflows from one playground and one API key.

Jun 4
How to Get a Claude API Key in 2026: Official Setup, Alternatives, and Tested ExamplesTutorial

How to Get a Claude API Key in 2026: Official Setup, Alternatives, and Tested Examples

"Learn how to get a Claude API key in 2026 from Anthropic or through Crazyrouter. Includes official setup steps, tested API examples, common problems, and a direct-vs-gateway comparison."

Mar 15