Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

Member-only story

How to Use the Kling AI API for Image Generation

AI Simplified
Python in Plain English
4 min readFeb 16, 2025

--

(Image Source)

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:

  1. Python Installed: Ensure you have Python installed on your system. You can download it from python.org.
  2. 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.
  3. 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.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

--

--

No responses yet

Write a response