> 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 V4 Flash

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

通过文字、首帧，或最多 10 张参考图和 5 段参考视频，生成 3–20 秒、带生成声音的 720p 视频：更快、更便宜的可灵 4.0。- 异步：创建接口返回任务 ID，任务成功后拿到视频。
- 三种输入方式：纯文字、一张首帧，或参考素材（图片和视频）。首帧和参考素材不能同时使用。
- 输出固定 720p，时长 3–20 秒，自带生成的声音。
- 按视频秒数计价；带参考视频的请求按更多秒数、更低的每秒单价计价。任务失败不收费。POST/v1/videos/tasks试一试在调试窗口里打开本模型，填入你的 BeatAPI API 密钥即可创建任务。调用是真实的，费用从你自己的余额中扣除。## 接口与鉴权`POST https://api.beatapi.io/v1/videos/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 之后的重试会重新执行。## 请求流程1) **创建任务** 向接口 `POST` 下方的参数。返回 `201` 表示任务已被接受，其价格已从你的余额中预留；任务在后台运行。保存 `data.id`。
2) **等待任务完成** 调用 `GET /v1/tasks/{task_id}`，两次调用之间等待 `data.poll_after_seconds` 秒（图片 5 秒，视频 8 秒），直到 `status` 为 `succeeded` 或 `failed`。也可以为 `task.succeeded` 和 `task.failed` 注册 [Webhook](/webhooks)；仍需保留轮询作为兜底，因为因处理超时而终止的任务不会发送事件。
3) **保存结果** 状态为 `succeeded` 时，下载每个 `data.output.media[].url` 并保存你需要的文件；BeatAPI 不承诺结果链接的保留时长。状态为 `failed` 时，读取 `data.error_code` 和 `data.error_message`：预扣的金额已退回你的余额，`data.retryable` 表示再次发送相同请求是否可能成功。## 输入模式| 模式   | 必填输入                                                            | 说明                        |
| ---- | --------------------------------------------------------------- | ------------------------- |
| 文生视频 | `model`、`prompt`                                                | 不要传任何素材数组。                |
| 首帧   | `model`、`prompt`、`images`（1 个链接）                                | 视频从这张图开始，并沿用它的画幅比例。不支持尾帧。 |
| 参考素材 | `model`、`prompt`，以及 `reference_images`、`reference_videos` 中至少一个 | 不能和 `images` 一起用。         |## 请求参数### `model``string` · 必需要运行的模型。**取值**：`kling-v4-flash`**取值有误时**- 缺少：`"model" is required`
- 把图片模型发到了这个接口：`"model" nano-banana-2 is served by POST /v1/images/tasks, not this endpoint`### `prompt``string` · 必需视频里发生什么：主体、动作、运镜和风格。用了参考素材时，用文字说明每个素材的用途。**长度**：1–5000 个字符- 长度按字符计（一个汉字算一个）。**取值有误时**- 缺少：`"prompt" is required`
- 为空或超过上限：`"prompt" has an unsupported length`### `images``string[]` · 可选首帧：视频从这张图开始。**数量**：1–1  \
每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。- 视频沿用这张图的画幅比例，所以带 `images` 时不要传 `aspect_ratio`。
- 不支持尾帧。只想用图片引导画面、不作为首帧时，请改用 `reference_images`。**取值有误时**- 超过一个链接：`"images" accepts at most 1 items`
- 同时传了任意 reference\_\* 字段：`Cannot combine "images" with reference inputs in one task`
- 不是 https\:// 链接：`"images[0]" must be a public HTTPS URL`### `reference_images``string[]` · 可选引导视频内容、人物、商品或风格的图片。**数量**：1–10  \
每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。- 按列表顺序使用；请在提示词里说明每张图的用途。**取值有误时**- 超过上限：`"reference_images" accepts at most 10 items`
- 和 `images` 一起传：`Cannot combine "images" with reference inputs in one task`### `reference_videos``string[]` · 可选用来参考动作、运镜或内容的视频。**数量**：1–5  \
每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。- 传公网 HTTPS 链接的 MP4 或 MOV 文件。
- 带参考视频的请求计价方式不同，见下方「计费」。**取值有误时**- 超过上限：`"reference_videos" accepts at most 5 items`### `duration``integer` · 可选 · 默认值: `5`视频时长，单位秒，整数。**默认值**：`5`  \
**范围**：3–20- 不传时按 `5` 发送。
- 价格按这个秒数计算。**取值有误时**- 超出范围或不是整数：`"duration" is outside its supported range`### `aspect_ratio``string` · 可选 · 默认值: `16:9`视频画幅，写成 宽:高。**可选值**：`16:9`, `9:16`, `1:1`, `21:9`  \
**默认值**：`16:9`- `images` 带首帧时不要传：视频沿用首帧的比例。没有 `images` 时默认 `16:9`。**取值有误时**- 和 `images` 一起传：`Kling V4 Flash takes the first frame's shape; do not send aspect_ratio with images`
- 取值不在列表里：`"aspect_ratio" must be one of: [16:9 9:16 1:1 21:9]`### `resolution``string` · 可选 · 默认值: `720p`输出分辨率。只有 `720p`，可以不传。**取值**：`720p`  \
**默认值**：`720p`**取值有误时**- 取值不在列表里（例如 `1080p`）：`"resolution" must be one of: [720p]`### `callback_url``string` · 可选任务成功或失败时通知的地址：公网 HTTPS URL，协议、主机和端口必须与你某个已启用的 [Webhook 端点](/webhooks)相同，并由该端点的 `secret` 签名。**长度**：≤ 2048 个字符- 请先用 `POST /v1/webhooks` 注册端点。BeatAPI 会推送 `task.succeeded` 或 `task.failed`，事件体、请求头和重试规则与账户 Webhook 相同；订阅了该事件的账户端点也会收到，与该端点地址完全相同时只通知一次。
- 签名端点被删除、停用或改到别的主机后，这条回调作废。**取值有误时**- 值不是字符串：`"callback_url" must be a string.`
- 地址超过 2048 个字符：`"callback_url" must be at most 2048 characters.`
- 不是 URL，或没有主机、没有 `http` 或 `https` 协议：`"callback_url" must be a valid https URL.`
- 使用了 `http`，或指向私有等非公网地址：`"callback_url" must be a public HTTPS URL.`
- 没有任何已启用的 Webhook 端点与之协议、主机和端口相同：`"callback_url" must be on the host of one of your active webhook endpoints, whose secret signs it; register one with POST /v1/webhooks.`网关还会在创建任务之前检查以下组合：- `images` 不能与参考素材字段同时使用。
- 一张图是首帧，视频沿用它的画幅，因此不能同时传 `aspect_ratio`；不支持尾帧。
- 首帧不能和 `reference_images` 或 `reference_videos` 一起传。
- 参考视频每段 2–20 秒，合计不超过 20 秒；不接受参考音频。
- 输出为 720p，并自带生成的声音。## 输入素材限制网关会在创建任务之前读取每一项输入，超出这些限制的输入会被拒绝，并返回点名该输入的 `400 bad_request`。不扣费。| 素材 | 创建任务前检查的限制                           |
| -- | ------------------------------------ |
| 图片 | 宽和高均为 300–65536 像素；宽高比（宽 ÷ 高）0.4–2.5 |
| 视频 | 每段 2–20 秒；合计不超过 20 秒                 |- 图片尺寸在宿主报告时检查。请用 JPEG、PNG 或 WebP；模型用不了的文件会在提交后以 `bad_request` 失败，任务全额退款。
- 参考视频须为 MP4 或 MOV，每段 2–20 秒，合计不超过 20 秒。
- 不接受参考音频。
- 本地文件？先用 `POST /v1/files` 上传，再传返回的 `data.url`。## 怎么写提示词描述镜头：主体、动作、运镜和风格。用了参考素材时，用文字说清每个素材的用途，例如「参考图里的瓶子」「运镜参考那段参考视频」。用首帧时，描述画面从这张图开始怎样变化。## 选 Kling V4 Flash 还是 Kling V4Kling V4 Flash 只出 720p、最长 20 秒，输入是文字、一张首帧或参考素材。需要 1080p、最长 30 秒、尾帧或中间帧、参考音频或命名元素时，请用 Kling V4。## 请求示例```bash title="cURL"
curl --request POST \
  --url https://api.beatapi.io/v1/videos/tasks \
  --header "Authorization: Bearer $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-v4-flash",
  "prompt": "A slow tracking shot through a rain-lit night market, neon reflections on wet stone",
  "duration": 5,
  "aspect_ratio": "16:9"
}'
``````python title="Python"
import os
import requests

