﻿> ## Documentation Index
>
> Fetch the complete documentation index at: https://kling.ai/document-api/llms.txt
> Use this file to discover all available pages before exploring further.

# Image Generation

> Source: https://kling.ai/document-api/api/image/4-0/image-generation
> Locale: en
> Current Tab: Image Generation
> Sibling Tabs: Image Generation / Long Image Generation / Element Management
> This content is optimized for LLMs. In-page tabs are expanded and UI-only controls are omitted.

---

## Create Task

### API Overview

- Method: `POST`
- Path: `/image-generation/kling-4.0`
- Auth: `Authorization: Bearer <API_KEY>`
- Content-Type: `application/json`

### Description

Supports text-to-image and image-to-image generation in single image mode or series mode. Single image mode can generate multiple independent images, series mode generates a series of related images.

### Headers

| Field | Type | Required | Default | Enum | Description |
|---|---|---:|---|---|---|
| `Content-Type` | string | Yes | `application/json` | - | Data exchange format |
| `Authorization` | string | Yes | - | - | Authentication information; see API Authentication |

### Request Body

| Field Path | Type | Required | Default | Enum | Description |
|---|---|---:|---|---|---|
| `contents` | array | Yes | - | - | A collection of reference input materials, such as prompts, images, and elements. |
| `contents[].type` | string | Yes | - | `prompt`, `refer_image`, `element` | Input material type. Supports prompts, reference images, and elements. |
| `settings` | object | No | - | - | Output configuration parameters, such as resolution and aspect ratio. |
| `settings.result_type` | string | No | `single` | `single`, `series` | Control whether to generate a single image or a series of images. |
| `settings.n` | int | No | `1` | - | Number of generated images (independent images). |
| `settings.series_amount` | int | No | `4` | - | Number of images in a generated image series. |
| `settings.resolution` | string | No | `2k` | `2k`, `4k`, `8k` | Image generation resolution. Applies to both single image mode and series mode. |
| `settings.aspect_ratio` | string | No | `auto` | `16:9`, `9:16`, `1:1`, `4:3`, `3:4`, `3:2`, `2:3`, `21:9`, `auto` | Aspect ratio of the generated images (width:height). |
| `options` | object | No | - | - | General configuration, such as callback URL and whether to include a watermark |
| `options.callback_url` | string | No | - | - | Callback notification URL for this task's results |
| `options.external_task_id` | string | No | - | - | User-defined task ID |
| `options.watermark_info` | object | No | - | - | Whether to generate watermarked results simultaneously |
| `options.watermark_info.enabled` | boolean | No | `false` | - | true enables generation, false disables generation; defaults to false. |

#### Request Body Field Notes

- `contents`: The reference format is shown below. See the parameter descriptions below for details:
- `contents`: ```json
  "contents": [
    {
      "type": "prompt",
      "text": "string"
    },
    {
      "type": "refer_image",
      "url": "string",
      "id": "string"
    },
    {
      "type": "element",
      "element_id": "string",
      "id": "string"
    }
  ]
  ```
- `contents[].type`: Input materials must include a prompt; prompt is required and must not be empty.
- `contents[].type`: A maximum of 10 images and elements combined is allowed. Prompts do not count toward the reference limit.
- `contents[].type.prompt`: Prompts can be templated to meet different image generation needs.
- `contents[].type.prompt`: Prompt length: English-only input must not exceed 50,000 characters; non-English-only input must not exceed 21,000 characters. Mixed input must satisfy: English character count/50000 + non-English character count/21000 ≤ 1.
- `contents[].type.prompt`: Defined in JSON format as follows:
- `contents[].type.prompt`: ```json
  {
    "type": "prompt", // Input material type; fixed parameter value: prompt; required
    "text": "string" // Text prompt content; required
  }
  ```
- `contents[].type.refer_image`: Defined in JSON format as follows:
- `contents[].type.refer_image`: ```json
  {
    "type": "refer_image", // Image input identifier
    "url": "string", // The input content can be provided through URL or base64; required
    "id": "string" // Reference ID for this input, used to reference it in the prompt; must be unique within the task
  }
  ```
