Member-only story
How to Use the Kling AI API for Image Generation

In this tutorial, we’ll walk through how to use the Kling AI API to generate images based on a text prompt. We’ll cover everything from setting up your environment to retrieving the generated images. Let’s get started!
The official documentation of Kling AI can be found here.
Prerequisites
Before we begin, make sure you have the following:
- Python Installed: Ensure you have Python installed on your system. You can download it from python.org.
- API Keys: You’ll need an API key (Access Key and Secret Key) from Kling AI. If you don’t have one, sign up on their platform to get your keys.
- Required Libraries: Install the necessary Python libraries using pip:
pip install requests pyjwt
Step 1: Set Up Your Environment
First, create a new Python file (e.g., kling_image_generation.py
) and import the necessary libraries:
import time
import jwt
import requests
Step 2: Generate a JWT Token
Kling AI uses JWT (JSON Web Tokens) for authentication. You’ll need to generate a JWT token using your Access Key (AK) and Secret Key (SK).
Here’s a function to generate the JWT token:
def encode_jwt_token(ak, sk):
headers = {
"alg": "HS256",
"typ": "JWT"
}
payload = {
"iss": ak, # Your Access Key
"exp": int(time.time()) + 1800, # Token expires in 30 minutes
"nbf": int(time.time()) - 5 # Token is valid 5 seconds from now
}
return jwt.encode(payload, sk, headers=headers)
- ak: Your Access Key.
- sk: Your Secret Key.
- exp: The expiration time of the token (30 minutes from now).
- nbf: The “not before” time, which ensures the token is valid only after 5 seconds from now.
Step 3: Generate an Image
Now that you have a JWT token, you can use it to generate an image based on a text prompt.