AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How to Integrate the Kling AI API: Programmatic Video Generation and Status Polling

Ana Lázaro Touza · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Relying on the browser dashboard to produce AI video works well for creative discovery and manual prompting. It collapses completely when an engineering team needs to generate hundreds of localized ad variations, power dynamic e-commerce product videos, or build an AI video SaaS. Browser workflows introduce human-in-the-loop latency, zero batch concurrency, and disconnected media assets.

Automating video creation demands direct integration with the Kling AI Open Platform REST API. Because multi-second diffusion video generation is compute-intensive, Kling AI does not deliver rendered video synchronously over a single HTTP connection. It operates as an asynchronous distributed job queue.

At 365Finds, our architectural stance is clear: treat Kling AI as an asynchronous remote rendering cluster. A resilient production integration requires three architectural pillars:

  1. Dynamic JWT or API key authentication with token caching.
  2. A dual-track fulfillment model using Webhook callbacks for high throughput, backed by defensive exponential polling for resilience.
  3. An automated asset persistence pipeline that offloads videos to private cloud storage before Kling AI's 24-hour CDN links expire.

This guide provides software engineers with the complete technical blueprints, request payloads, and battle-tested code patterns required to integrate Kling AI into backend services.


1. Authentication and Gateway Selection

Kling AI routes developer traffic through regional gateways. Selecting the correct base URL and managing authentication headers is the first step in constructing an enterprise client.

Gateway Endpoints

Authentication Schemes: Bearer API Key vs. Signed JWT

Kling AI supports two authentication mechanisms depending on how your developer credentials are provisioned:

  1. Direct API Key: An explicit secret key generated from the developer console, passed directly in the HTTP header:
    Authorization: Bearer <YOUR_API_KEY>
    
  2. Access Key (AK) / Secret Key (SK) with HMAC-SHA256 JWT: Kling AI's native enterprise protocol uses an Access Key and Secret Key to sign a short-lived JSON Web Token (RFC 7519) using the HS256 algorithm.

Dynamic JWT Payload Structure

When using the AK/SK pair, your service must sign a token with the following claims:

[!IMPORTANT] Do not generate a fresh JWT for every HTTP request. Generating cryptographic signatures on every call creates unnecessary CPU overhead. Cache the signed JWT in memory for 25 minutes, refresh it automatically 5 minutes before expiration, and attach it to your HTTP client session.

Python Token Manager Implementation

import time
import jwt

class KlingAuthManager:
    """Manages cached JWT generation for Kling AI AccessKey/SecretKey authentication."""
    def __init__(self, access_key: str, secret_key: str, ttl_seconds: int = 1800):
        self.access_key = access_key
        self.secret_key = secret_key
        self.ttl_seconds = ttl_seconds
        self._cached_token = None
        self._expires_at = 0

    def get_token(self) -> str:
        current_time = int(time.time())
        # Refresh if token has expired or is within 300 seconds of expiring
        if not self._cached_token or current_time >= (self._expires_at - 300):
            self._cached_token = self._generate_token(current_time)
            self._expires_at = current_time + self.ttl_seconds
        return self._cached_token

    def _generate_token(self, current_time: int) -> str:
        headers = {"alg": "HS256", "typ": "JWT"}
        payload = {
            "iss": self.access_key,
            "exp": current_time + self.ttl_seconds,
            "nbf": current_time - 5,
        }
        return jwt.encode(payload, self.secret_key, algorithm="HS256", headers=headers)

    def get_headers(self) -> dict:
        return {
            "Authorization": f"Bearer {self.get_token()}",
            "Content-Type": "application/json",
        }

2. Dispatching Video Generation Tasks: Text-to-Video and Image-to-Video

Kling AI exposes dedicated REST endpoints to trigger video rendering tasks. Each submission triggers an asynchronous process on the model cluster and immediately returns an operational task_id.

Text-to-Video (POST /v1/videos/text2video)

Text-to-Video accepts natural language descriptions, camera instructions, aspect ratios, and quality tier parameters.

Request Parameters

Text-to-Video Payload Example

{
  "model_name": "kling-v1-6",
  "prompt": "Cinematic wide drone shot of an electric sports car driving along a coastal highway at golden hour, dynamic lighting, 4k photorealistic",
  "negative_prompt": "cartoon, oversaturated, blurry, flickering, jittery motion",
  "duration": "5",
  "mode": "std",
  "aspect_ratio": "16:9",
  "cfg_scale": 0.5,
  "callback_url": "https://api.yourdomain.com/webhooks/kling",
  "external_task_id": "job_order_8849102"
}

Image-to-Video (POST /v1/videos/image2video)

Image-to-Video animates a provided start frame. Optionally, you can pass an end frame (image_tail) to constrain the final output state.

