Kling AI Text to Image Generation API Documentation

The Kling AI Text-to-Image API is a powerful tool that allows users to generate stunning, high-quality images from detailed text descriptions. This innovative technology opens up endless creative possibilities, making it ideal for artists, developers, marketers, and more. With this guide, you’ll find everything needed to integrate the API into your projects seamlessly. Learn how to authenticate your access, utilize the available endpoints, and optimize your experience for maximum efficiency.

Authentication:

To access this API, subscribe and obtain a Subscription-Key. Include this key in the request header for authentication.

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-image/v1/getImageTask

Request Body Parameters

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

Parameters Type Required Description
prompt string Yes Positive text prompt for image generation, with a maximum limit of 500 characters.
negative_prompt string optional Negative text prompt for excluding certain elements, with a maximum limit of 200 characters.
image string optional Input image in Base64 encoding or via URL. Default: null. Correct Base64 format: iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
image_fidelity float optional Sets the reference intensity for uploaded images during generation. Default: 0.5. Range: [0,1]. Higher values indicate stronger adherence to the input image.
n int Optional Number of images to generate. Default: 1. Range: [1,9].
aspect_ratio string Optional Aspect ratio of generated images. Default: 16:9. Enum values: 16:9, 9:16, 1:1, 4:3, 3:4, 3:2, 2:3.
callback_url string Optional Callback URL for receiving task result notifications. Default: None. When configured, the server will notify of task status updates. Refer to "Callback Protocol" for details.

Example Request Body

JSON

{
    "prompt": "Sparrow bird flying",
    "negative_prompt": "dark background, blurry details"
}
    

Request Code

Input
POST https://gateway.appypie.com/kling-ai-image/v1/getImageTask HTTP/1.1

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

{
    "prompt": "Sparrow bird flying"
}
import urllib.request, json

try:
    url = "https://gateway.appypie.com/kling-ai-image/v1/getImageTask"

    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": "Sparrow bird flying"
};

fetch('https://gateway.appypie.com/kling-ai-image/v1/getImageTask', {
        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-image/v1/getImageTask" -H "Content-Type: application/json" -H "Cache-Control: no-cache" --data-raw "{
    \"prompt\": \"Sparrow bird flying\"
}"
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-image/v1/getImageTask";
        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\": \"Sparrow bird flying\" }".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-image/v1/getImageTask";
$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": "Sparrow bird flying"
}';
curl_setopt($curl, CURLOPT_POSTFIELDS, $request_body);

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


Response

JSON

HTTP/1.1 200 OK

{
    "data": {
        "code": 0,
        "message": "SUCCEED",
        "request_id": "ChE1cmdAL6YAAAAAAQXcUg",
        "data": {
            "task_id": "ChE1cmdAL6YAAAAAAQXcUg",
            "task_status": "submitted",
            "created_at": 1732788384315,
            "updated_at": 1732788384315
        }
    }
}
    

Next Step: Polling Results

Retrieving Image Status and URL

To check the status of your image generation request and obtain the image URL, send a follow-up API call using the task_id included in the initial response.

Polling Endpoint

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

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/getImageStatus 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":"CjNSIWdD6DYAAAAAAIXXXX"
}        

Request Code

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

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

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

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

    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": "ChGl3Gc7D_cAAAXXXXXXXX"
};

fetch('https://gateway.appypie.com/kling-ai-polling/v1/getImageStatus', {
        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/getImageStatus" -H "Content-Type: application/json" -H "Cache-Control: no-cache" --data-raw "{
    \"task_id\": \"ChGl3Gc7D_cAAAXXXXXXXX\"
}"
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/getImageStatus";
        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\": \"ChGl3Gc7D_cAAAXXXXXXXX\" }".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/getImageStatus";
$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": "ChGl3Gc7D_cAAAXXXXXXXX"
}';
curl_setopt($curl, CURLOPT_POSTFIELDS, $request_body);

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


Response for Polling

When the polling is successful, the API returns a response indicating the image generation status and, if completed, the URL of the generated image.

Example Success Response

JSON

{
    "task_id": "CjNSIWdD6DYAAAAAAI1tSg",
    "task_status": "succeed",
    "task_status_msg": "",
    "task_result": {
        "images": [{
            "index": 0,
            "url": "https://cdn.klingai.com/bs2/upload-kling-api/7128237050/image/CjNSIWdD6DYAAAAAAI1tSg-0_raw_image_0.png"
        }]
    },
    "created_at": 1732789055592,
    "updated_at": 1732789063868
}
    

Response Handling

The Kling AI Text-to-Image API returns specific HTTP status codes and detailed response bodies to indicate the result of each request. Developers should implement robust error handling to process these responses efficiently and ensure a 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 comprehensive documentation outlines all the essential details required to effectively utilize the Kling AI Text-to-Image API. It includes everything you need to get started, from integration steps to usage guidelines. Make sure to replace YOUR_API_KEY with the actual key assigned to you upon subscribing to the service, as this is necessary for authentication and access. By following the provided instructions, you can seamlessly incorporate the API into your applications and unlock its full potential for generating high-quality images.