- `contents[].type.refer_image`: Accepts an image URL or Base64-encoded data. The URL must be accessible, and the value must not be empty.
- `contents[].type.refer_image`: Supported image formats: .jpg/.jpeg/.png.
- `contents[].type.refer_image`: Each image file must not exceed 30 MB. Both width and height must be at least 300 px, and the aspect ratio must be within 2:5–5:2.
- `contents[].type.element`: Defined in JSON format as follows:
- `contents[].type.element`: ```json
  {
    "type": "element", // Input type, fixed parameter value: element; required
    "element_id": "string", // The element ID, generated by the system, is returned by querying the element related API; required
    "id": "string" // Reference ID for this input, used to reference it in the prompt; must be unique within the task
  }
  ```
- `contents[].type.element`: Only multi-image elements (elements customized using images) are supported. Different element types have different scopes of applicability; distinguish between them accordingly.
- `contents[].type.element`: The total number of reference images and elements must not exceed 10.
- `contents[].type.element`: For more information about official elements, see the [Element Library](https://kling.ai/document-api/api/image/4-0/elements).
- `settings.result_type`: single: Single image mode. Multiple independent images can be generated using n;
  - series: A series of related images. In series mode, images in the same series share a group_id and are returned in their order within the series.
- `settings.n`: Optional in single image mode
- `settings.n`: Value range: [1,9].
- `settings.n`: This parameter has no effect when result_type=series. The number of images in the series is specified by series_amount.
- `settings.series_amount`: Type: integer/string; optional in series mode
- `settings.series_amount`: Value range: [2,10] or the string auto.
- `settings.series_amount`: auto intelligently selects the number of images to generate (2–10) based on the input content. When using auto, it consumes concurrency corresponding to the actual number of images generated.
- `settings.series_amount`: Only takes effect when result_type=series.
- `settings.resolution`: 2k: 2K high-res;
  - 4k: 4K high-res;
  - 8k: 8K ultra-high-res;
- `settings.aspect_ratio`: auto: Intelligently determines the image aspect ratio based on the input content. Applies to both single image mode and series mode.
- `options.callback_url`: If configured, the server proactively sends notifications when the task status changes
- `options.callback_url`: For the notification message schema, see the [Callback Protocol](https://kling.ai/document-api/api/get-started/callbacks)
- `options.external_task_id`: Providing this ID does not overwrite the system-generated task ID, but it can be used to query the task
- `options.external_task_id`: Ensure that IDs are unique within a single user account
- `options.watermark_info`: Defined using the enabled parameter:
  ```json
  "watermark_info": {
    "enabled": false // true: generate watermarked result; false: do not generate; default: false
  }
  ```
- `options.watermark_info`: Custom watermarks are not currently supported

### Request Example

```bash
curl --request POST \
  --url "https://api-singapore.klingai.com/image-generation/kling-4.0" \
  --header "Authorization: Bearer ${KLING_API_KEY}" \
  --header "Content-Type: application/json" \
  --data '{
  "contents": [
    {
      "type": "prompt",
      "text": "Using the dog in @dog as a reference, generate a 3D animated character poster. Preserve its fur color and appearance, with warm lighting and a simple background."
    },
    {
      "type": "refer_image",
      "url": "https://p1-kling.klingai.com/kcdn/cdn-kcdn112452/kling-qa-test/dog.png",
      "id": "dog"
    }
  ],
  "settings": {
    "result_type": "single",
    "n": 1,
    "resolution": "2k",
    "aspect_ratio": "1:1"
  }
}'
```

### Response Example

```json
{
  "code": 0, // Error code; 0 indicates success; see the error code documentation for definitions
  "message": "SUCCEED", // API message
  "request_id": "example-request-id", // Request tracking ID, generated by the system
  "data": {
    "id": "example-task-id", // System task ID, generated by the platform
    "status": "submitted", // Task status: submitted/processing/succeeded/failed
    "create_time": 1790000000000, // Task creation time, Unix timestamp in milliseconds
    "update_time": 1790000000000, // Task update time, Unix timestamp in milliseconds
    "external_id": "string" // User-defined task ID specified at creation (if any)
  }
}
```

## More Scenario Examples

### Image-to-image generation (series mode; 1 reference image, 4 related images, 2K, 3:4)

```cURL
curl --request POST \
  --url "https://api-singapore.klingai.com/image-generation/kling-4.0" \
  --header "Authorization: Bearer ${KLING_API_KEY}" \
  --header "Content-Type: application/json" \
  --data '{
  "contents": [
    {
      "type": "prompt",
      "text": "Generate four coherent story images in a 3D animated style starring the dog in @dog, in this order: entering a café, sitting by the window, smelling the aroma of coffee, and saying goodbye at the entrance. Keep the dog’s fur color, appearance, and visual style consistent. Depict one story moment per image."
    },
    {
      "type": "refer_image",
      "url": "https://p1-kling.klingai.com/kcdn/cdn-kcdn112452/kling-qa-test/dog.png",
      "id": "dog"
    }
  ],
  "settings": {
    "result_type": "series",
    "series_amount": 4,
    "resolution": "2k",
    "aspect_ratio": "3:4"
  },
  "options": {
    "external_task_id": "",
    "watermark_info": {
      "enabled": false
    }
  }
}'
```

---

## Query Task (By task ID)

### API Overview

- Method: `GET`
- Path: `/tasks`
- Auth: `Authorization: Bearer <API_KEY>`
- Content-Type: `application/json`

### Description

> Note: The API currently supports querying async tasks only

### Headers

| Field | Type | Required | Default | Enum | Description |
|---|---|---:|---|---|---|
| `Content-Type` | string | Yes | `application/json` | - | Data Exchange Format |
| `Authorization` | string | Yes | - | - | Authentication information, refer to API authentication |

### Query Params

| Field | Type | Required | Default | Enum | Description |
|---|---|---:|---|---|---|
| `task_ids` | string | No | - | - | The task ID defined by the system that needs to be queried |
| `external_task_ids` | string | No | - | - | The custom task ID that needs to be queried |

#### Query Params Field Notes

- `task_ids`: Query parameter; provide the value in the URL query string
- `task_ids`: When querying a task, you can choose between two query methods: task_ids and external_task_ids, but you cannot use them simultaneously
- `task_ids`: Support batch queries, separated by ","
- `external_task_ids`: Query parameter; provide the value in the URL query string
- `external_task_ids`: When querying a task, you can choose between two query methods: task_ids and external_task_ids, but you cannot use them simultaneously
- `external_task_ids`: Support batch queries, separated by ","

### Request Example

```bash
curl --location 'https://api-singapore.klingai.com/tasks?task_ids=123' \
  --header 'Content-Type: application/json' \
  --header "Authorization: Bearer ${KLING_API_KEY}"
```

```bash
curl --location 'https://api-singapore.klingai.com/tasks?external_task_ids=123' \
  --header 'Content-Type: application/json' \
  --header "Authorization: Bearer ${KLING_API_KEY}"
```

### Response Example

```json
{
  "code": 0, // Error code. See Error Codes for details
  "message": "string", // Error information
  "request_id": "string", // Request ID, generated by the system, is used to track requests and troubleshoot problems
  "data": [
    {
      "id": "893605946402811985", // The task ID being queried
      "status": "string", // Task status, Enum values: submitted, processing, succeeded, failed
      "message": "string", // Task status information, displaying the failure reason when the task fails (such as triggering the content risk control of the platform, etc.)
      "create_time": 1781080778802, // Task creation time, Unix timestamp, unit ms
      "update_time": 1781080794151, // Task update time, Unix timestamp, unit ms
      "external_id": "string", // The custom task ID for this task (if any)
      "outputs": [
        {
          "type": "video", // When the generated result is "video", the return value and related fields vary by content type. Enum values: image, video, audio, element, voice
          "id": "string", // Video ID, generated by the system
          "url": "string", // Generated result URL with hotlink protection. (Generated results are retained for 30 days; save them promptly.)
          "watermark_url": "string", // URL for generating result with watermark, hotlink protection format
          "duration": "string" // The duration of the generated video, in seconds
        },
        {
          "type": "image", // When the generated result is "image", the return value and related fields vary by content type. Enum values: image, video, audio, element, voice
          "url": "string", // Generated result URL with hotlink protection. (Generated results are retained for 30 days; save them promptly.)
          "watermark_url": "string", // Image download URL with watermark, protected URL
          "group_id": "string" // Only appears when generating grouped images, used to mark grouping relationships
        },
        {
          "type": "audio", // When the generated result is "audio", the return value and related fields vary by content type. Enum values: image, video, audio, element, voice
          "id": "string", // Audio ID, generated by the system
          "mp3_url": "string", // Generated MP3 URL with hotlink protection. (Generated results are retained for 30 days; save them promptly.)
          "wav_url": "string", // Generated WAV URL with hotlink protection. (Generated results are retained for 30 days; save them promptly.)
          "mp3_duration": "string", // The duration of the generated MP3 format audio, in seconds
          "wav_duration": "string" // The duration of the generated WAV format audio, in seconds
        },
        {
          "type": "voice", // When the generated result is "voice", the return value and related fields vary by content type. Enum values: image, video, audio, element, voice
          "id": "string", // Voice ID, generated by the system
          "name": "string", // Voice name
          "url": "string", // Material download link
          "owned_by": "string", // Voice source, kling is the official voice library, and the number is the creator ID
          "status": "succeeded" // Voice status. Enum values: succeeded, deleted
        },
        {
          "type": "element", // When the generated result is "element", the return value and related fields vary by content type. Enum values: image, video, audio, element, voice
          "id": "string", // Element ID, generated by the system
          "name": "string", // Element name
          "description": "string", // Element description
          "element_type": "string", // Element type, divided into video character element and multi-image element, enumeration values are: video_character_elements and multi_image_elements
          "references": [ // Related materials of element
            {
              "type": "image", // When returning 'image' materials, the enumeration values for each content type are: image, video, voice
              "role": "string", // Image reference material attributes are divided into frontal reference images and other reference images, with enumeration values of frontal and reference, respectively
              "url": "string" // Material download link
            },
            {
              "type": "video", // When returning "video" materials, the enumeration values for each content type are: image, video, voice
              "role": "refer", // Video reference material attribute, fixed value: refer
              "url": "string" // Material download link
            },
            {
              "type": "voice", // When "voice" material is returned, enumeration values of each content type: image, video, voice
              "role": "refer", // Voice reference material attribute, fixed value: refer
              "url": "string", // Material download link
              "id": "string", // Voice ID
              "name": "string", // Voice name
              "owned_by": "string" // Voice source. kling means official voice library; numbers are creator IDs
            }
          ],
          "owned_by": "string", // Element source. kling means the official Element library; numbers are creator IDs
          "status": "string", // Element status. Enum values: succeeded, deleted
          "tags": [ // Element label related information
            {
              "id": 1, // Tag ID
              "name": "string", // Tag name
              "description": "string" // Tag description
            }
          ]
        }
      ],
      "billing": [ // When task consumes balances from multiple cash types, the system will return multiple records.
        {
          "charge_type": "string", // Consumption account type: If the consumption is of balance, the parameter value is "cash"; if it is of resource package, the parameter value is "unit"
          "cash_type": "string", // Balance type. Only applicable when charge_type=cash. If the consumption is the official quota, the parameter value is balance. If the consumption is the test quota, the parameter value is test_balance. If the consumption is the reward quota, the parameter value is reward_balance.
          "amount": "string", // Deduction amount; In the balance deduction situation (charge_type=cash), it represents the discount price deducted from the balance, and in the resource package deduction situation (charge_type=unit), it represents the deduction amount of units; decimal system
          "currency": "string", // Consumption unit, which only exists in the consumption balance scenario (charge_type=cash), with a fixed parameter value of CNY/USD
          "package_type": "string", // Consumable resource bundle type, which only exists in the consumable resource bundle scenario (charge_type=unit), with fixed enumeration values: video, image, audio
          "list_price": "string" // Balance deduction list price only exists in the consumption limit scenario (charge_type=cash)
        }
      ]
    }
  ]
}
```

---

## Query Task (By Cursor)

### API Overview

- Method: `POST`
- Path: `/tasks`
- Auth: `Authorization: Bearer <API_KEY>`
- Content-Type: `application/json`

### Description

> Note: The API currently supports querying async tasks only

### Headers

| Field | Type | Required | Default | Enum | Description |
|---|---|---:|---|---|---|
| `Content-Type` | string | Yes | `application/json` | - | Data Exchange Format |
| `Authorization` | string | Yes | - | - | Authentication information, refer to API authentication |

### Request Body

| Field Path | Type | Required | Default | Enum | Description |
|---|---|---:|---|---|---|
| `start_time` | string | No | `end_time - 30 days` | - | Start time for task creation filtering |
| `end_time` | string | No | `current time` | - | End time for task creation filtering |
| `cursor` | string | No | - | - | Continuation cursor, i.e. query starting point |
| `limit` | int | No | `100` | - | Query the number of tasks |
| `filters` | array | No | - | - | Query task filtering criteria, such as task status and function type |
| `filters[].key` | string | No | - | `status`, `product_type` | Filtering dimensions, currently supporting filtering based on task status and other conditions |
| `filters[].values` | array | No | - | - | Filter value |

#### Request Body Field Notes

- `start_time`: Unix timestamp, in milliseconds
- `start_time`: The default value is end_time - 30 days
- `start_time`: Start time must be earlier than end time
- `end_time`: The default value is current time
- `end_time`: Unix timestamp, in milliseconds
- `end_time`: End time must be later than start time
- `cursor`: Use the next_cursor returned by the previous query
- `cursor`: When cursor is not empty, start_time and end_time are ignored
- `limit`: Maximum value: 500
- `filters`: Load with key/value format:
  ```json
  "filters": [
    {
      "key": "status", // Filter dimension by task status, fixed value: status
      "values": ["succeeded"]
    },
    {
      "key": "product_type", // Filter dimension by function type, fixed value: product_type
      "values": ["image"]
    }
  ]
  ```
- `filters[].key`: status: filter by task status
  - product_type: filter by function type
- `filters[].values`: status: submitted, processing, succeeded, failed
- `filters[].values`: product_type: video, image, try_on

### Request Example

```bash
curl --location 'https://api-singapore.klingai.com/tasks' \
  --header 'Content-Type: application/json' \
  --header "Authorization: Bearer ${KLING_API_KEY}" \
  --data '{
    "start_time": "1781193600000",
    "end_time": "1781516352968",
    "cursor": "",
    "limit": 500,
    "filters": [
      {
        "key": "status",
        "values": ["succeeded"]
      },
      {
        "key": "product_type",
        "values": ["image"]
      }
    ]
  }'
```

### Response Example

```json
{
  "code": 0, // Error code. See Error Codes for details
  "message": "string", // Error information
  "request_id": "string", // Request ID, generated by the system
  "data": {
    "result": [
      {
        "id": "string", // The task ID being queried
        "status": "string", // Task status, Enum values: submitted, processing, succeeded, failed
        "message": "string", // Task status information, displaying the failure reason when the task fails
        "create_time": 1781080778802, // Task creation time, Unix timestamp, unit ms
        "update_time": 1781080794151, // Task update time, Unix timestamp, unit ms
        "external_id": "string", // The custom task ID for this task (if any)
        "outputs": [
        {
          "type": "video", // When the generated result is "video", the return value and related fields vary by content type. Enum values: image, video, audio, element, voice
          "id": "string", // Video ID, generated by the system
          "url": "string", // Generated result URL with hotlink protection. (Generated results are retained for 30 days; save them promptly.)
          "watermark_url": "string", // URL for generating result with watermark, hotlink protection format
          "duration": "string" // The duration of the generated video, in seconds
        },
        {
          "type": "image", // When the generated result is "image", the return value and related fields vary by content type. Enum values: image, video, audio, element, voice
          "url": "string", // Generated result URL with hotlink protection. (Generated results are retained for 30 days; save them promptly.)
          "watermark_url": "string", // Image download URL with watermark, protected URL
          "group_id": "string" // Only appears when generating grouped images, used to mark grouping relationships
        },
        {
          "type": "audio", // When the generated result is "audio", the return value and related fields vary by content type. Enum values: image, video, audio, element, voice
          "id": "string", // Audio ID, generated by the system
          "mp3_url": "string", // Generated MP3 URL with hotlink protection. (Generated results are retained for 30 days; save them promptly.)
          "wav_url": "string", // Generated WAV URL with hotlink protection. (Generated results are retained for 30 days; save them promptly.)
          "mp3_duration": "string", // The duration of the generated MP3 format audio, in seconds
          "wav_duration": "string" // The duration of the generated WAV format audio, in seconds
        },
        {
          "type": "voice", // When the generated result is "voice", the return value and related fields vary by content type. Enum values: image, video, audio, element, voice
          "id": "string", // Voice ID, generated by the system
          "name": "string", // Voice name
          "url": "string", // Material download link
          "owned_by": "string", // Voice source, kling is the official voice library, and the number is the creator ID
          "status": "succeeded" // Voice status. Enum values: succeeded, deleted
        },
        {
          "type": "element", // When the generated result is "element", the return value and related fields vary by content type. Enum values: image, video, audio, element, voice
          "id": "string", // Element ID, generated by the system
          "name": "string", // Element name
          "description": "string", // Element description
          "element_type": "string", // Element type, divided into video character element and multi-image element, enumeration values are: video_character_elements and multi_image_elements
          "references": [ // Related materials of element
            {
              "type": "image", // When returning 'image' materials, the enumeration values for each content type are: image, video, voice
              "role": "string", // Image reference material attributes are divided into frontal reference images and other reference images, with enumeration values of frontal and reference, respectively
              "url": "string" // Material download link
            },
            {
              "type": "video", // When returning "video" materials, the enumeration values for each content type are: image, video, voice
              "role": "refer", // Video reference material attribute, fixed value: refer
              "url": "string" // Material download link
            },
            {
              "type": "voice", // When "voice" material is returned, enumeration values of each content type: image, video, voice
              "role": "refer", // Voice reference material attribute, fixed value: refer
              "url": "string", // Material download link
              "id": "string", // Voice ID
              "name": "string", // Voice name
              "owned_by": "string" // Voice source. kling means official voice library; numbers are creator IDs
            }
          ],
          "owned_by": "string", // Element source. kling means the official Element library; numbers are creator IDs
          "status": "string", // Element status. Enum values: succeeded, deleted
          "tags": [ // Element label related information
            {
              "id": 1, // Tag ID
              "name": "string", // Tag name
              "description": "string" // Tag description
            }
          ]
        }
      ],
        "billing": [ // When task consumes balances from multiple cash types, the system will return multiple records.
          {
            "charge_type": "string", // Consumption account type: cash for balance, unit for resource package
            "cash_type": "string", // Balance type. Only applicable when charge_type=cash. If the consumption is the official quota, the parameter value is balance. If the consumption is the test quota, the parameter value is test_balance. If the consumption is the reward quota, the parameter value is reward_balance.
            "amount": "string", // Deduction amount; In the balance deduction situation (charge_type=cash), it represents the discount price deducted from the balance, and in the resource package deduction situation (charge_type=unit), it represents the deduction amount of units; decimal system
            "currency": "string", // Consumption unit, which only exists in the consumption balance scenario (charge_type=cash), with a fixed parameter value of CNY/USD
            "package_type": "string", // Consumable resource bundle type, which only exists in the consumable resource bundle scenario (charge_type=unit), with fixed enumeration values: video, image, audio
            "list_price": "string" // Balance deduction list price only exists in the consumption limit scenario (charge_type=cash)
          }
        ]
      }
    ],
    "count": 1, // Number of query results
    "next_cursor": "string", // Cursor for querying subsequent results
    "has_more": true // Whether there are more results based on cursor information
  }
}
```
