> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.beatapi.io/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.beatapi.io/_mcp/server.

# Kling Image 4.0

POST https://api.beatapi.io/v1/images/tasks
Content-Type: application/json

可灵的图片模型。每个任务根据文字、最多 10 张参考图和命名元素生成或编辑 1–9 张图片，支持 2K、4K 和 8K。- 异步调用：创建请求会立即返回任务 ID，任务成功后即可取得图片。
- 一个任务用 `n` 生成 1–9 张图片，每张按 `resolution` 档位计费。
- 支持文生图，也可以用公网 HTTPS 链接传入参考图和命名 `elements`（合计最多 10 个）进行编辑与合成。
- 在提示词里引用输入：`images` 按顺序写作 `@image_1`、`@image_2` …，元素写作 `@` 加元素名。
- 按 `resolution`（2K、4K 或 8K）逐张计价，每张参考图和每个元素另收固定费用。任务失败不收费。POST/v1/images/tasks试一试在调试窗口里打开本模型，填入你的 BeatAPI API 密钥即可创建任务。调用是真实的，费用从你自己的余额中扣除。## 接口与鉴权`POST https://api.beatapi.io/v1/images/tasks`Authorization
string
必需你的 BeatAPI API 密钥，以 `Bearer <BEATAPI_API_KEY>` 形式发送。在[控制台](https://beatapi.io/dashboard)创建密钥。密钥只能保存在你的服务端，不要放进浏览器或移动端应用。请求体使用 JSON，并设置 `Content-Type: application/json`。`Idempotency-Key` 为可选：每个逻辑请求发送一个唯一值（最长 255 个字符），仅在重试完全相同的请求体时复用。24 小时内，用相同的键和请求体重试会再次返回第一次的响应，并带上 `Idempotent-Replayed: true`；相同的键搭配不同的请求体则返回 `409 idempotency_conflict`。非 2xx 的响应不会被保存，因此 400 或 402 之后的重试会重新执行。## 请求流程向接口 `POST` 下方的参数。返回 `201` 表示任务已被接受，其价格已从你的余额中预留；任务在后台运行。保存 `data.id`。调用 `GET /v1/tasks/{task_id}`，两次调用之间等待 `data.poll_after_seconds` 秒（图片 5 秒，视频 8 秒），直到 `status` 为 `succeeded` 或 `failed`。也可以为 `task.succeeded` 和 `task.failed` 注册 [Webhook](/webhooks)；仍需保留轮询作为兜底，因为因处理超时而终止的任务不会发送事件。状态为 `succeeded` 时，下载每个 `data.output.media[].url` 并保存你需要的文件；BeatAPI 不承诺结果链接的保留时长。状态为 `failed` 时，读取 `data.error_code` 和 `data.error_message`：预扣的金额已退回你的余额，`data.retryable` 表示再次发送相同请求是否可能成功。## 输入模式| 模式      | 必填输入                                          | 说明                                                              |
| ------- | --------------------------------------------- | --------------------------------------------------------------- |
| 文生图     | `model`、`prompt`                              | 不传 `images` 和 `elements`。                                       |
| 编辑或合成图片 | `model`、`prompt`，以及 `images`、`elements` 之一或两者 | 参考图与元素合计最多 10 个。在 `prompt` 中逐一引用：第一张图写 `@image_1`，元素写 `@` 加元素名。 |## 请求参数model
string
必需要调用的模型。**取值**：`kling-image-v4`**取值有误时**- 未传：`"model" is required`
- 模型 ID 不存在：`"model" kling-image-v9 is not catalogued`
- 把视频模型发到了这个端点：`"model" kling-v4 is served by POST /v1/videos/tasks, not this endpoint`prompt
string
必需要画什么，或要在参考图上改什么：主体、风格、光线、构图以及必须出现在图中的文字，并用 `@` 引用逐一指明各个输入。**长度**：1–20000 个字符- 长度按字符计（一个中日韩文字算一个字符）。
- 引用方式：`images` 按列表顺序写作 `@image_1`、`@image_2` …，元素写作 `@` 加它的 `name`。
- 每个 `@image_N` 都必须对应同一请求中的一张图。只传两张图却写了 `@image_3`，会在创建任务时被拒绝。**取值有误时**- 未传：`"prompt" is required`
- 为空或超过长度上限：`"prompt" has an unsupported length`
- 引用了请求中没有的图片：`the prompt names @image_3, which this request does not send`images
string[]
可选要编辑或合成的参考图。在提示词中按列表顺序写作 `@image_1`、`@image_2` …。**数量**：1–10  \
每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。- 每一项都必须是指向 JPEG 或 PNG 文件的公网 `https://` 链接。创建任务时，BeatAPI 会读取每个链接；不是这类图片或超出下方限制的，会按位置指出并拒绝（`images[0]` 是第一个链接）。
- `images` 与 `elements` 合计最多 10 个。
- 每个链接都会给任务加一笔固定费用（见计费）。**取值有误时**- 超过上限：`"images" accepts at most 10 items`
- 空数组：`"images" requires at least 1 item`
- 不是 https\:// 链接：`"images[0]" must be a public HTTPS URL`
- 链接不是 JPEG 或 PNG 文件（此例为 WebP）：`"images[0]" is not a PNG or JPEG image: the URL returned image/webp`
- 链接返回错误：`"images[0]" could not be downloaded: the URL returned HTTP 404`
- 图片与元素合计超过 10 个：`Kling Image 4.0 takes at most 10 images and elements together`**示例**```json
"images": [
  "https://cdn.beatapi.io/samples/smart-bottle.png",
  "https://cdn.beatapi.io/samples/neon-singer.png"
]
```elements
object[]
可选命名主体，例如角色、动物、道具、服装或场景。每个元素用 2–4 张图片表示，在提示词中写作 `@` 加它的 `name`。**数量**：≤ 10- 对象数组。每个对象只接受以下键：
- `elements[].name`（字符串，必填）：1–20 个字母、数字、下划线或汉字，同一请求内不区分大小写不得重复；不能是 `image_N`、`video_N`、`voice_N`、`keyframe_N`、`object_N`、`audio_N`、`first_frame` 或 `last_frame`。
- `elements[].element_input_urls`（字符串数组，必填）：2–4 个指向该元素图片的公网 HTTPS 链接，第一张是主视图。
- `elements[].tag`（字符串，可选）：元素的类别。
- `elements[].description`（字符串，可选）：元素说明，最多 100 个字符。
- 元素只能由图片组成：本模型不接受视频元素和带声音的元素。
- `images` 与 `elements` 合计最多 10 个。每个元素给任务加一笔固定费用，与它包含几张图无关。**取值有误时**- 多于 10 个元素：`"elements" accepts at most 10 items`
- 元素不是对象：`"elements[0]" must be an object`
- 元素缺少 `name`：`"name" is required in "elements[0]"`
- 元素缺少 `element_input_urls`：`"element_input_urls" is required in "elements[0]"`
- `name` 为空或超过 20 个字符：`"elements[0].name" has an unsupported length`
- `name` 含其他字符，或是保留名：`elements[0].name "image_1" is not a name Kling V4 accepts`
- 同一个 `name` 出现两次（不区分大小写）：`elements[1].name "Hero" is used twice`
- 图片少于两张：`"elements[0].element_input_urls" requires at least 2 item`
- 图片多于四张：`"elements[0].element_input_urls" accepts at most 4 items`
- `tag` 不在列表中：`"elements[0].tag" must be one of: [character animal prop costume scene effect others]`
- `description` 超过 100 个字符：`"elements[0].description" has an unsupported length`
- 元素里有不接受的键，例如视频：`field "element_input_video_urls" is not supported in "elements[0]"`**示例**```json
"elements": [
  {
    "name": "Bottle",
    "tag": "prop",
    "description": "A matte smart water bottle",
    "element_input_urls": [
      "https://your-cdn.example.com/bottle-front.png",
      "https://your-cdn.example.com/bottle-side.png"
    ]
  }
]
```aspect_ratio
string
可选默认值: auto图片的宽高比，写作 宽:高。**可选值**：`auto`, `1:1`, `16:9`, `9:16`, `4:3`, `3:4`, `3:2`, `2:3`, `21:9`  \
**默认值**：`auto`- 不传时使用 `auto`：由模型根据提示词和输入图决定画幅。对画面形状有要求时请明确传比例。**取值有误时**- 取值不在列表中：`"aspect_ratio" must be one of: [auto 1:1 16:9 9:16 4:3 3:4 3:2 2:3 21:9]`resolution
string
可选默认值: 2K图片的尺寸档位：`2K`、`4K` 或 `8K`。每档每张单独定价。**可选值**：`2K`, `4K`, `8K`  \
**默认值**：`2K`- 不传时使用并按 `2K` 计费。
- 2K 和 4K 返回 PNG，8K 返回 JPEG。
- K 必须大写：`2k` 会被拒绝。没有 1K 档，也不接受 `2048x2048` 这样的像素尺寸。**取值有误时**- 取值不在列表中（例如 `1K` 或 `2k`）：`"resolution" must be one of: [2K 4K 8K]`n
integer
可选默认值: 1本任务要生成的图片张数。每张都使用相同的提示词、输入、比例和档位。**默认值**：`1`  \
**范围**：1–9- 不传时为 `1`。
- 每张图按 `resolution` 的价格计费，所以 `n` 会成倍放大图片部分的价格；参考图和元素的费用每个任务只计一次，不按张数重复计。
- 按交付的图片张数计费。**取值有误时**- 超出范围、不是整数，或以字符串传入：`"n" is outside its supported range`网关还会在创建任务之前检查以下组合：- `n` 让一次请求生成 1–9 张图；每张图按其分辨率档计费，`images` 里的每张图和每个元素每次请求另计一次。
- 提示词中按顺序用 `@image_1`、`@image_2` … 指代 `images` 里的图，用 `@` 加元素名指代元素；每个 `@image_N` 都必须对应同一请求中的一张图。
- 一个元素是 `element_input_urls` 里同一主体的 2–4 张图（第一张为主视图）；`images` 与 `elements` 合计最多 10 个。
- 元素名为 1–20 个字母、数字、下划线或汉字，不区分大小写不得重复，且不能是 `image_N`、`video_N`、`voice_N`、`keyframe_N`、`object_N`、`audio_N`、`first_frame` 或 `last_frame`。
- `images` 里的图须为 JPEG 或 PNG，不超过 20 MB，宽高比在 2:5 到 5:2 之间，每边不超过 8192 px。
- `2K` 和 `4K` 返回 PNG，`8K` 返回 JPEG；`aspect_ratio: auto` 由模型根据提示词和输入图决定画幅。## 输入素材限制网关会在创建任务之前读取每一项输入，超出这些限制的输入会被拒绝，并返回点名该输入的 `400 bad_request`。不扣费。| 素材 | 创建任务前检查的限制                                     |
| -- | ---------------------------------------------- |
| 图片 | 宽和高均为 至多 8192 像素；宽高比（宽 ÷ 高）0.4–2.5；每个不超过 20 MB |- 网关会在创建任务前读取 `images` 中的每个链接，超出限制的会被拒绝，报错会指出是哪一个，例如 `images[0] has an aspect ratio of 3.10 (width/height); this model takes 0.4 to 2.5.` 不收费。
- 元素图片（`element_input_urls`）在创建任务前只检查是否为公网 HTTPS 链接。请使用符合同样限制的 JPEG 或 PNG 文件。
- 本地文件请先用 `POST /v1/files` 上传，再传入返回的 `data.url`。## 提示词中的引用每种输入都有自己的引用写法：| 引用                      | 指代             | 可用条件              |
| ----------------------- | -------------- | ----------------- |
| `@image_1`、`@image_2` … | `images`，按列表顺序 | 至少传了这么多张图         |
| `@` + 元素名               | `name` 为该值的元素  | 该元素在 `elements` 中 |- 没有对应图片的 `@image_N` 会在创建任务时被拒绝，例如 `the prompt names @image_2, which this request does not send`。## 该模型不接受的字段图片端点支持一些其他图片模型使用的字段。在这里传入它们会被拒绝而不是被忽略，因此你不会为没有效果的设置付费：- `output_format`、`quality`、`seed`、`background`、`size`、`enhance_prompt` → `field "output_format" is not supported by model kling-image-v4`（其中是你传入的字段名）。
- 其他任何未知字段 → `unknown field: <name>`。如果请求中有多个无效字段，报错信息只会指出其中一个；修正后再次发送即可。## 请求示例```bash title="cURL"
curl --request POST \
  --url https://api.beatapi.io/v1/images/tasks \
  --header "Authorization: Bearer $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-image-v4",
  "prompt": "A cinematic storefront campaign image at blue hour, warm light spilling from the windows onto wet pavement",
  "aspect_ratio": "16:9",
  "resolution": "2K"
}'
``````python title="Python"
import os
import requests

