Kling AI Text to Video Generation API Documentation

The Kling AI Text to Video Generation API Docs offers detailed instructions to convert text prompts into high-quality videos. Configure parameters like style, resolution, and duration with precision. The API supports real-time rendering, batch processing, and seamless integration for efficient video automation. Tailored for developers, it simplifies the creation of dynamic, customizable videos, perfect for marketing, education, and creative applications.

Authentication:

To use this API, sign up and acquire a Subscription-Key. Include the key in the request headers to authenticate your access.

Request Headers:

Content-Type Set to application/json
Cache-Control Recommended to set to no-cache
Ocp-Apim-Subscription-Key YOUR_SUBSCRIPTION_KEY

Endpoint

Base URL: https://gateway.appypie.com/kling-ai-video/v1/generateVideoTask

Request Body Parameters

API Parameters: The API POST- https://gateway.appypie.com/kling-ai-video/v1/generateVideoTask takes the following parameters:

Parameters Type Required Description
prompt string Yes A detailed instruction or description for generating the desired video scene. Maximum length: 2500 characters.
negative_prompt string optional Text input to specify elements to exclude from the generated video. Maximum length: 2500 characters.
cfg_scale float optional Controls flexibility in video generation. Default: 0.5. Range: [0, 1]. Higher values increase adherence to the user's prompt, reducing flexibility.
aspect_ratio string optional Defines the aspect ratio of the video frame. Default: 16:9. Enum values: 16:9, 9:16, 1:1.
callback_url string Optional A URL for receiving task result notifications. Default: None. If set, the server sends task updates as per the "Callback Protocol".

Example Request Body

JSON

{
    "prompt": "An enchanted forest with glowing mushrooms, fireflies, and a sparkling river flowing through the trees.",
    "negative_prompt": "nude, porn, abusive"
}
    

Request Code

Input
POST https://gateway.appypie.com/kling-ai-video/v1/generateVideoTask HTTP/1.1

Content-Type: application/json
Cache-Control: no-cache

{
    "prompt": "An enchanted forest with glowing mushrooms, fireflies, and a sparkling river flowing through the trees.",
    "negative_prompt": "nude, porn, abusive"
}
import urllib.request, json

try:
    url = "https://gateway.appypie.com/kling-ai-video/v1/generateVideoTask"

    hdr ={
    # Request headers
    'Content-Type': 'application/json',
    'Cache-Control': 'no-cache',
    }

    # Request body
    data =  
    data = json.dumps(data)
    req = urllib.request.Request(url, headers=hdr, data = bytes(data.encode("utf-8")))

    req.get_method = lambda: 'POST'
    response = urllib.request.urlopen(req)
    print(response.getcode())
    print(response.read())
    except Exception as e:
    print(e)
// Request body
const body = {
    "prompt": "An enchanted forest with glowing mushrooms, fireflies, and a sparkling river flowing through the trees.",
    "negative_prompt": "nude, porn, abusive"
};

fetch('https://gateway.appypie.com/kling-ai-video/v1/generateVideoTask', {
        method: 'POST',
        body: JSON.stringify(body),
        // Request headers
        headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache',}
    })
    .then(response => {
        console.log(response.status);
        console.log(response.text());
    })
    .catch(err => console.error(err));
curl -v -X POST "https://gateway.appypie.com/kling-ai-video/v1/generateVideoTask" -H "Content-Type: application/json" -H "Cache-Control: no-cache" --data-raw "{
    \"prompt\": \"An enchanted forest with glowing mushrooms, fireflies, and a sparkling river flowing through the trees.\",
    \"negative_prompt\": \"nude, porn, abusive\"
}"
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.io.UnsupportedEncodingException;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.FileInputStream;

public class HelloWorld {