response = requests.post(
    "https://api.beatapi.io/v1/videos/tasks",
    headers={"Authorization": f"Bearer {os.environ['BEATAPI_API_KEY']}"},
    json={
      "model": "kling-v4-flash",
      "prompt": "A slow tracking shot through a rain-lit night market, neon reflections on wet stone",
      "duration": 5,
      "aspect_ratio": "16:9"
    },
    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/videos/tasks', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.BEATAPI_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "model": "kling-v4-flash",
    "prompt": "A slow tracking shot through a rain-lit night market, neon reflections on wet stone",
    "duration": 5,
    "aspect_ratio": "16:9"
  }),
});
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);
```### 文生视频一段 5 秒、720p、横屏、带声音的视频。```bash
curl --request POST \
  --url https://api.beatapi.io/v1/videos/tasks \
  --header "Authorization: Bearer $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-v4-flash",
  "prompt": "A slow tracking shot through a rain-lit night market, neon reflections on wet stone",
  "duration": 5,
  "aspect_ratio": "16:9"
}'
```### 首帧视频从这张图开始，并保持它的画幅。```bash
curl --request POST \
  --url https://api.beatapi.io/v1/videos/tasks \
  --header "Authorization: Bearer $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-v4-flash",
  "prompt": "The singer turns to the camera and starts to sing as the stage lights sweep across the crowd",
  "images": [
    "https://cdn.beatapi.io/samples/neon-singer.png"
  ],
  "duration": 5
}'
```### 参考图一段跟随参考图的产品短片。```bash
curl --request POST \
  --url https://api.beatapi.io/v1/videos/tasks \
  --header "Authorization: Bearer $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-v4-flash",
  "prompt": "The bottle from the reference image turns slowly on a marble table, soft studio light, shallow depth of field",
  "reference_images": [
    "https://cdn.beatapi.io/samples/smart-bottle.png"
  ],
  "duration": 8,
  "aspect_ratio": "9:16"
}'
```### 参考图和参考视频把视频链接换成你自己的 MP4 或 MOV。```bash
curl --request POST \
  --url https://api.beatapi.io/v1/videos/tasks \
  --header "Authorization: Bearer $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-v4-flash",
  "prompt": "The bottle from the reference image on a turntable, with camera movement like the reference video",
  "reference_images": [
    "https://cdn.beatapi.io/samples/smart-bottle.png"
  ],
  "reference_videos": [
    "https://your-cdn.example.com/clips/source.mp4"
  ],
  "duration": 6
}'
```## 响应### 创建任务（201）任务对象。任务成功之前 `output` 为 `null`。标注“运行中”的字段会在任务结束后消失。```json
{
  "data": {
    "id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
    "object": "task",
    "task_kind": "video",
    "capability_id": "kling-v4-flash",
    "capability_version": 1,
    "media_type": "video",
    "model": "kling-v4-flash",
    "status": "queued",
    "stage": "queued",
    "created_at": 1791993600,
    "updated_at": 1791993600,
    "completed_at": null,
    "poll_after_seconds": 8,
    "output": null,
    "usage": {
      "credits_reserved": 0.3995,
      "credits_settled": 0,
      "credits_refunded": 0,
      "credits_charged": 0.3995,
      "billable_duration_seconds": 5
    },
    "request_id": "202611260732156684925978268d9d6yOLdMCKV",
    "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": "video",
    "capability_id": "kling-v4-flash",
    "capability_version": 1,
    "media_type": "video",
    "model": "kling-v4-flash",
    "status": "succeeded",
    "stage": "succeeded",
    "created_at": 1791993600,
    "updated_at": 1791993690,
    "completed_at": 1791993690,
    "output": {
      "media": [
        {
          "type": "video",
          "url": "https://media.beatapi.io/outputs/task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ/0.mp4",
          "mime_type": "video/mp4"
        }
      ],
      "url": "https://media.beatapi.io/outputs/task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ/0.mp4",
      "r2_url": "https://media.beatapi.io/outputs/task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ/0.mp4"
    },
    "usage": {
      "credits_reserved": 0.3995,
      "credits_settled": 0.3995,
      "credits_refunded": 0,
      "credits_charged": 0.3995,
      "billable_duration_seconds": 5
    },
    "request_id": "202611260732156684925978268d9d6yOLdMCKV",
    "error_code": null,
    "error_message": null
  }
}
```#### 输出字段| 字段                         | 类型         | 说明                                           |
| -------------------------- | ---------- | -------------------------------------------- |
| `output.media`             | `object[]` | 生成的文件；这个模型只有一个视频。                            |
| `output.media[].type`      | `string`   | 固定为 `video`。                                 |
| `output.media[].url`       | `string`   | 已存储视频的 HTTPS 链接。请下载保存，不承诺保留期限。               |
| `output.media[].mime_type` | `string`   | `video/mp4`。                                 |
| `output.url`               | `string`   | 主结果：视频链接。读结果看 `output.url`；`media[]` 列出全部输出。 |
| `output.r2_url`            | `string`   | `output.url` 的旧名，值相同；请读 `output.url`。        |### 任务失败失败的任务在 `GET /v1/tasks/{task_id}` 上仍然是 HTTP 200：失败信息在响应体里。预扣金额会全额退回，因此不会扣费。```json
{
  "data": {
    "id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
    "object": "task",
    "task_kind": "video",
    "capability_id": "kling-v4-flash",
    "capability_version": 1,
    "media_type": "video",
    "model": "kling-v4-flash",
    "status": "failed",
    "stage": "failed",
    "created_at": 1791993600,
    "updated_at": 1791993690,
    "completed_at": 1791993690,
    "output": null,
    "usage": {
      "credits_reserved": 0.3995,
      "credits_settled": 0,
      "credits_refunded": 0.3995,
      "credits_charged": 0,
      "billable_duration_seconds": 5
    },
    "retryable": true,
    "request_id": "202611260732156684925978268d9d6yOLdMCKV",
    "error_code": "processing_failed",
    "error_message": "The task failed during processing on our side. Retry; a failed task is refunded.",
    "error": {
      "code": "processing_failed",
      "message": "The task failed during processing on our side. Retry; a failed task is refunded.",
      "retryable": true
    }
  }
}
```| 字段                   | 类型        | 说明                                                                                                                                                                          |
| -------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `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.error`         | `object`  | 仅失败的任务才有：`code`、`message` 和 `retryable` 合成一个对象，值与 `data.error_code`、`data.error_message` 和 `data.retryable` 相同。                                                             |
| `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/videos/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-v4-flash",
  "prompt": "A slow tracking shot through a rain-lit night market, neon reflections on wet stone",
  "duration": 5,
  "aspect_ratio": "16:9"
})
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"])
```## 计费- 不带参考视频时，价格 = 请求的秒数（`duration`，不传为 5）× 每秒单价。输入方式和 `aspect_ratio` 不影响价格。
- 带参考视频时，计费秒数 = 输出秒数 + 参考视频总长与输出秒数中较长的一个，按列出的「带视频输入」较低每秒单价计价。
- 创建任务时预扣，按实测的参考视频时长结算；`data.usage.billable_duration_seconds` 显示计费依据的秒数。
- 任务失败（包括提交后被内容审核拒绝）全额退款。当前牌价，与[价格页](https://beatapi.io/pricing)一致。享有协商折扣的账户实付更低；任务的 `data.usage` 始终显示实际扣费金额。| 选项                   | 牌价（美元）    |
| -------------------- | --------- |
| 1 秒 · 720p           | \$0.0799  |
| 1 计费秒 · 720p · 有视频输入 | \$0.05355 |## 常见错误| 错误或现象                                                           | 原因                              | 处理方式                                            |
| --------------------------------------------------------------- | ------------------------------- | ----------------------------------------------- |
| 400 `"resolution" must be one of: [720p]`                       | 传了 `1080p` 或 `4K`。              | 传 `720p` 或不传 `resolution`。需要 1080p 请用 Kling V4。 |
| 400 `"duration" is outside its supported range`                 | 不是 3–20 的整数，或传成了字符串。            | 传整数，例如 `5`。                                     |
| 400 `"images" accepts at most 1 items`                          | 同时传了首帧和尾帧。                      | 只传一张首帧。需要尾帧请用 Kling V4。                         |
| 400 `Cannot combine "images" with reference inputs in one task` | 同一个请求里既有首帧又有 `reference_*`。     | 首帧和参考素材二选一。多张图片请都放进 `reference_images`。         |
| 任务 `failed`，原因 `content_policy_violation`                       | 提示词、输入或结果被内容审核拒绝（真人、公众人物、版权角色）。 | 修改输入。原样重试仍会失败；不收费。                              |## HTTP 错误速查任务生成之前的错误会以非 2xx 响应返回，不扣费。请根据 `error.code` 或 `error.retryable` 判断处理方式；`message` 会指出问题所在。完整列表和重试策略见[错误码](/errors)。```json
{
  "error": {
    "code": "bad_request",
    "message": "\"prompt\" is required",
    "retryable": false,
    "request_id": "202611260732156684925978268d9d6yOLdMCKV"
  }
}
```| 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/video-api/kling-v4-flash

## 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 KlingV4FlashVideoRequest.

- `model` (enum, required) — 要运行的模型。 **取值**：`kling-v4-flash` **取值有误时** - 缺少：`"model" is required` - 把图片模型发到了这个接口：`"model" nano-banana-2 is served by POST /v1/images/tasks, not this endpoint`
  - Allowed values: `kling-v4-flash`
- `prompt` (string, required) — 视频里发生什么：主体、动作、运镜和风格。用了参考素材时，用文字说明每个素材的用途。 **长度**：1–5000 个字符 - 长度按字符计（一个汉字算一个）。 **取值有误时** - 缺少：`"prompt" is required` - 为空或超过上限：`"prompt" has an unsupported length`
- `aspect_ratio` (enum, optional, default: 16:9) — 视频画幅，写成 宽:高。 **可选值**：`16:9`, `9:16`, `1:1`, `21:9` **默认值**：`16:9` - `images` 带首帧时不要传：视频沿用首帧的比例。没有 `images` 时默认 `16:9`。 **取值有误时** - 和 `images` 一起传：`Kling V4 Flash takes the first frame's shape; do not send aspect_ratio with images` - 取值不在列表里：`"aspect_ratio" must be one of: [16:9 9:16 1:1 21:9]`
  - Allowed values: `16:9`, `9:16`, `1:1`, `21:9`