response = requests.post(
    "https://api.beatapi.io/v1/images/tasks",
    headers={"Authorization": f"Bearer {os.environ['BEATAPI_API_KEY']}"},
    json={
      "model": "kling-image-v4",
      "prompt": "A cinematic storefront campaign image at blue hour, warm light spilling from the windows onto wet pavement",
      "aspect_ratio": "16:9",
      "resolution": "2K"
    },
    timeout=60,
)
body = response.json()
if not response.ok:
    raise RuntimeError(f"{response.status_code} {body['error']['code']}: {body['error']['message']}")
task = body["data"]
print(task["id"], task["status"])
``````javascript title="JavaScript"
const response = await fetch('https://api.beatapi.io/v1/images/tasks', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.BEATAPI_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "model": "kling-image-v4",
    "prompt": "A cinematic storefront campaign image at blue hour, warm light spilling from the windows onto wet pavement",
    "aspect_ratio": "16:9",
    "resolution": "2K"
  }),
});
const body = await response.json();
if (!response.ok) throw new Error(`${response.status} ${body.error.code}: ${body.error.message}`);
console.log(body.data.id, body.data.status);
```### 文生图根据提示词生成一张 2K 图片。```bash
curl --request POST \
  --url https://api.beatapi.io/v1/images/tasks \
  --header "Authorization: Bearer $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-image-v4",
  "prompt": "A cinematic storefront campaign image at blue hour, warm light spilling from the windows onto wet pavement",
  "aspect_ratio": "16:9",
  "resolution": "2K"
}'
```### 一个任务出四张用同一提示词生成四张 4K 图片，每张按 4K 价格计费。```bash
curl --request POST \
  --url https://api.beatapi.io/v1/images/tasks \
  --header "Authorization: Bearer $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-image-v4",
  "prompt": "A minimalist poster of a lighthouse on a cliff at dawn, soft pastel colours, generous empty sky",
  "aspect_ratio": "3:4",
  "resolution": "4K",
  "n": 4
}'
```### 编辑一张图片把一张商品照片重新构图为宣传图。```bash
curl --request POST \
  --url https://api.beatapi.io/v1/images/tasks \
  --header "Authorization: Bearer $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-image-v4",
  "prompt": "Keep the bottle in @image_1 exactly as it is. Place it on a sunlit kitchen counter with a soft reflection under it.",
  "images": [
    "https://cdn.beatapi.io/samples/smart-bottle.png"
  ],
  "resolution": "2K"
}'
```### 合成多张图片在提示词中用引用逐一指明每张参考图。```bash
curl --request POST \
  --url https://api.beatapi.io/v1/images/tasks \
  --header "Authorization: Bearer $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-image-v4",
  "prompt": "Place the bottle from @image_1 on a neon-lit stage like the one in @image_2. Keep the bottle label readable.",
  "images": [
    "https://cdn.beatapi.io/samples/smart-bottle.png",
    "https://cdn.beatapi.io/samples/neon-singer.png"
  ],
  "aspect_ratio": "16:9",
  "resolution": "2K"
}'
```### 命名元素把同一主体的多个角度做成一个元素，再按名字放进画面。```bash
curl --request POST \
  --url https://api.beatapi.io/v1/images/tasks \
  --header "Authorization: Bearer $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-image-v4",
  "prompt": "A product shot of @Bottle on a marble bathroom shelf beside folded towels, morning light",
  "elements": [
    {
      "name": "Bottle",
      "tag": "prop",
      "element_input_urls": [
        "https://your-cdn.example.com/bottle-front.png",
        "https://your-cdn.example.com/bottle-side.png"
      ]
    }
  ],
  "aspect_ratio": "1:1",
  "resolution": "2K"
}'
```## 响应### 创建任务（201）任务对象。任务成功之前 `output` 为 `null`。标注“运行中”的字段会在任务结束后消失。```json
{
  "data": {
    "id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
    "object": "task",
    "task_kind": "image",
    "capability_id": "kling-image-v4",
    "capability_version": 1,
    "media_type": "image",
    "model": "kling-image-v4",
    "status": "queued",
    "stage": "queued",
    "created_at": 1791993600,
    "updated_at": 1791993600,
    "completed_at": null,
    "poll_after_seconds": 5,
    "output": null,
    "usage": {
      "credits_reserved": 0.0593,
      "credits_settled": 0,
      "credits_refunded": 0,
      "credits_charged": 0.0593
    },
    "request_id": "req_5f0c2a9e4b7d4e31",
    "error_code": null,
    "error_message": null
  }
}
```| 字段                                     | 类型                | 说明                                                                        |
| -------------------------------------- | ----------------- | ------------------------------------------------------------------------- |
| `data.id`                              | `string`          | 任务 ID：`task_` 后接 32 位字母和数字。用于轮询以及匹配 Webhook 事件。                           |
| `data.object`                          | `string`          | 固定为 `task`。                                                               |
| `data.task_kind`                       | `string`          | `image` 或 `video`。                                                        |
| `data.capability_id`                   | `string`          | 你发送的模型 ID。                                                                |
| `data.capability_version`              | `integer`         | 模型的契约版本，当前为 `1`。                                                          |
| `data.media_type`                      | `string`          | `image` 或 `video`。                                                        |
| `data.model`                           | `string`          | 你发送的模型 ID（与 `capability_id` 相同）。                                          |
| `data.status`                          | `string`          | `queued`、`processing`、`succeeded` 或 `failed`。只有后两个是终态。                    |
| `data.stage`                           | `string`          | 与 `status` 相同；为旧版客户端保留。                                                   |
| `data.created_at`                      | `integer`         | 任务创建时间，Unix 秒。                                                            |
| `data.updated_at`                      | `integer`         | 最后一次变更时间，Unix 秒。                                                          |
| `data.completed_at`                    | `integer \| null` | 任务结束时间，Unix 秒；运行中为 `null`。                                                |
| `data.poll_after_seconds`              | `integer`         | 运行中：下一次轮询前需要等待的秒数（图片 5，视频 8）。                                             |
| `data.typical_seconds`                 | `object`          | 运行中且近期样本足够时出现：在最近的 `window` 内，根据 `samples` 个任务统计的完成时间 `p50` 和 `p90`，单位为秒。 |
| `data.output`                          | `object \| null`  | 任务结果；`status` 为 `succeeded` 之前为 `null`。见下方输出字段。                           |
| `data.usage.credits_reserved`          | `number`          | 创建任务时从你的余额中预扣的美元金额。                                                       |
| `data.usage.credits_charged`           | `number`          | 该任务的费用（美元）；失败的任务为 `0`。                                                    |
| `data.usage.credits_settled`           | `number`          | 最终结算扣除的美元金额；任务成功时设置，否则为 `0`。                                              |
| `data.usage.credits_refunded`          | `number`          | 退回你余额的美元金额；失败的任务在退款记录完成后等于预扣金额。                                           |
| `data.usage.billable_duration_seconds` | `integer`         | 仅视频：计价所依据的秒数。模型未上报时长时不出现。                                                 |
| `data.request_id`                      | `string`          | 请求 ID。联系支持时请附上。                                                           |
| `data.error_code`                      | `string \| null`  | 失败码；任务未失败时为 `null`。                                                       |
| `data.error_message`                   | `string \| null`  | 出了什么问题以及该改什么；任务未失败时为 `null`。                                              |### 任务完成`GET /v1/tasks/{task_id}` 返回 HTTP 200 和 `status: "succeeded"`，结果在 `data.output` 中。```json
{
  "data": {
    "id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
    "object": "task",
    "task_kind": "image",
    "capability_id": "kling-image-v4",
    "capability_version": 1,
    "media_type": "image",
    "model": "kling-image-v4",
    "status": "succeeded",
    "stage": "succeeded",
    "created_at": 1791993600,
    "updated_at": 1791993690,
    "completed_at": 1791993690,
    "output": {
      "media": [
        {
          "type": "image",
          "url": "https://media.beatapi.io/outputs/task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ/0.png",
          "mime_type": "image/png"
        }
      ],
      "r2_url": "https://media.beatapi.io/outputs/task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ/0.png"
    },
    "usage": {
      "credits_reserved": 0.0593,
      "credits_settled": 0.0593,
      "credits_refunded": 0,
      "credits_charged": 0.0593
    },
    "request_id": "req_5f0c2a9e4b7d4e31",
    "error_code": null,
    "error_message": null
  }
}
```#### 输出字段| 字段                         | 类型         | 说明                                               |
| -------------------------- | ---------- | ------------------------------------------------ |
| `output.media`             | `object[]` | 生成的文件：每张交付的图片一项，最多 `n` 项。                        |
| `output.media[].type`      | `string`   | 固定为 `image`。                                     |
| `output.media[].url`       | `string`   | 存储图片的 HTTPS 链接。请下载保存；不承诺保留期限。                    |
| `output.media[].mime_type` | `string`   | 存储的文件类型：2K 和 4K 为 `image/png`，8K 为 `image/jpeg`。 |
| `output.r2_url`            | `string`   | 第一个媒体链接的副本，供旧客户端使用。请改读 `media`。                  |### 任务失败失败的任务在 `GET /v1/tasks/{task_id}` 上仍然是 HTTP 200：失败信息在响应体里。预扣金额会全额退回，因此不会扣费。```json
{
  "data": {
    "id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
    "object": "task",
    "task_kind": "image",
    "capability_id": "kling-image-v4",
    "capability_version": 1,
    "media_type": "image",
    "model": "kling-image-v4",
    "status": "failed",
    "stage": "failed",
    "created_at": 1791993600,
    "updated_at": 1791993690,
    "completed_at": 1791993690,
    "output": null,
    "usage": {
      "credits_reserved": 0.0593,
      "credits_settled": 0,
      "credits_refunded": 0.0593,
      "credits_charged": 0
    },
    "retryable": true,
    "request_id": "req_5f0c2a9e4b7d4e31",
    "error_code": "processing_failed",
    "error_message": "The task failed during processing on our side. Retry; a failed task is refunded."
  }
}
```| 字段                   | 类型        | 说明                                                                                                                                                                          |
| -------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data.error_code`    | `string`  | `bad_request` 和 `content_policy_violation`（需修改请求）之一，或 `processing_unavailable`、`processing_timeout`、`processing_failed` 和 `result_transfer_failed`（稍后重试）之一。见[错误码](/errors)。 |
| `data.error_message` | `string`  | 一句话，指出问题和处理方式。                                                                                                                                                              |
| `data.retryable`     | `boolean` | 仅在任务失败时出现：为 `true` 表示再次发送相同请求可能成功。                                                                                                                                          |
| `data.usage`         | `object`  | 退款记录完成后（通常就在任务失败的那一刻）：`credits_charged` 和 `credits_settled` 为 `0`；`credits_refunded` 等于 `credits_reserved`。                                                                 |## 完整示例创建任务，按服务端给出的轮询提示等待，然后打印结果链接。请在环境变量中设置 `BEATAPI_API_KEY` 并安装 `requests`。```python
import os
import time
import uuid