  public static void main(String[] args) {
    try {
        String urlString = "https://gateway.appypie.com/kling-ai-video/v1/generateVideoTask";
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        //Request headers
    connection.setRequestProperty("Content-Type", "application/json");
    
    connection.setRequestProperty("Cache-Control", "no-cache");
    
        connection.setRequestMethod("POST");

        // Request body
        connection.setDoOutput(true);
        connection
            .getOutputStream()
            .write(
             "{ \"prompt\": \"An enchanted forest with glowing mushrooms, fireflies, and a sparkling river flowing through the trees.\", \"negative_prompt\": \"nude, porn, abusive\" }".getBytes()
             );
    
        int status = connection.getResponseCode();
        System.out.println(status);

        BufferedReader in = new BufferedReader(
            new InputStreamReader(connection.getInputStream())
        );
        String inputLine;
        StringBuffer content = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        System.out.println(content);

        connection.disconnect();
    } catch (Exception ex) {
      System.out.print("exception:" + ex.getMessage());
    }
  }
}
$url = "https://gateway.appypie.com/kling-ai-video/v1/generateVideoTask";
$curl = curl_init($url);

curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

# Request headers
$headers = array(
    'Content-Type: application/json',
    'Cache-Control: no-cache',);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

# Request body
$request_body = '{
    "prompt": "An enchanted forest with glowing mushrooms, fireflies, and a sparkling river flowing through the trees.",
    "negative_prompt": "nude, porn, abusive"
}';
curl_setopt($curl, CURLOPT_POSTFIELDS, $request_body);

$resp = curl_exec($curl);
curl_close($curl);
var_dump($resp);


Response

JSON

HTTP/1.1 200 OK

{
    "code": 0,
    "message": "SUCCEED",
    "request_id": "CjMkWmdJhuIAAAAAAKKcRg",
    "data": {
        "task_id": "CjMkWmdJhuIAAAAAAKXXXX",
        "task_status": "submitted",
        "created_at": 1733214367840,
        "updated_at": 1733214367840
    }
}
    

Next Step: Polling Results

Retrieving Video Status and URL

To verify the status of your image generation request and retrieve the image URL, make a subsequent API call using the task_id provided in the original response.

Polling Endpoint

Base URL: https://gateway.appypie.com/kling-ai-polling/v1/getVideoStatus

Request Headers:

Content-Type Set to application/json
Cache-Control Recommended to set to no-cache

Request Body Parameters

API Parameters: The API POST- https://gateway.appypie.com/kling-ai-polling/v1/getVideoStatus takes the following parameters:

Request Body

Pass the task_id received from the initial response in your request body.

Example Request Body

JSON

{
    "task_id":"CjMkWmdJhuIAAAAAAKXXXX"
}        

Request Code

Input
POST https://gateway.appypie.com/kling-ai-polling/v1/getVideoStatus HTTP/1.1

Content-Type: application/json
Cache-Control: no-cache

{
    "task_id": "task_id"
}
import urllib.request, json

try:
    url = "https://gateway.appypie.com/kling-ai-polling/v1/getVideoStatus"

    hdr ={
    # Request headers
    'Content-Type': 'application/json',
    'Cache-Control': 'no-cache',
    }

    # Request body
    data =  
    data = json.dumps(data)
    req = urllib.request.Request(url, headers=hdr, data = bytes(data.encode("utf-8")))

    req.get_method = lambda: 'POST'
    response = urllib.request.urlopen(req)
    print(response.getcode())
    print(response.read())
    except Exception as e:
    print(e)
// Request body
const body = {
    "task_id": "task_id"
};

fetch('https://gateway.appypie.com/kling-ai-polling/v1/getVideoStatus', {
        method: 'POST',
        body: JSON.stringify(body),
        // Request headers
        headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache',}
    })
    .then(response => {
        console.log(response.status);
        console.log(response.text());
    })
    .catch(err => console.error(err));
curl -v -X POST "https://gateway.appypie.com/kling-ai-polling/v1/getVideoStatus" -H "Content-Type: application/json" -H "Cache-Control: no-cache" --data-raw "{
    \"task_id\": \"task_id\"
}"
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.io.UnsupportedEncodingException;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.FileInputStream;