- `duration` (integer, optional, default: 5) — 视频时长，单位秒，整数。 **默认值**：`5` **范围**：3–20 - 不传时按 `5` 发送。 - 价格按这个秒数计算。 **取值有误时** - 超出范围或不是整数：`"duration" is outside its supported range`
- `images` (list of string, optional) — 首帧：视频从这张图开始。 **数量**：1–1 每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。 - 视频沿用这张图的画幅比例，所以带 `images` 时不要传 `aspect_ratio`。 - 不支持尾帧。只想用图片引导画面、不作为首帧时，请改用 `reference_images`。 **取值有误时** - 超过一个链接：`"images" accepts at most 1 items` - 同时传了任意 reference_* 字段：`Cannot combine "images" with reference inputs in one task` - 不是 https:// 链接：`"images[0]" must be a public HTTPS URL`
- `reference_images` (list of string, optional) — 引导视频内容、人物、商品或风格的图片。 **数量**：1–10 每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。 - 按列表顺序使用；请在提示词里说明每张图的用途。 **取值有误时** - 超过上限：`"reference_images" accepts at most 10 items` - 和 `images` 一起传：`Cannot combine "images" with reference inputs in one task`
- `reference_videos` (list of string, optional) — 用来参考动作、运镜或内容的视频。 **数量**：1–5 每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。 - 传公网 HTTPS 链接的 MP4 或 MOV 文件。 - 带参考视频的请求计价方式不同，见下方「计费」。 **取值有误时** - 超过上限：`"reference_videos" accepts at most 5 items`
- `resolution` (enum, optional, default: 720p) — 输出分辨率。只有 `720p`，可以不传。 **取值**：`720p` **默认值**：`720p` **取值有误时** - 取值不在列表里（例如 `1080p`）：`"resolution" must be one of: [720p]`
  - Allowed values: `720p`