import requests

API = "https://api.beatapi.io"
HEADERS = {"Authorization": f"Bearer {os.environ['BEATAPI_API_KEY']}"}


def create_task(body: dict) -> dict:
    # One Idempotency-Key per logical request: a retry with the same key cannot create a second task.
    headers = {**HEADERS, "Idempotency-Key": str(uuid.uuid4())}
    for attempt in range(3):
        response = requests.post(f"{API}/v1/images/tasks", headers=headers, json=body, timeout=60)
        if response.status_code in (429, 503) and attempt < 2:
            time.sleep(int(response.headers.get("Retry-After", 10)))
            continue
        break
    try:
        payload = response.json()
    except ValueError:  # an edge error page is not JSON
        response.raise_for_status()
        raise
    if not response.ok:
        error = payload["error"]
        raise RuntimeError(f"{response.status_code} {error['code']}: {error['message']} (request_id={error.get('request_id')})")
    return payload["data"]


def wait_for_task(task_id: str, timeout_seconds: int = 1800) -> dict:
    deadline = time.monotonic() + timeout_seconds
    while time.monotonic() < deadline:
        response = requests.get(f"{API}/v1/tasks/{task_id}", headers=HEADERS, timeout=30)
        if response.status_code == 429 or response.status_code >= 500:
            time.sleep(int(response.headers.get("Retry-After", 10)))
            continue
        response.raise_for_status()
        task = response.json()["data"]
        if task["status"] in ("succeeded", "failed"):
            return task
        time.sleep(task.get("poll_after_seconds", 5))
    raise TimeoutError(f"task {task_id} is still running; keep polling later")