Additional Parameters

Image-to-Video Payload Example

{
  "model_name": "kling-v1-6",
  "image": "https://assets.yourdomain.com/keyframes/product_hero_01.jpg",
  "prompt": "Camera smoothly pans right around the luxury bottle, studio lighting reflections shimmering across the glass surface",
  "negative_prompt": "deformed geometry, jerky movement, artifacts",
  "duration": "5",
  "mode": "pro",
  "aspect_ratio": "16:9",
  "callback_url": "https://api.yourdomain.com/webhooks/kling",
  "external_task_id": "job_order_8849103"
}

Initial Synchronous API Response

Both endpoints return an HTTP 200 payload confirming task ingestion:

{
  "code": 0,
  "message": "success",
  "request_id": "req_9f3b817e04",
  "data": {
    "task_id": "893605946402811985",
    "task_status": "submitted",
    "created_at": 1730526340000,
    "updated_at": 1730526340000
  }
}

3. The Task Status Lifecycle

Once dispatched, a Kling AI video task passes through four primary states:

[ submitted ] ──> [ processing ] ──┬──> [ succeed ]  (Contains temporary MP4 CDN URLs)
                                   └──> [ failed ]   (Contains task_status_msg error)
StateStatus NameDescriptionRecommended System Action
submittedSubmittedTask received and queued in GPU scheduler.Wait; do not hammer polling endpoints.
processingProcessingDiffusion model is actively rendering frames.Maintain steady polling or await Webhook.
succeedSucceededRendering completed; output video available.Extract MP4 URL; immediately transfer to private storage.
failedFailedGeneration aborted due to prompt violation or system fault.Parse task_status_msg; alert or trigger fallback.

When querying task status via GET /v1/videos/text2video/{task_id} or GET /v1/videos/image2video/{task_id}, a successful task returns:

{
  "code": 0,
  "message": "success",
  "request_id": "req_88a91c5e",
  "data": {
    "task_id": "893605946402811985",
    "task_status": "succeed",
    "task_status_msg": "",
    "created_at": 1730526340000,
    "updated_at": 1730526378000,
    "task_result": {
      "videos": [
        {
          "id": "vid_20261102_01",
          "url": "https://p2-kling.klingai.com/output/893605946402811985.mp4",
          "duration": "5"
        }
      ]
    }
  }
}

If the task fails (e.g., triggering automated content moderation filters), the response reports:

{
  "code": 0,
  "message": "success",
  "data": {
    "task_id": "893605946402811985",
    "task_status": "failed",
    "task_status_msg": "Input prompt violates content safety policies."
  }
}

4. Designing a Resilient Task Polling Architecture

Software teams frequently make two mistakes when building status checkers:

  1. Aggressive Polling: Polling every 500 milliseconds. Video generation takes 20 to 90 seconds depending on server load and quality mode. Rapid polling exhausts API rate limits, risks HTTP 429 errors, and wastes socket resources.
  2. Synchronous Blocking: Blocking HTTP threads while polling, consuming application server worker pools.

The 365Finds Polling Blueprint: Silent Sleep + Exponential Backoff with Jitter

For environments where Webhooks are impractical (e.g., local test runners, internal VPCs without public ingress, or synchronous CLI tools), implement a phased polling loop:

  1. Initial Silent Window: Sleep for 15 seconds before issuing the first status request. No Kling AI video finishes within 15 seconds.
  2. Backoff Loop: Poll with an expanding interval: 5 seconds, 8 seconds, 12 seconds, capped at 15 seconds.
  3. Random Jitter: Add a random floating-point variation (0.5 to 1.5 seconds) to prevent synchronized request thundering across concurrent batch workers.
  4. Hard Timeout: Abort with a descriptive error if the task remains incomplete after 360 seconds (6 minutes).
import time
import random
import requests
import logging

logger = logging.getLogger(__name__)