- `callback_url` (string, optional) — 任务成功或失败时通知的地址：公网 HTTPS URL，协议、主机和端口必须与你某个已启用的 [Webhook 端点](/webhooks)相同，并由该端点的 `secret` 签名。 **长度**：≤ 2048 个字符 - 请先用 `POST /v1/webhooks` 注册端点。BeatAPI 会推送 `task.succeeded` 或 `task.failed`，事件体、请求头和重试规则与账户 Webhook 相同；订阅了该事件的账户端点也会收到，与该端点地址完全相同时只通知一次。 - 签名端点被删除、停用或改到别的主机后，这条回调作废。 **取值有误时** - 值不是字符串：`"callback_url" must be a string.` - 地址超过 2048 个字符：`"callback_url" must be at most 2048 characters.` - 不是 URL，或没有主机、没有 `http` 或 `https` 协议：`"callback_url" must be a valid https URL.` - 使用了 `http`，或指向私有等非公网地址：`"callback_url" must be a public HTTPS URL.` - 没有任何已启用的 Webhook 端点与之协议、主机和端口相同：`"callback_url" must be on the host of one of your active webhook endpoints, whose secret signs it; register one with POST /v1/webhooks.`

## Response

### 201

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

- `data` (QueuedTask, required) — Accepted or current BeatAPI task state.