task = create_task({
  "model": "kling-image-v4",
  "prompt": "A cinematic storefront campaign image at blue hour, warm light spilling from the windows onto wet pavement",
  "aspect_ratio": "16:9",
  "resolution": "2K"
})
print("created", task["id"])
task = wait_for_task(task["id"])
if task["status"] == "failed":
    raise SystemExit(f"{task['error_code']}: {task['error_message']}")
for item in task["output"]["media"]:
    print(item["url"])
```## 计费- 每张图按 `resolution` 定价（见下表），再乘以 `n`。`images` 里的每个链接和 `elements` 里的每个元素，每个任务各加一笔固定费用。
- 创建任务时会预留这笔费用：从余额扣，如果密钥设置了额度也从额度扣。在任务创建前就被拒绝的请求不收费。
- 任务成功后按交付的图片张数计费。任务失败时预留金额全额退回：`credits_refunded` 等于 `credits_reserved`，`credits_charged` 和 `credits_settled` 为 0。当前牌价，与[价格页](https://beatapi.io/pricing)一致。享有协商折扣的账户实付更低；任务的 `data.usage` 始终显示实际扣费金额。| 选项                                       | 牌价（美元）   |
| ---------------------------------------- | -------- |
| 1 张图片 · 2K                               | \$0.0593 |
| 1 张图片 · 4K                               | \$0.0893 |
| 1 张图片 · 8K                               | \$0.1486 |
| `images` 里每张参考图、`elements` 里每个元素，每个任务计一次 | \$0.0026 |## 常见错误| 错误或现象                                                                     | 原因                                                                                  | 处理方式                                                   |
| ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------ |
| 400 `"resolution" must be one of: [2K 4K 8K]`                             | 传了 `1K`、小写的 `2k`，或 `2048x2048` 这样的像素尺寸。                                             | 传 `2K`、`4K` 或 `8K`，或者不传该字段。                            |
| 400 `"n" is outside its supported range`                                  | `n` 大于 9、小于 1、是小数或字符串。                                                              | 传 1–9 的整数；需要更多图片时再建一个任务。                               |
| 400 `Kling Image 4.0 takes at most 10 images and elements together`       | `images` 与 `elements` 合计超过 10 个。                                                    | 总数控制在 10 个以内；同一主体的多张图片可以合成一个元素。                        |
| 400 `the prompt names @image_3, which this request does not send`         | 引用的编号超过了 `images` 中最后一个链接。                                                          | 按列表顺序从 `@image_1` 开始编号，或补上缺少的图片。                       |
| 400 `elements[0].name "image_1" is not a name Kling V4 accepts`           | 用了保留名，或名字里有空格、连字符等符号。                                                               | 使用 1–20 个字母、数字、下划线或汉字，例如 `Bottle`。                     |
| 400 `"images[0]" is not a PNG or JPEG image: the URL returned image/webp` | 传了 WebP、GIF 或 HEIC 文件，或链接返回的是网页。                                                    | 把文件转成 JPEG 或 PNG，或用 `POST /v1/files` 上传后使用 `data.url`。 |
| 400 `field "output_format" is not supported by model kling-image-v4`      | 传了其他图片模型的字段（`output_format`、`seed`、`quality`、`size`、`background`、`enhance_prompt`）。 | 删掉该字段。                                                 |
| 任务 `failed`，错误为 `content_policy_violation`                                | 提示词、参考图或生成的图片未通过内容审核。                                                               | 修改提示词或图片。原样重试仍会失败；不收费。                                 |
| 任务 `failed`，错误为 `processing_timeout`                                      | 图片没有在处理时限内完成。                                                                       | 重试；失败的任务已退款。                                           |
| 从未充值的账户收到 403 `forbidden`                                                 | 赠送额度只覆盖部分模型。                                                                        | 充值一次，或改用赠送额度可用的模型。                                     |## HTTP 错误速查任务生成之前的错误会以非 2xx 响应返回，不扣费。请根据 `error.code` 或 `error.retryable` 判断处理方式；`message` 会指出问题所在。完整列表和重试策略见[错误码](/errors)。```json
{
  "error": {
    "code": "bad_request",
    "message": "\"prompt\" is required",
    "retryable": false,
    "request_id": "req_5f0c2a9e4b7d4e31"
  }
}
```| HTTP 状态码 | `error.code`                                                                                  | 处理方式                                                   |
| -------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------ |
| 400      | `bad_request`, `content_policy_violation`                                                     | 修改请求；message 会点名出错的字段。不要原样重试。                          |
| 401      | `missing_api_key`, `invalid_api_key`（旧版客户端可能看到 `unauthorized`）                                | 以 `Authorization: Bearer <key>` 发送有效的密钥。               |
| 402      | `insufficient_credits`                                                                        | 充值，或提高密钥的额度，然后重新发送。                                    |
| 403      | `forbidden`                                                                                   | 该密钥或账户不能使用此模型（例如免费额度只覆盖部分模型）。不要原样重试。                   |
| 404      | `not_found`                                                                                   | 在 `GET /v1/tasks/{task_id}` 上：该任务在此密钥所属账户下不存在。请检查 ID。  |
| 409      | `idempotency_conflict`                                                                        | 换一个新的 `Idempotency-Key`，或等待使用该键的第一个请求完成。               |
| 429      | `rate_limit_exceeded`                                                                         | 等待 `Retry-After` 秒（也见 `error.retry_after_seconds`）后重试。 |
| 500      | `internal_error`                                                                              | 退避重试；若持续出现，请带上 `request_id` 联系支持。                      |
| 503      | `processing_unavailable`, `processing_timeout`, `processing_failed`, `result_transfer_failed` | 未扣费。使用指数退避重试。                                          |

Reference: https://docs.beatapi.io/api-reference/image-api/kling-image-v4

## Authentication

- `Authorization` header (bearer token, required) — 通过 `Authorization: Bearer <BEATAPI_API_KEY>` 发送 API 密钥。

## Servers

- `https://api.beatapi.io` (Direct, default)
- `https://api.beatapi.io` (API)