class KlingPollingClient:
    def __init__(self, auth_manager: KlingAuthManager, base_url: str = "https://api-singapore.klingai.com"):
        self.auth_manager = auth_manager
        self.base_url = base_url.rstrip("/")

    def poll_video_task(self, task_id: str, task_type: str = "text2video", max_timeout: int = 360) -> dict:
        """
        Polls a Kling AI task using initial silent delay followed by exponential backoff.
        task_type: 'text2video' or 'image2video'
        """
        endpoint = f"{self.base_url}/v1/videos/{task_type}/{task_id}"
        start_time = time.time()
        
        # Step 1: Initial silent window
        logger.info(f"Task {task_id} dispatched. Entering initial 15s quiet phase...")
        time.sleep(15)

        poll_interval = 5.0
        max_interval = 15.0

        while time.time() - start_time < max_timeout:
            headers = self.auth_manager.get_headers()
            try:
                response = requests.get(endpoint, headers=headers, timeout=15)
                response.raise_for_status()
                body = response.json()
            except requests.RequestException as e:
                logger.warning(f"Transient network error polling task {task_id}: {e}. Retrying...")
                time.sleep(5)
                continue

            if body.get("code") != 0:
                raise RuntimeError(f"API Error {body.get('code')}: {body.get('message')}")

            data = body.get("data", {})
            status = data.get("task_status")

            if status == "succeed":
                logger.info(f"Task {task_id} succeeded in {int(time.time() - start_time)}s.")
                return data
            elif status == "failed":
                reason = data.get("task_status_msg", "Unknown error")
                raise RuntimeError(f"Video generation task {task_id} failed: {reason}")
            elif status in ("submitted", "processing"):
                jitter = random.uniform(0.5, 1.5)
                sleep_time = min(poll_interval + jitter, max_interval)
                logger.debug(f"Task {task_id} status: {status}. Sleeping {sleep_time:.1f}s...")
                time.sleep(sleep_time)
                poll_interval = min(poll_interval * 1.3, max_interval)
            else:
                logger.warning(f"Encountered unexpected status: {status}")
                time.sleep(5)

        raise TimeoutError(f"Task {task_id} timed out after {max_timeout} seconds.")

5. Enterprise Webhooks vs. Polling: The Dual-Track Strategy

For production microservices processing thousands of video jobs daily, running long-lived polling threads in Celery or temporal workers is inefficient. Webhooks transform the workflow into a truly event-driven pipeline.

Webhook Delivery Mechanism

When you pass "callback_url": "https://api.yourdomain.com/webhooks/kling" during task dispatch, Kling AI fires an HTTP POST request to that address the moment rendering reaches a terminal state (succeed or failed).

Sample Webhook Payload

{
  "code": 0,
  "message": "success",
  "request_id": "req_cb_102837",
  "data": {
    "task_id": "893605946402811985",
    "task_status": "succeed",
    "task_status_msg": "",
    "created_at": 1730526340000,
    "updated_at": 1730526378000,
    "task_result": {
      "videos": [
        {
          "id": "vid_01",
          "url": "https://p2-kling.klingai.com/output/893605946402811985.mp4",
          "duration": "5"
        }
      ]
    }
  }
}

The 365Finds Production Recommendation: Hybrid Dual-Track

Relying 100% on Webhooks introduces a single point of failure: dropped packets, DNS resolution blips, or ingress firewall timeouts will leave video tasks permanently marked as "pending" in your database.

The Solution:

  1. Primary Track (Webhook): Fast-path fulfillment. Ingest the webhook payload, acknowledge HTTP 200 within 200ms, and queue an internal background job to persist the media.
  2. Secondary Track (Reconciliation Sweep): A scheduled Cron job checks all database tasks that have stayed in submitted or processing for more than 180 seconds. It makes a single GET /v1/videos/text2video/{task_id} call to reconcile missing webhook events.

6. The 24-Hour Expiration Trap: Automated Asset Persistence

A critical engineering detail often overlooked in initial POCs is asset longevity:

[!WARNING] Kling AI video download URLs are temporary CDN links. They expire and become inaccessible within approximately 24 hours. Never store raw klingai.com URLs in your production databases or return them to front-end clients.

Your backend service must immediately stream the finished MP4 file directly into your own private object storage (e.g., Amazon S3, Cloudflare R2, Google Cloud Storage, or Aliyun OSS).

High-Efficiency Stream-and-Upload Pipeline

Rather than buffering multi-megabyte video files completely into server RAM, stream bytes directly through an in-memory buffer or chunked multipart upload:

import io
import requests
import boto3
import logging

logger = logging.getLogger(__name__)

def persist_kling_video_to_s3(
    kling_video_url: str,
    s3_bucket: str,
    s3_key: str,
    aws_region: str = "us-east-1"
) -> str:
    """
    Streams generated MP4 directly from Kling AI CDN to an Amazon S3 bucket.
    Avoids writing to local disk, making it ideal for containerized workers.
    """
    s3_client = boto3.client("s3", region_name=aws_region)
    logger.info(f"Streaming video from Kling CDN to s3://{s3_bucket}/{s3_key}...")

    # Stream download with response context manager
    with requests.get(kling_video_url, stream=True, timeout=60) as r:
        r.raise_for_status()
        content_type = r.headers.get("Content-Type", "video/mp4")
        
        # Upload stream to S3 using upload_fileobj
        s3_client.upload_fileobj(
            Fileobj=r.raw,
            Bucket=s3_bucket,
            Key=s3_key,
            ExtraArgs={"ContentType": content_type}
        )

    permanent_url = f"https://{s3_bucket}.s3.{aws_region}.amazonaws.com/{s3_key}"
    logger.info(f"Video safely persisted: {permanent_url}")
    return permanent_url