public class HelloWorld {

  public static void main(String[] args) {
    try {
        String urlString = "https://gateway.appypie.com/kling-ai-polling/v1/getVideoStatus";
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        //Request headers
    connection.setRequestProperty("Content-Type", "application/json");
    
    connection.setRequestProperty("Cache-Control", "no-cache");
    
        connection.setRequestMethod("POST");

        // Request body
        connection.setDoOutput(true);
        connection
            .getOutputStream()
            .write(
             "{ \"task_id\": \"task_id\" }".getBytes()
             );
    
        int status = connection.getResponseCode();
        System.out.println(status);

        BufferedReader in = new BufferedReader(
            new InputStreamReader(connection.getInputStream())
        );
        String inputLine;
        StringBuffer content = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        System.out.println(content);

        connection.disconnect();
    } catch (Exception ex) {
      System.out.print("exception:" + ex.getMessage());
    }
  }
}
$url = "https://gateway.appypie.com/kling-ai-polling/v1/getVideoStatus";
$curl = curl_init($url);

curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

# Request headers
$headers = array(
    'Content-Type: application/json',
    'Cache-Control: no-cache',);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

# Request body
$request_body = '{
    "task_id": "task_id"
}';
curl_setopt($curl, CURLOPT_POSTFIELDS, $request_body);

$resp = curl_exec($curl);
curl_close($curl);
var_dump($resp);


Response for Polling

After successful polling, the API will respond with the status of the video generation and, if completed, provide the URL of the generated video.

Example Success Response

JSON

{
    "code": 0,
    "message": "SUCCEED",
    "request_id": "CjMkWmdJhuIAAAAAAKXApA",
    "data": {
        "task_id": "CjMkWmdJhuIAAAAAAKKcRg",
        "task_status": "succeed",
        "task_status_msg": "",
        "task_result": {
            "videos": [{
                "id": "2e0bd237-31ac-464d-98b3-ab0535ea8fee",
                "url": "https://cdn.klingai.com/bs2/upload-kling-api/6472161052/text2video/CjMkWmdJhuIAAAAAAKKcRg-0_raw_video_1.mp4",
                "duration": "5.1"
            }]
        },
        "created_at": 1733214367840,
        "updated_at": 1733214655289
    }
}
    

Response Handling

The Kling AI Text-to-Video Generation API returns specific HTTP status codes and detailed response bodies to reflect the outcome of each request. Developers are advised to implement effective error handling to manage these responses properly, ensuring a smooth and seamless user experience.

Common Status Codes and Responses

Status Code Description Response Body
200 Success - The request was successfully processed, and the image generation is in progress or completed. { "msg": "Image Getting Created", ... }
400 Bad Request - The request contains invalid parameters or missing fields. { "error": "Invalid request parameters" }
401 Unauthorized - The provided subscription key is missing or invalid. { "error": "Invalid or missing authentication" }
403 Forbidden - The subscription does not have access to this API or action. { "error": "Access denied for this operation" }
404 Not Found - The requested resource or endpoint could not be found. { "error": "Endpoint not found" }
429 Too Many Requests - The request rate limit has been exceeded. { "error": "Rate limit exceeded, please retry later" }
500 Internal Server Error - An unexpected error occurred on the server. { "error": "An unexpected error occurred, please try again later" }

Example Error Response

{
        "task_status": "failed",
        "task_status_msg": "task not found"
}
    

Conclusion

This detailed documentation provides all the necessary information to effectively use the Kling AI Text-to-Video Generation API. It covers everything from integration steps to usage guidelines to help you get started. Be sure to replace YOUR_API_KEY with the actual key provided when you subscribe to the service, as this is essential for authentication and access. By following the outlined instructions, you can easily integrate the API into your applications and harness its full capabilities for generating high-quality videos.