## Request

### Headers

- `Idempotency-Key` (string, optional) — 请求体使用 JSON，并设置 `Content-Type: application/json`。`Idempotency-Key` 为可选：每个逻辑请求发送一个唯一值（最长 255 个字符），仅在重试完全相同的请求体时复用。24 小时内，用相同的键和请求体重试会再次返回第一次的响应，并带上 `Idempotent-Replayed: true`；相同的键搭配不同的请求体则返回 `409 idempotency_conflict`。非 2xx 的响应不会被保存，因此 400 或 402 之后的重试会重新执行。

### Body (application/json)

This endpoint expects a KlingImageV4Request.

- `model` (enum, required) — 要调用的模型。 **取值**：`kling-image-v4` **取值有误时** - 未传：`"model" is required` - 模型 ID 不存在：`"model" kling-image-v9 is not catalogued` - 把视频模型发到了这个端点：`"model" kling-v4 is served by POST /v1/videos/tasks, not this endpoint`
  - Allowed values: `kling-image-v4`
- `prompt` (string, required) — 要画什么，或要在参考图上改什么：主体、风格、光线、构图以及必须出现在图中的文字，并用 `@` 引用逐一指明各个输入。 **长度**：1–20000 个字符 - 长度按字符计（一个中日韩文字算一个字符）。 - 引用方式：`images` 按列表顺序写作 `@image_1`、`@image_2` …，元素写作 `@` 加它的 `name`。 - 每个 `@image_N` 都必须对应同一请求中的一张图。只传两张图却写了 `@image_3`，会在创建任务时被拒绝。 **取值有误时** - 未传：`"prompt" is required` - 为空或超过长度上限：`"prompt" has an unsupported length` - 引用了请求中没有的图片：`the prompt names @image_3, which this request does not send`
- `aspect_ratio` (enum, optional, default: auto) — 图片的宽高比，写作 宽:高。 **可选值**：`auto`, `1:1`, `16:9`, `9:16`, `4:3`, `3:4`, `3:2`, `2:3`, `21:9` **默认值**：`auto` - 不传时使用 `auto`：由模型根据提示词和输入图决定画幅。对画面形状有要求时请明确传比例。 **取值有误时** - 取值不在列表中：`"aspect_ratio" must be one of: [auto 1:1 16:9 9:16 4:3 3:4 3:2 2:3 21:9]`
  - Allowed values: `auto`, `1:1`, `16:9`, `9:16`, `4:3`, `3:4`, `3:2`, `2:3`, `21:9`
- `elements` (list of KlingImageV4RequestElementsItems, optional) — 命名主体，例如角色、动物、道具、服装或场景。每个元素用 2–4 张图片表示，在提示词中写作 `@` 加它的 `name`。 **数量**：≤ 10 * 对象数组。每个对象只接受以下键： * `elements[].name`（字符串，必填）：1–20 个字母、数字、下划线或汉字，同一请求内不区分大小写不得重复；不能是 `image_N`、`video_N`、`voice_N`、`keyframe_N`、`object_N`、`audio_N`、`first_frame` 或 `last_frame`。 * `elements[].element_input_urls`（字符串数组，必填）：2–4 个指向该元素图片的公网 HTTPS 链接，第一张是主视图。 * `elements[].tag`（字符串，可选）：元素的类别。 * `elements[].description`（字符串，可选）：元素说明，最多 100 个字符。 * 元素只能由图片组成：本模型不接受视频元素和带声音的元素。 * `images` 与 `elements` 合计最多 10 个。每个元素给任务加一笔固定费用，与它包含几张图无关。 **取值有误时** * 多于 10 个元素：`"elements" accepts at most 10 items` * 元素不是对象：`"elements[0]" must be an object` * 元素缺少 `name`：`"name" is required in "elements[0]"` * 元素缺少 `element_input_urls`：`"element_input_urls" is required in "elements[0]"` * `name` 为空或超过 20 个字符：`"elements[0].name" has an unsupported length` * `name` 含其他字符，或是保留名：`elements[0].name "image_1" is not a name Kling V4 accepts` * 同一个 `name` 出现两次（不区分大小写）：`elements[1].name "Hero" is used twice` * 图片少于两张：`"elements[0].element_input_urls" requires at least 2 item` * 图片多于四张：`"elements[0].element_input_urls" accepts at most 4 items` * `tag` 不在列表中：`"elements[0].tag" must be one of: [character animal prop costume scene effect others]` * `description` 超过 100 个字符：`"elements[0].description" has an unsupported length` * 元素里有不接受的键，例如视频：`field "element_input_video_urls" is not supported in "elements[0]"` **示例** ```json "elements": [ { "name": "Bottle", "tag": "prop", "description": "A matte smart water bottle", "element_input_urls": [ "https://your-cdn.example.com/bottle-front.png", "https://your-cdn.example.com/bottle-side.png" ] } ] ```
- `images` (list of string, optional) — 要编辑或合成的参考图。在提示词中按列表顺序写作 `@image_1`、`@image_2` …。 **数量**：1–10 每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。 - 每一项都必须是指向 JPEG 或 PNG 文件的公网 `https://` 链接。创建任务时，BeatAPI 会读取每个链接；不是这类图片或超出下方限制的，会按位置指出并拒绝（`images[0]` 是第一个链接）。 - `images` 与 `elements` 合计最多 10 个。 - 每个链接都会给任务加一笔固定费用（见计费）。 **取值有误时** - 超过上限：`"images" accepts at most 10 items` - 空数组：`"images" requires at least 1 item` - 不是 https:// 链接：`"images[0]" must be a public HTTPS URL` - 链接不是 JPEG 或 PNG 文件（此例为 WebP）：`"images[0]" is not a PNG or JPEG image: the URL returned image/webp` - 链接返回错误：`"images[0]" could not be downloaded: the URL returned HTTP 404` - 图片与元素合计超过 10 个：`Kling Image 4.0 takes at most 10 images and elements together` **示例** ```json "images": [ "https://cdn.beatapi.io/samples/smart-bottle.png", "https://cdn.beatapi.io/samples/neon-singer.png" ] ```
- `n` (integer, optional, default: 1) — 本任务要生成的图片张数。每张都使用相同的提示词、输入、比例和档位。 **默认值**：`1` **范围**：1–9 - 不传时为 `1`。 - 每张图按 `resolution` 的价格计费，所以 `n` 会成倍放大图片部分的价格；参考图和元素的费用每个任务只计一次，不按张数重复计。 - 按交付的图片张数计费。 **取值有误时** - 超出范围、不是整数，或以字符串传入：`"n" is outside its supported range`
- `resolution` (enum, optional, default: 2K) — 图片的尺寸档位：`2K`、`4K` 或 `8K`。每档每张单独定价。 **可选值**：`2K`, `4K`, `8K` **默认值**：`2K` - 不传时使用并按 `2K` 计费。 - 2K 和 4K 返回 PNG，8K 返回 JPEG。 - K 必须大写：`2k` 会被拒绝。没有 1K 档，也不接受 `2048x2048` 这样的像素尺寸。 **取值有误时** - 取值不在列表中（例如 `1K` 或 `2k`）：`"resolution" must be one of: [2K 4K 8K]`
  - Allowed values: `2K`, `4K`, `8K`

## Response

### 201

任务对象。任务成功之前 `output` 为 `null`。标注“运行中”的字段会在任务结束后消失。

- `map from string to any`

## Errors

### 400 Bad Request Error

`bad_request`, `content_policy_violation` 修改请求；message 会点名出错的字段。不要原样重试。

- `map from string to any`