## 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

### QueuedTask

- `id` (string, required) — Stable BeatAPI task ID used for polling and support.
- `object` (enum, required) — Object discriminator; always `task`.
  - Allowed values: `task`
- `task_kind` (enum, required) — Public task family that determines which capability fields are present. `data` is a data capability run as a task (`data:web.research`), polled through `POST /v1/capabilities/run`.
  - Allowed values: `workflow`, `effect`, `image`, `video`, `audio`, `data`
- `capability_id` (string, required) — Stable BeatAPI workflow, Effect, generation model, or data capability ID (such as `web.research`) selected when the task was accepted.
- `capability_version` (integer, required) — Always `1`.
- `status` (enum, required) — Current task lifecycle status. Stop polling at `succeeded` or `failed`; Music Video can also require manual action.
  - Allowed values: `queued`, `processing`, `storyboard_ready`, `requires_action`, `editing`, `composing`, `succeeded`, `failed`
- `stage` (enum, required) — Always repeats `status`. Kept for compatibility; read `status`.
  - Allowed values: `queued`, `processing`, `storyboard_ready`, `requires_action`, `editing`, `composing`, `succeeded`, `failed`
- `created_at` (integer, required) — Unix timestamp when BeatAPI accepted the task.
- `updated_at` (integer, required) — Unix timestamp of the latest task update.
- `completed_at` (integer, required, nullable) — Terminal Unix timestamp, or null while work is in progress.
- `output` (QueuedTaskOutput, required, nullable) — Output is null until the task succeeds.
- `request_id` (string, required) — Correlation ID to retain for logs and BeatAPI support.
- `error_code` (string, required, nullable) — Machine-readable terminal failure code, or null when no task failure is recorded.
- `error_message` (string, required, nullable) — Human-readable terminal failure detail, or null when no task failure is recorded.
- `workflow` (enum, optional) — Present for workflow tasks; identifies the selected BeatAPI workflow.
  - Allowed values: `music-video`, `ecommerce-video`, `video-analysis`
- `effect_id` (string, optional) — Present for Effect tasks; stable selected Effect ID.
- `effect_version` (integer, optional) — Present for Effect tasks; immutable Effect version used for processing.
- `media_type` (enum, optional) — Present when task_kind is image or video.
  - Allowed values: `image`, `video`, `audio`
- `model` (string, optional) — Stable BeatAPI model alias. It is independent from internal execution routing.
- `storyboard` (Storyboard, optional) — Music Video storyboard metadata when available.
- `poll_after_seconds` (integer, optional) — Present while the task is running: how long to wait before the next status call (5 for images, 8 for video and Effects, 10 for workflows and data tasks). Follow it instead of a fixed interval. Absent on a terminal task.
- `typical_seconds` (QueuedTaskTypicalSeconds, optional) — Present while the task is running, when enough recent finishes exist: how long this task's model recently took from accepted to succeeded, measured on this gateway. Past `p90` with no change the task is running long; there is no ETA beyond that.
- `usage` (TaskUsage, optional) — USD reservation, settlement, refund, and optional billable duration for this task.
- `error` (QueuedTaskError, optional) — Present on a failed task: the terminal failure as one object. Its values are the same as the flat `error_code`, `error_message` and `retryable`, which stay.
- `retryable` (boolean, optional) — Present on a failed task: whether resubmitting could succeed. True when the task failed on our side or timed out (a failed task is not charged); false when it was refused for content or bad input. Same code-to-retryable rule as the error envelope.

### QueuedTaskOutput

Output is null until the task succeeds.

- QueuedTaskOutput0
- QueuedTaskOutput1
- QueuedTaskOutput2

### Storyboard

- `shots` (list of StoryboardShot, required) — Ordered Music Video storyboard shots. The array may be empty before storyboard generation completes.

### QueuedTaskTypicalSeconds

Present while the task is running, when enough recent finishes exist: how long this task's model recently took from accepted to succeeded, measured on this gateway. Past `p90` with no change the task is running long; there is no ETA beyond that.

- `p50` (integer, required) — Median seconds.
- `p90` (integer, required) — Ninetieth-percentile seconds.
- `samples` (integer, required) — Finished tasks the figures rest on.
- `window` (string, required) — The window measured, such as `7d`.

### TaskUsage

- `credits_reserved` (double, required) — USD amount reserved for this task. The compatibility field name is retained; 1 Credit equals $1 USD.
- `credits_charged` (double, required) — USD amount charged. `0` on a failed task, because the reserved amount was returned.
- `credits_settled` (double, required) — USD amount settled after successful work.
- `credits_refunded` (double, required) — USD amount returned after a failed task. On a failed task `credits_reserved` is the amount held at create, `credits_charged` and `credits_settled` are `0`, and `credits_refunded` is the amount returned.
- `billable_duration_seconds` (integer, optional) — Server-detected or request-declared billable duration used for USD calculation.

### QueuedTaskError

Present on a failed task: the terminal failure as one object. Its values are the same as the flat `error_code`, `error_message` and `retryable`, which stay.