7. Complete End-to-End Integration Pipeline

Below is a complete, runnable Python integration combining JWT authentication, task creation, resilient polling, and asset persistence.

import os
import time
import requests
from kling_auth import KlingAuthManager  # Defined in Section 1

class KlingAIClient:
    def __init__(self, access_key: str, secret_key: str, base_url: str = "https://api-singapore.klingai.com"):
        self.auth = KlingAuthManager(access_key, secret_key)
        self.base_url = base_url.rstrip("/")

    def create_text_to_video(self, prompt: str, duration: int = 5, mode: str = "std", aspect_ratio: str = "16:9") -> str:
        url = f"{self.base_url}/v1/videos/text2video"
        payload = {
            "model_name": "kling-v1-6",
            "prompt": prompt,
            "duration": str(duration),
            "mode": mode,
            "aspect_ratio": aspect_ratio,
        }
        response = requests.post(url, json=payload, headers=self.auth.get_headers(), timeout=15)
        response.raise_for_status()
        data = response.json()
        if data.get("code") != 0:
            raise RuntimeError(f"Submission failed: {data.get('message')}")
        return data["data"]["task_id"]

    def create_image_to_video(self, image_url: str, prompt: str, duration: int = 5, mode: str = "std") -> str:
        url = f"{self.base_url}/v1/videos/image2video"
        payload = {
            "model_name": "kling-v1-6",
            "image": image_url,
            "prompt": prompt,
            "duration": str(duration),
            "mode": mode,
        }
        response = requests.post(url, json=payload, headers=self.auth.get_headers(), timeout=15)
        response.raise_for_status()
        data = response.json()
        if data.get("code") != 0:
            raise RuntimeError(f"Submission failed: {data.get('message')}")
        return data["data"]["task_id"]

    def wait_for_video(self, task_id: str, task_type: str = "text2video", timeout: int = 360) -> str:
        endpoint = f"{self.base_url}/v1/videos/{task_type}/{task_id}"
        time.sleep(15)  # Quiet period
        start = time.time()
        interval = 5.0

        while time.time() - start < timeout:
            res = requests.get(endpoint, headers=self.auth.get_headers(), timeout=15)
            res.raise_for_status()
            res_json = res.json()
            data = res_json.get("data", {})
            status = data.get("task_status")

            if status == "succeed":
                videos = data.get("task_result", {}).get("videos", [])
                if not videos:
                    raise RuntimeError("Status is succeed but video list is empty.")
                return videos[0]["url"]
            elif status == "failed":
                raise RuntimeError(f"Task failed: {data.get('task_status_msg')}")

            time.sleep(interval)
            interval = min(interval * 1.2, 15.0)

        raise TimeoutError("Task polling exceeded maximum timeout.")

# Execution Pipeline Demonstration
if __name__ == "__main__":
    AK = os.getenv("KLING_ACCESS_KEY", "your_ak_here")
    SK = os.getenv("KLING_SECRET_KEY", "your_sk_here")
    
    client = KlingAIClient(AK, SK)
    
    # 1. Trigger Generation
    prompt_text = "Macro close-up of a raindrop falling on an autumn leaf in slow motion, photorealistic 8k"
    print("Submitting Text-to-Video task to Kling AI...")
    task_id = client.create_text_to_video(prompt_text, duration=5, mode="std")
    print(f"Task successfully queued. Task ID: {task_id}")
    
    # 2. Poll for Completion
    print("Awaiting video render...")
    temporary_cdn_url = client.wait_for_video(task_id, task_type="text2video")
    print(f"Render completed! Temporary CDN URL: {temporary_cdn_url}")
    
    # 3. Offload to S3
    # permanent_url = persist_kling_video_to_s3(temporary_cdn_url, "my-company-assets", f"videos/{task_id}.mp4")

8. Integration Architecture Comparison

Architecture PatternLatency ProfileInfrastructure OverheadReliability & RecoveryRecommended Use Case
Pure Polling (Linear)Moderate to High; constant CPU cyclesZero ingress setup required; worker-heavyHigh network overhead; risks HTTP 429 rate limitsCLI tools, localized scripts, dev environments
Pure WebhookLowest; instant event dispatchIngress gateway, public IP, and SSL requiredVulnerable to lost events during network dropsSimple serverless apps with no persistent tracking
Hybrid (Webhook + Sweep)Optimal latency; minimal idle computeModerate (webhook receiver + cron worker)Industry best-in-class; self-healing against network dropsEnterprise SaaS, automated ad pipelines, batch renderers

9. Integration Checklist for Production

Before rolling your Kling AI integration to production, verify that your service complies with these operational requirements:

References