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:
- Dynamic JWT or API key authentication with token caching.
- A dual-track fulfillment model using Webhook callbacks for high throughput, backed by defensive exponential polling for resilience.
- 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
- Global / International Gateway:
https://api-singapore.klingai.com(recommended for services deployed outside mainland China). - Mainland China Gateway:
https://api.klingai.com.
Authentication Schemes: Bearer API Key vs. Signed JWT
Kling AI supports two authentication mechanisms depending on how your developer credentials are provisioned:
- Direct API Key: An explicit secret key generated from the developer console, passed directly in the HTTP header:
Authorization: Bearer <YOUR_API_KEY> - 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
HS256algorithm.
Dynamic JWT Payload Structure
When using the AK/SK pair, your service must sign a token with the following claims:
iss(Issuer): Your Kling AI Access Key.exp(Expiration Time): Current Unix timestamp + TTL (e.g., 1800 seconds / 30 minutes).nbf(Not Before): Current Unix timestamp - 5 seconds (to compensate for distributed clock skew).
[!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
model_name(String, Required): Model version (e.g.,"kling-v1","kling-v1-5","kling-v1-6","kling-v3").prompt(String, Required): Textual description of scene, characters, and movement (up to 2,500 characters).negative_prompt(String, Optional): Visual elements to exclude (e.g.,"blurry, low quality, distorted, extra limbs").duration(String/Int, Required): Duration of generated clip in seconds ("5"or"10").mode(String, Optional): Quality tier."std": Standard mode. High rendering velocity, lower cost. Ideal for high-volume programmatic generation, creative A/B testing, and social drafts."pro": Professional mode. High visual fidelity, refined lighting coherence, and higher credit consumption.
aspect_ratio(String, Optional): Output aspect ratio:"16:9","9:16", or"1:1".cfg_scale(Float, Optional): Prompt adherence weighting, ranging from0.0to1.0(default:0.5).callback_url(String, Optional): Public HTTPS endpoint on your backend to receive webhook completion notifications.external_task_id(String, Optional): Unique business identifier from your system for idempotency and correlation.
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(String, Required): Publicly accessible HTTPS URL or Base64 string of the starting image frame.image_tail(String, Optional): Public HTTPS URL or Base64 string for the destination frame (supported in"pro"mode).camera_control(Object, Optional): Configuration object for parameterized camera trajectories (pan, tilt, zoom).
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)
| State | Status Name | Description | Recommended System Action |
|---|---|---|---|
submitted | Submitted | Task received and queued in GPU scheduler. | Wait; do not hammer polling endpoints. |
processing | Processing | Diffusion model is actively rendering frames. | Maintain steady polling or await Webhook. |
succeed | Succeeded | Rendering completed; output video available. | Extract MP4 URL; immediately transfer to private storage. |
failed | Failed | Generation 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:
- 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.
- 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:
- Initial Silent Window: Sleep for 15 seconds before issuing the first status request. No Kling AI video finishes within 15 seconds.
- Backoff Loop: Poll with an expanding interval: 5 seconds, 8 seconds, 12 seconds, capped at 15 seconds.
- Random Jitter: Add a random floating-point variation (0.5 to 1.5 seconds) to prevent synchronized request thundering across concurrent batch workers.
- 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:
- 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.
- Secondary Track (Reconciliation Sweep): A scheduled Cron job checks all database tasks that have stayed in
submittedorprocessingfor more than 180 seconds. It makes a singleGET /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.comURLs 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 Pattern | Latency Profile | Infrastructure Overhead | Reliability & Recovery | Recommended Use Case |
|---|---|---|---|---|
| Pure Polling (Linear) | Moderate to High; constant CPU cycles | Zero ingress setup required; worker-heavy | High network overhead; risks HTTP 429 rate limits | CLI tools, localized scripts, dev environments |
| Pure Webhook | Lowest; instant event dispatch | Ingress gateway, public IP, and SSL required | Vulnerable to lost events during network drops | Simple serverless apps with no persistent tracking |
| Hybrid (Webhook + Sweep) | Optimal latency; minimal idle compute | Moderate (webhook receiver + cron worker) | Industry best-in-class; self-healing against network drops | Enterprise 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:
- Token Expiration Buffer: JWT generation logic must refresh tokens 3 to 5 minutes prior to expiration.
- Initial Quiet Window: Polling services must sleep for at least 15 seconds before issuing the first query.
- Rate Limiting Guardrails: Backoff schedules must prevent exceeding gateway request thresholds.
- Asset Transfer Queue: Output videos must be streamed to persistent S3/GCS buckets immediately upon receiving status
succeed. - Content Safety Fallbacks: Application logic must cleanly capture
task_status == 'failed'and surface actionable prompts or fallback assets without crashing worker threads. - Regional Routing: All API requests originating outside mainland China must target
https://api-singapore.klingai.com.