- `code` (string, required) — Machine-readable failure code, the same value as `error_code`.
- `message` (string, required) — English sentence that states the cause, the same value as `error_message`.
- `retryable` (boolean, optional) — Whether resubmitting could succeed, the same value as `retryable`. Absent when `retryable` is absent.

### QueuedTaskOutput0

- `media` (list of QueuedTaskOutputOneOf0MediaItems, required) — BeatAPI-hosted result assets.
- `url` (string, required) — The primary asset's URL, the one to read when you want a single file (the first video, else the first image). The same value as `r2_url`.
- `r2_url` (string, required, deprecated) — Deprecated — read `url`. The same value as `url`, kept only for clients that already read it.
- `tracks` (list of QueuedTaskOutputOneOf0TracksItems, optional) — Audio tasks only. One entry for each song or stem the call made, beside the files in `media`.
- `data` (any, optional) — Audio tasks only. What an action returns that is not a file, such as lyrics, aligned lyrics, a boosted style, a persona id or MIDI notes.

### QueuedTaskOutput1

- `text` (string, required) — Completed video analysis text.
- `usage` (QueuedTaskOutputOneOf1Usage, required) — Measured token usage used for final USD settlement.
- `finish_reason` (string, required, nullable) — Why the model stopped generating.

### QueuedTaskOutput2

A data task's result: the capability's own result object, such as `web.research` with `research_notes` and `sources` (in a view: `items`).

- `object` (string, required) — The result type, such as `web.research`.
- `request_id` (string, optional) — The ID of the task that produced the result.
- `query` (string, optional) — The question that was researched.
- `status` (enum, optional) — `partial` when part of the research could not be finished; `partial_reasons` says why.
  - Allowed values: `complete`, `partial`
- `research_notes` (string, optional) — The research notes.
- `sources` (list of map from string to any, optional) — The sources behind the notes.
- `partial_reasons` (list of string, optional) — Present when `status` is `partial`.
- `x_search` (map from string to any, optional) — How much X was searched, when the run searched X at all.

### StoryboardShot

- `id` (string, required) — BeatAPI shot id. Use this id for media retrieval, edit, and compose operations.
- `index` (integer, required) — Zero-based shot order in the storyboard.
- `status` (enum, required) — Current lifecycle state for this storyboard shot.
  - Allowed values: `queued`, `processing`, `storyboard_ready`, `requires_action`, `editing`, `composing`, `succeeded`, `failed`
- `created_at` (integer, required) — Unix timestamp when the shot record was created.
- `updated_at` (integer, required) — Unix timestamp when the shot record last changed.
- `duration_seconds` (integer, optional) — Planned or generated shot duration in seconds.
- `prompt` (string, optional) — Creative instruction used to generate this shot.
- `lyric_text` (string, optional) — Lyric segment aligned with this shot when available.
- `media` (StoryboardShotMedia, optional) — Present only after the shot media has been materialized or after a shot edit finishes.

### QueuedTaskOutputOneOf0MediaItems

- `type` (enum, required) — Result asset type.
  - Allowed values: `image`, `video`, `audio`
- `url` (string, required) — BeatAPI-hosted HTTPS result URL.
- `mime_type` (string, required) — Result asset MIME type.

### QueuedTaskOutputOneOf0TracksItems

- `id` (string, required) — The id a follow-up sends as `audio_id`.
- `title` (string, optional) — Song title.
- `name` (string, optional) — Stem name on a split result.
- `tags` (string, optional) — Style tags.
- `lyrics` (string, optional) — Lyrics of the song.
- `duration` (double, optional) — Length in seconds.
- `audio_url` (string, optional) — The song or stem file.
- `image_url` (string, optional) — Cover art.

### QueuedTaskOutputOneOf1Usage

Measured token usage used for final USD settlement.

- `input_tokens` (integer, required) — Tokens consumed by the prompt and video input.
- `output_tokens` (integer, required) — Tokens consumed by visible output and model reasoning.
- `total_tokens` (integer, required) — Total measured input and output tokens.

### StoryboardShotMedia

Present only after the shot media has been materialized or after a shot edit finishes.

- `type` (string, optional) — Hosted media type for the materialized shot.
- `url` (string, optional) — BeatAPI-hosted HTTPS URL for the materialized shot.
- `mime_type` (string, optional) — MIME type of the hosted shot media.

## Examples

### 文生视频

**Request**

```json
{
  "model": "kling-v4-flash",
  "prompt": "A slow tracking shot through a rain-lit night market, neon reflections on wet stone",
  "aspect_ratio": "16:9",
  "duration": 5
}
```

**Response**

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

**SDK Code**