### 401 Unauthorized Error

`missing_api_key`, `invalid_api_key`（旧版客户端可能看到 `unauthorized`） 以 `Authorization: Bearer <key>` 发送有效的密钥。

- `map from string to any`

### 402 Payment Required Error

`insufficient_credits` 充值，或提高密钥的额度，然后重新发送。

- `map from string to any`

### 403 Forbidden Error

`forbidden` 该密钥或账户不能使用此模型（例如免费额度只覆盖部分模型）。不要原样重试。

- `map from string to any`

### 409 Conflict Error

`idempotency_conflict` 换一个新的 `Idempotency-Key`，或等待使用该键的第一个请求完成。

- `map from string to any`

### 429 Too Many Requests Error

`rate_limit_exceeded` 等待 `Retry-After` 秒（也见 `error.retry_after_seconds`）后重试。

- `map from string to any`

### 500 Internal Server Error

`internal_error` 退避重试；若持续出现，请带上 `request_id` 联系支持。

- `map from string to any`

### 503 Service Unavailable Error

`processing_unavailable`, `processing_timeout`, `processing_failed`, `result_transfer_failed` 未扣费。使用指数退避重试。

- `map from string to any`

## Types

### KlingImageV4RequestElementsItems

- `element_input_urls` (list of string, required) — `elements[].element_input_urls`（字符串数组，必填）：2–4 个指向该元素图片的公网 HTTPS 链接，第一张是主视图。 **数量**：2–4 每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。
- `name` (string, required) — `elements[].name`（字符串，必填）：1–20 个字母、数字、下划线或汉字，同一请求内不区分大小写不得重复；不能是 `image_N`、`video_N`、`voice_N`、`keyframe_N`、`object_N`、`audio_N`、`first_frame` 或 `last_frame`。 **长度**：1–20 个字符
- `description` (string, optional) — `elements[].description`（字符串，可选）：元素说明，最多 100 个字符。 **长度**：≤ 100 个字符
- `tag` (enum, optional) — `elements[].tag`（字符串，可选）：元素的类别。 **可选值**：`character`, `animal`, `prop`, `costume`, `scene`, `effect`, `others`
  - Allowed values: `character`, `animal`, `prop`, `costume`, `scene`, `effect`, `others`

## Examples

### 文生图

**Request**

```json
{
  "model": "kling-image-v4",
  "prompt": "A cinematic storefront campaign image at blue hour, warm light spilling from the windows onto wet pavement",
  "aspect_ratio": "16:9",
  "resolution": "2K"
}
```

**Response**

```json
{
  "data": {
    "capability_id": "kling-image-v4",
    "capability_version": 1,
    "completed_at": null,
    "created_at": 1791993600,
    "error_code": null,
    "error_message": null,
    "id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
    "media_type": "image",
    "model": "kling-image-v4",
    "object": "task",
    "output": null,
    "poll_after_seconds": 5,
    "request_id": "req_5f0c2a9e4b7d4e31",
    "stage": "queued",
    "status": "queued",
    "task_kind": "image",
    "updated_at": 1791993600,
    "usage": {
      "credits_charged": 0.0593,
      "credits_refunded": 0,
      "credits_reserved": 0.0593,
      "credits_settled": 0
    }
  }
}
```

**SDK Code**

```python 文生图
import requests

url = "https://api.beatapi.io/v1/images/tasks"

payload = {
    "model": "kling-image-v4",
    "prompt": "A cinematic storefront campaign image at blue hour, warm light spilling from the windows onto wet pavement",
    "aspect_ratio": "16:9",
    "resolution": "2K"
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript 文生图
const url = 'https://api.beatapi.io/v1/images/tasks';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"kling-image-v4","prompt":"A cinematic storefront campaign image at blue hour, warm light spilling from the windows onto wet pavement","aspect_ratio":"16:9","resolution":"2K"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go 文生图
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.beatapi.io/v1/images/tasks"

	payload := strings.NewReader("{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"A cinematic storefront campaign image at blue hour, warm light spilling from the windows onto wet pavement\",\n  \"aspect_ratio\": \"16:9\",\n  \"resolution\": \"2K\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby 文生图
require 'uri'
require 'net/http'

url = URI("https://api.beatapi.io/v1/images/tasks")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"A cinematic storefront campaign image at blue hour, warm light spilling from the windows onto wet pavement\",\n  \"aspect_ratio\": \"16:9\",\n  \"resolution\": \"2K\"\n}"

response = http.request(request)
puts response.read_body
```

```java 文生图
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.beatapi.io/v1/images/tasks")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"A cinematic storefront campaign image at blue hour, warm light spilling from the windows onto wet pavement\",\n  \"aspect_ratio\": \"16:9\",\n  \"resolution\": \"2K\"\n}")
  .asString();
```

```php 文生图
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.beatapi.io/v1/images/tasks', [
  'body' => '{
  "model": "kling-image-v4",
  "prompt": "A cinematic storefront campaign image at blue hour, warm light spilling from the windows onto wet pavement",
  "aspect_ratio": "16:9",
  "resolution": "2K"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp 文生图
using RestSharp;

var client = new RestClient("https://api.beatapi.io/v1/images/tasks");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"A cinematic storefront campaign image at blue hour, warm light spilling from the windows onto wet pavement\",\n  \"aspect_ratio\": \"16:9\",\n  \"resolution\": \"2K\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 文生图
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "kling-image-v4",
  "prompt": "A cinematic storefront campaign image at blue hour, warm light spilling from the windows onto wet pavement",
  "aspect_ratio": "16:9",
  "resolution": "2K"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.beatapi.io/v1/images/tasks")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

### 一个任务出四张

**Request**

```json
{
  "model": "kling-image-v4",
  "prompt": "A minimalist poster of a lighthouse on a cliff at dawn, soft pastel colours, generous empty sky",
  "aspect_ratio": "3:4",
  "n": 4,
  "resolution": "4K"
}
```

**Response**

```json
{
  "data": {
    "capability_id": "kling-image-v4",
    "capability_version": 1,
    "completed_at": null,
    "created_at": 1791993600,
    "error_code": null,
    "error_message": null,
    "id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
    "media_type": "image",
    "model": "kling-image-v4",
    "object": "task",
    "output": null,
    "poll_after_seconds": 5,
    "request_id": "req_5f0c2a9e4b7d4e31",
    "stage": "queued",
    "status": "queued",
    "task_kind": "image",
    "updated_at": 1791993600
  }
}
```

**SDK Code**

```python 一个任务出四张
import requests

url = "https://api.beatapi.io/v1/images/tasks"

