> 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

Kling の画像モデルです。テキスト、最大 10 枚の参照画像、名前付きエレメントから、1 タスクで 1～9 枚の画像を 2K、4K、8K で生成・編集します。- 非同期です。作成リクエストはすぐにタスク ID を返し、タスクが成功すると画像を取得できます。
- 1 タスクで `n` により 1～9 枚を生成し、各画像は `resolution` の料金で課金されます。
- テキストからの生成に加え、公開 HTTPS リンクで渡した参照画像と名前付き `elements`（合計 10 個まで）を使った編集・合成に対応します。
- プロンプトでは入力を指定します。`images` は順に `@image_1`、`@image_2` …、エレメントは `@` とその名前です。
- `resolution`（2K、4K、8K）ごとの 1 枚単位の料金に、参照画像とエレメント 1 つごとの固定料金が加わります。失敗したタスクは課金されません。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` は任意です。論理的に 1 件のリクエストごとに一意の値（255 文字以内）を送り、まったく同じボディを再試行するときだけ再利用してください。24 時間以内に同じキーと同じボディで再試行すると、最初のレスポンスが `Idempotent-Replayed: true` 付きで再度返されます。同じキーで異なるボディを送ると `409 idempotency_conflict` が返ります。2xx 以外のレスポンスは保存されないため、400 や 402 の後の再試行は改めて実行されます。## リクエストの流れ下記のパラメーターをエンドポイントに `POST` します。`201` が返れば、タスクが受け付けられ、料金が残高から仮確保されたことを意味します。処理はバックグラウンドで実行されます。`data.id` を保存してください。`GET /v1/tasks/{task_id}` を呼び出し、`status` が `succeeded` または `failed` になるまで、呼び出しの間隔を `data.poll_after_seconds`（画像は 5 秒、動画は 8 秒）だけ空けてください。あるいは `task.succeeded` と `task.failed` の[Webhook](/webhooks)を登録することもできます。処理タイムアウトで停止したタスクはイベントを送信しないため、フォールバックとしてポーリングも続けてください。`succeeded` の場合は、すべての `data.output.media[].url` をダウンロードし、必要なファイルを保存してください。結果 URL がいつまで利用できるかは保証されません。`failed` の場合は、`data.error_code` と `data.error_message` を確認してください。仮確保された金額は残高に戻されます。`data.retryable` は、同じリクエストをもう一度送れば成功する可能性があるかどうかを示します。## 入力モード| モード      | 必須の入力                                               | 備考                                                                                |
| -------- | --------------------------------------------------- | --------------------------------------------------------------------------------- |
| テキストから画像 | `model`、`prompt`                                    | `images` と `elements` は送りません。                                                     |
| 画像の編集・合成 | `model`、`prompt`、および `images` と `elements` の一方または両方 | 参照画像とエレメントは合計 10 個まで。`prompt` でそれぞれを指定します。1 枚目の画像は `@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 文字- 長さは文字数で数えます（CJK の 1 文字は 1 文字です）。
- メンション：`images` はリスト順に `@image_1`、`@image_2` …、エレメントは `@` に続けてその `name` を書きます。
- すべての `@image_N` は同じリクエストの画像を指す必要があります。画像が 2 枚なのに `@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://` の URL です。ローカルファイルは先に [アップロード](/quick-guide#upload-an-input-file)（`POST /v1/files`）し、返された `data.url` を渡してください。- 各項目は JPEG または PNG ファイルを指す公開 `https://` リンクである必要があります。タスク作成時に BeatAPI は各リンクを読み取り、そのような画像でないもの、または下記の上限を外れるものを、位置を示して拒否します（`images[0]` が 1 つ目のリンク）。
- `images` と `elements` は合計 10 個までです。
- リンク 1 つごとにタスクへ固定料金が加わります（課金を参照）。**値が正しくない場合**- 上限を超える：`"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`（文字列の配列、必須）：エレメントの画像を指す公開 HTTPS リンク 2～4 個。1 枚目がメインビューです。
- `elements[].tag`（文字列、任意）：エレメントの種類。
- `elements[].description`（文字列、任意）：エレメントの説明。100 文字まで。
- エレメントは画像のみです。このモデルは動画エレメントと音声付きのエレメントを受け付けません。
- `images` と `elements` は合計 10 個までです。エレメント 1 つごとに、含む画像の枚数にかかわらずタスクへ固定料金が加わります。**値が正しくない場合**- エレメントが 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` が 2 回（大文字・小文字を区別しない）：`elements[1].name "Hero" is used twice`
- 画像が 2 枚未満：`"elements[0].element_input_urls" requires at least 2 item`
- 画像が 4 枚を超える：`"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]`
- 100 文字を超える `description`：`"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`。区分ごとに 1 枚あたりの料金が異なります。**指定できる値**：`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` は画像部分の料金を倍増させます。参照画像とエレメントの料金はタスクごとに 1 回だけで、枚数分は重ねて課金されません。
- 課金は届いた画像の枚数に基づきます。**値が正しくない場合**- 範囲外、整数ではない、または文字列で送った：`"n" is outside its supported range`ゲートウェイはタスク作成前に、次の組み合わせも確認します。- `n` で 1 回のリクエストから 1～9 枚を生成します。各画像は解像度の料金で課金され、`images` の各画像と各エレメントはリクエストごとに 1 回ずつ追加で課金されます。
- プロンプトでは `images` の画像を順に `@image_1`、`@image_2` …、エレメントを `@` とその名前で指定します。すべての `@image_N` は同じリクエストの画像を指す必要があります。
- 1 つのエレメントは、`element_input_urls` に入れた同じ被写体の画像 2～4 枚です（1 枚目がメインビュー）。`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 px以下；アスペクト比（幅 ÷ 高さ）0.4～2.5；1 件あたり 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>`。リクエストに不正なフィールドが複数ある場合、メッセージはそのうち 1 つだけを示します。修正してからもう一度送ってください。## リクエスト例```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 の画像を 1 枚生成します。```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"
}'
```### 1 タスクで 4 枚のバリエーション同じプロンプトから 4K の画像を 4 枚生成します。各画像は 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
}'
```### 1 枚の画像を編集商品写真をキャンペーン画像に再構成します。```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"
}'
```### 名前付きエレメント1 つの被写体を複数の角度から撮った画像をエレメントにし、名前で配置します。```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` のいずれかです。最終状態は後ろの 2 つだけです。                          |
| `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`          | タスク作成時に残高から仮確保された金額（USD）です。                                                                   |
| `data.usage.credits_charged`           | `number`          | このタスクの料金（USD）です。失敗したタスクでは `0` です。                                                             |
| `data.usage.credits_settled`           | `number`          | 最終的に差し引かれた金額（USD）です。タスクが成功した時点で設定され、それ以外では `0` です。                                            |
| `data.usage.credits_refunded`          | `number`          | 残高に戻された金額（USD）です。失敗したタスクでは、返金が記録された時点で仮確保した金額と一致します。                                          |
| `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[]` | 生成されたファイル。届いた画像 1 枚ごとに 1 項目で、最大 `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`   | 1 つ目のメディア URL の再掲で、古いクライアント向けです。`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` と一致します。                                                                                 |## 完全なコード例タスクを作成し、サーバーが示すポーリング間隔で完了を待ち、結果の URL を出力します。環境変数に `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` のエレメントは、1 つごとにタスクにつき 1 回、固定料金が加わります。
- 料金はタスク作成時に、残高から、キーに上限がある場合はその上限からも予約されます。タスクが作られる前に拒否されたリクエストは課金されません。
- 成功したタスクは届いた画像の枚数に応じて課金されます。失敗したタスクは予約額が全額返金され、`credits_refunded` は `credits_reserved` と等しく、`credits_charged` と `credits_settled` は 0 になります。現在の定価です。[料金](https://beatapi.io/pricing)ページと同じ金額です。割引を個別に契約しているアカウントでは、より低い金額になります。実際に課金された金額は、タスクの `data.usage` で確認できます。| オプション                                                      | 定価（USD）  |
| ---------------------------------------------------------- | -------- |
| 1 枚 · 2K                                                   | \$0.0593 |
| 1 枚 · 4K                                                   | \$0.0893 |
| 1 枚 · 8K                                                   | \$0.1486 |
| `images` の参照画像 1 枚ごと、`elements` のエレメント 1 個ごと（1 タスクにつき 1 回） | \$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 個以内にしてください。同じ被写体の複数の画像は 1 つのエレメントにまとめられます。                  |
| 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`           | 予約名、またはスペースやハイフンなどの記号を含む名前。                                                            | `Bottle` のように、英字、数字、アンダースコア、漢字の 1～20 文字を使ってください。                  |
| 400 `"images[0]" is not a PNG or JPEG image: the URL returned image/webp` | WebP、GIF、HEIC のファイル、または Web ページを返すリンク。                                                 | 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`                                                     | リクエストを修正してください。メッセージにフィールド名が示されます。そのまま再試行しないでください。                               |
| 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) — API キーを `Authorization: Bearer <BEATAPI_API_KEY>` として送信してください。

## 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` は任意です。論理的に 1 件のリクエストごとに一意の値（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 文字 - 長さは文字数で数えます（CJK の 1 文字は 1 文字です）。 - メンション：`images` はリスト順に `@image_1`、`@image_2` …、エレメントは `@` に続けてその `name` を書きます。 - すべての `@image_N` は同じリクエストの画像を指す必要があります。画像が 2 枚なのに `@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`（文字列の配列、必須）：エレメントの画像を指す公開 HTTPS リンク 2～4 個。1 枚目がメインビューです。 * `elements[].tag`（文字列、任意）：エレメントの種類。 * `elements[].description`（文字列、任意）：エレメントの説明。100 文字まで。 * エレメントは画像のみです。このモデルは動画エレメントと音声付きのエレメントを受け付けません。 * `images` と `elements` は合計 10 個までです。エレメント 1 つごとに、含む画像の枚数にかかわらずタスクへ固定料金が加わります。 **値が正しくない場合** * エレメントが 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` が 2 回（大文字・小文字を区別しない）：`elements[1].name "Hero" is used twice` * 画像が 2 枚未満：`"elements[0].element_input_urls" requires at least 2 item` * 画像が 4 枚を超える：`"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]` * 100 文字を超える `description`：`"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://` の URL です。ローカルファイルは先に [アップロード](/quick-guide#upload-an-input-file)（`POST /v1/files`）し、返された `data.url` を渡してください。 - 各項目は JPEG または PNG ファイルを指す公開 `https://` リンクである必要があります。タスク作成時に BeatAPI は各リンクを読み取り、そのような画像でないもの、または下記の上限を外れるものを、位置を示して拒否します（`images[0]` が 1 つ目のリンク）。 - `images` と `elements` は合計 10 個までです。 - リンク 1 つごとにタスクへ固定料金が加わります（課金を参照）。 **値が正しくない場合** - 上限を超える：`"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` は画像部分の料金を倍増させます。参照画像とエレメントの料金はタスクごとに 1 回だけで、枚数分は重ねて課金されません。 - 課金は届いた画像の枚数に基づきます。 **値が正しくない場合** - 範囲外、整数ではない、または文字列で送った：`"n" is outside its supported range`
- `resolution` (enum, optional, default: 2K) — 画像のサイズ区分：`2K`、`4K`、`8K`。区分ごとに 1 枚あたりの料金が異なります。 **指定できる値**：`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` リクエストを修正してください。メッセージにフィールド名が示されます。そのまま再試行しないでください。

- `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`（文字列の配列、必須）：エレメントの画像を指す公開 HTTPS リンク 2～4 個。1 枚目がメインビューです。 **要素数**：2–4 各要素は公開されている `https://` の URL です。ローカルファイルは先に [アップロード](/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()
```

### 1 タスクで 4 枚のバリエーション

**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 1 タスクで 4 枚のバリエーション
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 1 タスクで 4 枚のバリエーション
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 1 タスクで 4 枚のバリエーション
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 1 タスクで 4 枚のバリエーション
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 1 タスクで 4 枚のバリエーション
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 1 タスクで 4 枚のバリエーション
<?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 1 タスクで 4 枚のバリエーション
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 1 タスクで 4 枚のバリエーション
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()
```

### 1 枚の画像を編集

**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 1 枚の画像を編集
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 1 枚の画像を編集
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 1 枚の画像を編集
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 1 枚の画像を編集
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 1 枚の画像を編集
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 1 枚の画像を編集
<?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 1 枚の画像を編集
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 1 枚の画像を編集
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()
```