```python 文生视频
import requests

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

payload = {
    "model": "kling-v4-flash",
    "prompt": "A slow tracking shot through a rain-lit night market, neon reflections on wet stone",
    "aspect_ratio": "16:9",
    "duration": 5
}
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/videos/tasks';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"kling-v4-flash","prompt":"A slow tracking shot through a rain-lit night market, neon reflections on wet stone","aspect_ratio":"16:9","duration":5}'
};

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/videos/tasks"

	payload := strings.NewReader("{\n  \"model\": \"kling-v4-flash\",\n  \"prompt\": \"A slow tracking shot through a rain-lit night market, neon reflections on wet stone\",\n  \"aspect_ratio\": \"16:9\",\n  \"duration\": 5\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/videos/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-v4-flash\",\n  \"prompt\": \"A slow tracking shot through a rain-lit night market, neon reflections on wet stone\",\n  \"aspect_ratio\": \"16:9\",\n  \"duration\": 5\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/videos/tasks")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"kling-v4-flash\",\n  \"prompt\": \"A slow tracking shot through a rain-lit night market, neon reflections on wet stone\",\n  \"aspect_ratio\": \"16:9\",\n  \"duration\": 5\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.beatapi.io/v1/videos/tasks', [
  'body' => '{
  "model": "kling-v4-flash",
  "prompt": "A slow tracking shot through a rain-lit night market, neon reflections on wet stone",
  "aspect_ratio": "16:9",
  "duration": 5
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp 文生视频
using RestSharp;

var client = new RestClient("https://api.beatapi.io/v1/videos/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-v4-flash\",\n  \"prompt\": \"A slow tracking shot through a rain-lit night market, neon reflections on wet stone\",\n  \"aspect_ratio\": \"16:9\",\n  \"duration\": 5\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 文生视频
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "kling-v4-flash",
  "prompt": "A slow tracking shot through a rain-lit night market, neon reflections on wet stone",
  "aspect_ratio": "16:9",
  "duration": 5
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.beatapi.io/v1/videos/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-v4-flash",
  "prompt": "The singer turns to the camera and starts to sing as the stage lights sweep across the crowd",
  "duration": 5,
  "images": [
    "https://cdn.beatapi.io/samples/neon-singer.png"
  ]
}
```

**Response**

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

**SDK Code**

```python 首帧
import requests

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

payload = {
    "model": "kling-v4-flash",
    "prompt": "The singer turns to the camera and starts to sing as the stage lights sweep across the crowd",
    "duration": 5,
    "images": ["https://cdn.beatapi.io/samples/neon-singer.png"]
}
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/videos/tasks';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"kling-v4-flash","prompt":"The singer turns to the camera and starts to sing as the stage lights sweep across the crowd","duration":5,"images":["https://cdn.beatapi.io/samples/neon-singer.png"]}'
};

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/videos/tasks"

	payload := strings.NewReader("{\n  \"model\": \"kling-v4-flash\",\n  \"prompt\": \"The singer turns to the camera and starts to sing as the stage lights sweep across the crowd\",\n  \"duration\": 5,\n  \"images\": [\n    \"https://cdn.beatapi.io/samples/neon-singer.png\"\n  ]\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/videos/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-v4-flash\",\n  \"prompt\": \"The singer turns to the camera and starts to sing as the stage lights sweep across the crowd\",\n  \"duration\": 5,\n  \"images\": [\n    \"https://cdn.beatapi.io/samples/neon-singer.png\"\n  ]\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/videos/tasks")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"kling-v4-flash\",\n  \"prompt\": \"The singer turns to the camera and starts to sing as the stage lights sweep across the crowd\",\n  \"duration\": 5,\n  \"images\": [\n    \"https://cdn.beatapi.io/samples/neon-singer.png\"\n  ]\n}")
  .asString();
```

```php 首帧
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.beatapi.io/v1/videos/tasks', [
  'body' => '{
  "model": "kling-v4-flash",
  "prompt": "The singer turns to the camera and starts to sing as the stage lights sweep across the crowd",
  "duration": 5,
  "images": [
    "https://cdn.beatapi.io/samples/neon-singer.png"
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp 首帧
using RestSharp;

var client = new RestClient("https://api.beatapi.io/v1/videos/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-v4-flash\",\n  \"prompt\": \"The singer turns to the camera and starts to sing as the stage lights sweep across the crowd\",\n  \"duration\": 5,\n  \"images\": [\n    \"https://cdn.beatapi.io/samples/neon-singer.png\"\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 首帧
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "kling-v4-flash",
  "prompt": "The singer turns to the camera and starts to sing as the stage lights sweep across the crowd",
  "duration": 5,
  "images": ["https://cdn.beatapi.io/samples/neon-singer.png"]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.beatapi.io/v1/videos/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-v4-flash",
  "prompt": "The bottle from the reference image turns slowly on a marble table, soft studio light, shallow depth of field",
  "aspect_ratio": "9:16",
  "duration": 8,
  "reference_images": [
    "https://cdn.beatapi.io/samples/smart-bottle.png"
  ]
}
```

**Response**

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

**SDK Code**

```python 参考图
import requests

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

payload = {
    "model": "kling-v4-flash",
    "prompt": "The bottle from the reference image turns slowly on a marble table, soft studio light, shallow depth of field",
    "aspect_ratio": "9:16",
    "duration": 8,
    "reference_images": ["https://cdn.beatapi.io/samples/smart-bottle.png"]
}
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/videos/tasks';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"kling-v4-flash","prompt":"The bottle from the reference image turns slowly on a marble table, soft studio light, shallow depth of field","aspect_ratio":"9:16","duration":8,"reference_images":["https://cdn.beatapi.io/samples/smart-bottle.png"]}'
};

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/videos/tasks"

	payload := strings.NewReader("{\n  \"model\": \"kling-v4-flash\",\n  \"prompt\": \"The bottle from the reference image turns slowly on a marble table, soft studio light, shallow depth of field\",\n  \"aspect_ratio\": \"9:16\",\n  \"duration\": 8,\n  \"reference_images\": [\n    \"https://cdn.beatapi.io/samples/smart-bottle.png\"\n  ]\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/videos/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-v4-flash\",\n  \"prompt\": \"The bottle from the reference image turns slowly on a marble table, soft studio light, shallow depth of field\",\n  \"aspect_ratio\": \"9:16\",\n  \"duration\": 8,\n  \"reference_images\": [\n    \"https://cdn.beatapi.io/samples/smart-bottle.png\"\n  ]\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/videos/tasks")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"kling-v4-flash\",\n  \"prompt\": \"The bottle from the reference image turns slowly on a marble table, soft studio light, shallow depth of field\",\n  \"aspect_ratio\": \"9:16\",\n  \"duration\": 8,\n  \"reference_images\": [\n    \"https://cdn.beatapi.io/samples/smart-bottle.png\"\n  ]\n}")
  .asString();
```