payload = {
    "model": "kling-image-v4",
    "prompt": "A minimalist poster of a lighthouse on a cliff at dawn, soft pastel colours, generous empty sky",
    "aspect_ratio": "3:4",
    "n": 4,
    "resolution": "4K"
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript 一个任务出四张
const url = 'https://api.beatapi.io/v1/images/tasks';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"kling-image-v4","prompt":"A minimalist poster of a lighthouse on a cliff at dawn, soft pastel colours, generous empty sky","aspect_ratio":"3:4","n":4,"resolution":"4K"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go 一个任务出四张
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.beatapi.io/v1/images/tasks"

	payload := strings.NewReader("{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"A minimalist poster of a lighthouse on a cliff at dawn, soft pastel colours, generous empty sky\",\n  \"aspect_ratio\": \"3:4\",\n  \"n\": 4,\n  \"resolution\": \"4K\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby 一个任务出四张
require 'uri'
require 'net/http'

url = URI("https://api.beatapi.io/v1/images/tasks")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"A minimalist poster of a lighthouse on a cliff at dawn, soft pastel colours, generous empty sky\",\n  \"aspect_ratio\": \"3:4\",\n  \"n\": 4,\n  \"resolution\": \"4K\"\n}"

response = http.request(request)
puts response.read_body
```

```java 一个任务出四张
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.beatapi.io/v1/images/tasks")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"A minimalist poster of a lighthouse on a cliff at dawn, soft pastel colours, generous empty sky\",\n  \"aspect_ratio\": \"3:4\",\n  \"n\": 4,\n  \"resolution\": \"4K\"\n}")
  .asString();
```

```php 一个任务出四张
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.beatapi.io/v1/images/tasks', [
  'body' => '{
  "model": "kling-image-v4",
  "prompt": "A minimalist poster of a lighthouse on a cliff at dawn, soft pastel colours, generous empty sky",
  "aspect_ratio": "3:4",
  "n": 4,
  "resolution": "4K"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp 一个任务出四张
using RestSharp;

var client = new RestClient("https://api.beatapi.io/v1/images/tasks");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"A minimalist poster of a lighthouse on a cliff at dawn, soft pastel colours, generous empty sky\",\n  \"aspect_ratio\": \"3:4\",\n  \"n\": 4,\n  \"resolution\": \"4K\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 一个任务出四张
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "kling-image-v4",
  "prompt": "A minimalist poster of a lighthouse on a cliff at dawn, soft pastel colours, generous empty sky",
  "aspect_ratio": "3:4",
  "n": 4,
  "resolution": "4K"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.beatapi.io/v1/images/tasks")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

### 编辑一张图片

**Request**

```json
{
  "model": "kling-image-v4",
  "prompt": "Keep the bottle in @image_1 exactly as it is. Place it on a sunlit kitchen counter with a soft reflection under it.",
  "images": [
    "https://cdn.beatapi.io/samples/smart-bottle.png"
  ],
  "resolution": "2K"
}
```

**Response**

```json
{
  "data": {
    "capability_id": "kling-image-v4",
    "capability_version": 1,
    "completed_at": null,
    "created_at": 1791993600,
    "error_code": null,
    "error_message": null,
    "id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
    "media_type": "image",
    "model": "kling-image-v4",
    "object": "task",
    "output": null,
    "poll_after_seconds": 5,
    "request_id": "req_5f0c2a9e4b7d4e31",
    "stage": "queued",
    "status": "queued",
    "task_kind": "image",
    "updated_at": 1791993600
  }
}
```

**SDK Code**

```python 编辑一张图片
import requests

url = "https://api.beatapi.io/v1/images/tasks"

payload = {
    "model": "kling-image-v4",
    "prompt": "Keep the bottle in @image_1 exactly as it is. Place it on a sunlit kitchen counter with a soft reflection under it.",
    "images": ["https://cdn.beatapi.io/samples/smart-bottle.png"],
    "resolution": "2K"
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript 编辑一张图片
const url = 'https://api.beatapi.io/v1/images/tasks';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"kling-image-v4","prompt":"Keep the bottle in @image_1 exactly as it is. Place it on a sunlit kitchen counter with a soft reflection under it.","images":["https://cdn.beatapi.io/samples/smart-bottle.png"],"resolution":"2K"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go 编辑一张图片
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.beatapi.io/v1/images/tasks"

	payload := strings.NewReader("{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"Keep the bottle in @image_1 exactly as it is. Place it on a sunlit kitchen counter with a soft reflection under it.\",\n  \"images\": [\n    \"https://cdn.beatapi.io/samples/smart-bottle.png\"\n  ],\n  \"resolution\": \"2K\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby 编辑一张图片
require 'uri'
require 'net/http'

url = URI("https://api.beatapi.io/v1/images/tasks")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"Keep the bottle in @image_1 exactly as it is. Place it on a sunlit kitchen counter with a soft reflection under it.\",\n  \"images\": [\n    \"https://cdn.beatapi.io/samples/smart-bottle.png\"\n  ],\n  \"resolution\": \"2K\"\n}"

response = http.request(request)
puts response.read_body
```

```java 编辑一张图片
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.beatapi.io/v1/images/tasks")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"Keep the bottle in @image_1 exactly as it is. Place it on a sunlit kitchen counter with a soft reflection under it.\",\n  \"images\": [\n    \"https://cdn.beatapi.io/samples/smart-bottle.png\"\n  ],\n  \"resolution\": \"2K\"\n}")
  .asString();
```

```php 编辑一张图片
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.beatapi.io/v1/images/tasks', [
  'body' => '{
  "model": "kling-image-v4",
  "prompt": "Keep the bottle in @image_1 exactly as it is. Place it on a sunlit kitchen counter with a soft reflection under it.",
  "images": [
    "https://cdn.beatapi.io/samples/smart-bottle.png"
  ],
  "resolution": "2K"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp 编辑一张图片
using RestSharp;

var client = new RestClient("https://api.beatapi.io/v1/images/tasks");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"Keep the bottle in @image_1 exactly as it is. Place it on a sunlit kitchen counter with a soft reflection under it.\",\n  \"images\": [\n    \"https://cdn.beatapi.io/samples/smart-bottle.png\"\n  ],\n  \"resolution\": \"2K\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 编辑一张图片
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "kling-image-v4",
  "prompt": "Keep the bottle in @image_1 exactly as it is. Place it on a sunlit kitchen counter with a soft reflection under it.",
  "images": ["https://cdn.beatapi.io/samples/smart-bottle.png"],
  "resolution": "2K"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.beatapi.io/v1/images/tasks")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

### 合成多张图片

**Request**

```json
{
  "model": "kling-image-v4",
  "prompt": "Place the bottle from @image_1 on a neon-lit stage like the one in @image_2. Keep the bottle label readable.",
  "aspect_ratio": "16:9",
  "images": [
    "https://cdn.beatapi.io/samples/smart-bottle.png",
    "https://cdn.beatapi.io/samples/neon-singer.png"
  ],
  "resolution": "2K"
}
```

**Response**

```json
{
  "data": {
    "capability_id": "kling-image-v4",
    "capability_version": 1,
    "completed_at": null,
    "created_at": 1791993600,
    "error_code": null,
    "error_message": null,
    "id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
    "media_type": "image",
    "model": "kling-image-v4",
    "object": "task",
    "output": null,
    "poll_after_seconds": 5,
    "request_id": "req_5f0c2a9e4b7d4e31",
    "stage": "queued",
    "status": "queued",
    "task_kind": "image",
    "updated_at": 1791993600
  }
}
```

**SDK Code**

```python 合成多张图片
import requests

url = "https://api.beatapi.io/v1/images/tasks"

payload = {
    "model": "kling-image-v4",
    "prompt": "Place the bottle from @image_1 on a neon-lit stage like the one in @image_2. Keep the bottle label readable.",
    "aspect_ratio": "16:9",
    "images": ["https://cdn.beatapi.io/samples/smart-bottle.png", "https://cdn.beatapi.io/samples/neon-singer.png"],
    "resolution": "2K"
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript 合成多张图片
const url = 'https://api.beatapi.io/v1/images/tasks';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"kling-image-v4","prompt":"Place the bottle from @image_1 on a neon-lit stage like the one in @image_2. Keep the bottle label readable.","aspect_ratio":"16:9","images":["https://cdn.beatapi.io/samples/smart-bottle.png","https://cdn.beatapi.io/samples/neon-singer.png"],"resolution":"2K"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go 合成多张图片
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.beatapi.io/v1/images/tasks"

	payload := strings.NewReader("{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"Place the bottle from @image_1 on a neon-lit stage like the one in @image_2. Keep the bottle label readable.\",\n  \"aspect_ratio\": \"16:9\",\n  \"images\": [\n    \"https://cdn.beatapi.io/samples/smart-bottle.png\",\n    \"https://cdn.beatapi.io/samples/neon-singer.png\"\n  ],\n  \"resolution\": \"2K\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby 合成多张图片
require 'uri'
require 'net/http'

url = URI("https://api.beatapi.io/v1/images/tasks")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"Place the bottle from @image_1 on a neon-lit stage like the one in @image_2. Keep the bottle label readable.\",\n  \"aspect_ratio\": \"16:9\",\n  \"images\": [\n    \"https://cdn.beatapi.io/samples/smart-bottle.png\",\n    \"https://cdn.beatapi.io/samples/neon-singer.png\"\n  ],\n  \"resolution\": \"2K\"\n}"

response = http.request(request)
puts response.read_body
```

```java 合成多张图片
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.beatapi.io/v1/images/tasks")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"Place the bottle from @image_1 on a neon-lit stage like the one in @image_2. Keep the bottle label readable.\",\n  \"aspect_ratio\": \"16:9\",\n  \"images\": [\n    \"https://cdn.beatapi.io/samples/smart-bottle.png\",\n    \"https://cdn.beatapi.io/samples/neon-singer.png\"\n  ],\n  \"resolution\": \"2K\"\n}")
  .asString();
```

```php 合成多张图片
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.beatapi.io/v1/images/tasks', [
  'body' => '{
  "model": "kling-image-v4",
  "prompt": "Place the bottle from @image_1 on a neon-lit stage like the one in @image_2. Keep the bottle label readable.",
  "aspect_ratio": "16:9",
  "images": [
    "https://cdn.beatapi.io/samples/smart-bottle.png",
    "https://cdn.beatapi.io/samples/neon-singer.png"
  ],
  "resolution": "2K"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp 合成多张图片
using RestSharp;

var client = new RestClient("https://api.beatapi.io/v1/images/tasks");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"Place the bottle from @image_1 on a neon-lit stage like the one in @image_2. Keep the bottle label readable.\",\n  \"aspect_ratio\": \"16:9\",\n  \"images\": [\n    \"https://cdn.beatapi.io/samples/smart-bottle.png\",\n    \"https://cdn.beatapi.io/samples/neon-singer.png\"\n  ],\n  \"resolution\": \"2K\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 合成多张图片
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "kling-image-v4",
  "prompt": "Place the bottle from @image_1 on a neon-lit stage like the one in @image_2. Keep the bottle label readable.",
  "aspect_ratio": "16:9",
  "images": ["https://cdn.beatapi.io/samples/smart-bottle.png", "https://cdn.beatapi.io/samples/neon-singer.png"],
  "resolution": "2K"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.beatapi.io/v1/images/tasks")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

### 命名元素

**Request**

```json
{
  "model": "kling-image-v4",
  "prompt": "A product shot of @Bottle on a marble bathroom shelf beside folded towels, morning light",
  "aspect_ratio": "1:1",
  "elements": [
    {
      "element_input_urls": [
        "https://your-cdn.example.com/bottle-front.png",
        "https://your-cdn.example.com/bottle-side.png"
      ],
      "name": "Bottle",
      "tag": "prop"
    }
  ],
  "resolution": "2K"
}
```

**Response**

```json
{
  "data": {
    "capability_id": "kling-image-v4",
    "capability_version": 1,
    "completed_at": null,
    "created_at": 1791993600,
    "error_code": null,
    "error_message": null,
    "id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
    "media_type": "image",
    "model": "kling-image-v4",
    "object": "task",
    "output": null,
    "poll_after_seconds": 5,
    "request_id": "req_5f0c2a9e4b7d4e31",
    "stage": "queued",
    "status": "queued",
    "task_kind": "image",
    "updated_at": 1791993600
  }
}
```

**SDK Code**

```python 命名元素
import requests

url = "https://api.beatapi.io/v1/images/tasks"

payload = {
    "model": "kling-image-v4",
    "prompt": "A product shot of @Bottle on a marble bathroom shelf beside folded towels, morning light",
    "aspect_ratio": "1:1",
    "elements": [
        {
            "element_input_urls": ["https://your-cdn.example.com/bottle-front.png", "https://your-cdn.example.com/bottle-side.png"],
            "name": "Bottle",
            "tag": "prop"
        }
    ],
    "resolution": "2K"
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript 命名元素
const url = 'https://api.beatapi.io/v1/images/tasks';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"kling-image-v4","prompt":"A product shot of @Bottle on a marble bathroom shelf beside folded towels, morning light","aspect_ratio":"1:1","elements":[{"element_input_urls":["https://your-cdn.example.com/bottle-front.png","https://your-cdn.example.com/bottle-side.png"],"name":"Bottle","tag":"prop"}],"resolution":"2K"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go 命名元素
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.beatapi.io/v1/images/tasks"

	payload := strings.NewReader("{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"A product shot of @Bottle on a marble bathroom shelf beside folded towels, morning light\",\n  \"aspect_ratio\": \"1:1\",\n  \"elements\": [\n    {\n      \"element_input_urls\": [\n        \"https://your-cdn.example.com/bottle-front.png\",\n        \"https://your-cdn.example.com/bottle-side.png\"\n      ],\n      \"name\": \"Bottle\",\n      \"tag\": \"prop\"\n    }\n  ],\n  \"resolution\": \"2K\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby 命名元素
require 'uri'
require 'net/http'

url = URI("https://api.beatapi.io/v1/images/tasks")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"A product shot of @Bottle on a marble bathroom shelf beside folded towels, morning light\",\n  \"aspect_ratio\": \"1:1\",\n  \"elements\": [\n    {\n      \"element_input_urls\": [\n        \"https://your-cdn.example.com/bottle-front.png\",\n        \"https://your-cdn.example.com/bottle-side.png\"\n      ],\n      \"name\": \"Bottle\",\n      \"tag\": \"prop\"\n    }\n  ],\n  \"resolution\": \"2K\"\n}"

response = http.request(request)
puts response.read_body
```

```java 命名元素
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.beatapi.io/v1/images/tasks")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"A product shot of @Bottle on a marble bathroom shelf beside folded towels, morning light\",\n  \"aspect_ratio\": \"1:1\",\n  \"elements\": [\n    {\n      \"element_input_urls\": [\n        \"https://your-cdn.example.com/bottle-front.png\",\n        \"https://your-cdn.example.com/bottle-side.png\"\n      ],\n      \"name\": \"Bottle\",\n      \"tag\": \"prop\"\n    }\n  ],\n  \"resolution\": \"2K\"\n}")
  .asString();
```

```php 命名元素
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.beatapi.io/v1/images/tasks', [
  'body' => '{
  "model": "kling-image-v4",
  "prompt": "A product shot of @Bottle on a marble bathroom shelf beside folded towels, morning light",
  "aspect_ratio": "1:1",
  "elements": [
    {
      "element_input_urls": [
        "https://your-cdn.example.com/bottle-front.png",
        "https://your-cdn.example.com/bottle-side.png"
      ],
      "name": "Bottle",
      "tag": "prop"
    }
  ],
  "resolution": "2K"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp 命名元素
using RestSharp;

var client = new RestClient("https://api.beatapi.io/v1/images/tasks");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"kling-image-v4\",\n  \"prompt\": \"A product shot of @Bottle on a marble bathroom shelf beside folded towels, morning light\",\n  \"aspect_ratio\": \"1:1\",\n  \"elements\": [\n    {\n      \"element_input_urls\": [\n        \"https://your-cdn.example.com/bottle-front.png\",\n        \"https://your-cdn.example.com/bottle-side.png\"\n      ],\n      \"name\": \"Bottle\",\n      \"tag\": \"prop\"\n    }\n  ],\n  \"resolution\": \"2K\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 命名元素
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "kling-image-v4",
  "prompt": "A product shot of @Bottle on a marble bathroom shelf beside folded towels, morning light",
  "aspect_ratio": "1:1",
  "elements": [
    [
      "element_input_urls": ["https://your-cdn.example.com/bottle-front.png", "https://your-cdn.example.com/bottle-side.png"],
      "name": "Bottle",
      "tag": "prop"
    ]
  ],
  "resolution": "2K"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.beatapi.io/v1/images/tasks")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```