```php 参考图
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.beatapi.io/v1/videos/tasks', [
  'body' => '{
  "model": "kling-v4-flash",
  "prompt": "The bottle from the reference image turns slowly on a marble table, soft studio light, shallow depth of field",
  "aspect_ratio": "9:16",
  "duration": 8,
  "reference_images": [
    "https://cdn.beatapi.io/samples/smart-bottle.png"
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp 参考图
using RestSharp;

var client = new RestClient("https://api.beatapi.io/v1/videos/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-v4-flash\",\n  \"prompt\": \"The bottle from the reference image turns slowly on a marble table, soft studio light, shallow depth of field\",\n  \"aspect_ratio\": \"9:16\",\n  \"duration\": 8,\n  \"reference_images\": [\n    \"https://cdn.beatapi.io/samples/smart-bottle.png\"\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 参考图
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "kling-v4-flash",
  "prompt": "The bottle from the reference image turns slowly on a marble table, soft studio light, shallow depth of field",
  "aspect_ratio": "9:16",
  "duration": 8,
  "reference_images": ["https://cdn.beatapi.io/samples/smart-bottle.png"]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.beatapi.io/v1/videos/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-v4-flash",
  "prompt": "The bottle from the reference image on a turntable, with camera movement like the reference video",
  "duration": 6,
  "reference_images": [
    "https://cdn.beatapi.io/samples/smart-bottle.png"
  ],
  "reference_videos": [
    "https://your-cdn.example.com/clips/source.mp4"
  ]
}
```

**Response**

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

**SDK Code**

```python 参考图和参考视频
import requests

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

payload = {
    "model": "kling-v4-flash",
    "prompt": "The bottle from the reference image on a turntable, with camera movement like the reference video",
    "duration": 6,
    "reference_images": ["https://cdn.beatapi.io/samples/smart-bottle.png"],
    "reference_videos": ["https://your-cdn.example.com/clips/source.mp4"]
}
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/videos/tasks';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"kling-v4-flash","prompt":"The bottle from the reference image on a turntable, with camera movement like the reference video","duration":6,"reference_images":["https://cdn.beatapi.io/samples/smart-bottle.png"],"reference_videos":["https://your-cdn.example.com/clips/source.mp4"]}'
};

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/videos/tasks"

	payload := strings.NewReader("{\n  \"model\": \"kling-v4-flash\",\n  \"prompt\": \"The bottle from the reference image on a turntable, with camera movement like the reference video\",\n  \"duration\": 6,\n  \"reference_images\": [\n    \"https://cdn.beatapi.io/samples/smart-bottle.png\"\n  ],\n  \"reference_videos\": [\n    \"https://your-cdn.example.com/clips/source.mp4\"\n  ]\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/videos/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-v4-flash\",\n  \"prompt\": \"The bottle from the reference image on a turntable, with camera movement like the reference video\",\n  \"duration\": 6,\n  \"reference_images\": [\n    \"https://cdn.beatapi.io/samples/smart-bottle.png\"\n  ],\n  \"reference_videos\": [\n    \"https://your-cdn.example.com/clips/source.mp4\"\n  ]\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/videos/tasks")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"kling-v4-flash\",\n  \"prompt\": \"The bottle from the reference image on a turntable, with camera movement like the reference video\",\n  \"duration\": 6,\n  \"reference_images\": [\n    \"https://cdn.beatapi.io/samples/smart-bottle.png\"\n  ],\n  \"reference_videos\": [\n    \"https://your-cdn.example.com/clips/source.mp4\"\n  ]\n}")
  .asString();
```

```php 参考图和参考视频
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.beatapi.io/v1/videos/tasks', [
  'body' => '{
  "model": "kling-v4-flash",
  "prompt": "The bottle from the reference image on a turntable, with camera movement like the reference video",
  "duration": 6,
  "reference_images": [
    "https://cdn.beatapi.io/samples/smart-bottle.png"
  ],
  "reference_videos": [
    "https://your-cdn.example.com/clips/source.mp4"
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp 参考图和参考视频
using RestSharp;

var client = new RestClient("https://api.beatapi.io/v1/videos/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-v4-flash\",\n  \"prompt\": \"The bottle from the reference image on a turntable, with camera movement like the reference video\",\n  \"duration\": 6,\n  \"reference_images\": [\n    \"https://cdn.beatapi.io/samples/smart-bottle.png\"\n  ],\n  \"reference_videos\": [\n    \"https://your-cdn.example.com/clips/source.mp4\"\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 参考图和参考视频
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "kling-v4-flash",
  "prompt": "The bottle from the reference image on a turntable, with camera movement like the reference video",
  "duration": 6,
  "reference_images": ["https://cdn.beatapi.io/samples/smart-bottle.png"],
  "reference_videos": ["https://your-cdn.example.com/clips/source.mp4"]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.beatapi.io/v1/videos/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()
```