# クイックスタート

> 最初の画像を生成してファイルに保存します。サインインして API キーを作成し、タスクを送信してポーリングし、結果をダウンロードします。

このページの手順を完了すると、1 回の API 呼び出しで生成された PNG がディスクに保存されます。必要なものは、メールアドレス、0 より大きい残高、そして [`jq`](https://jqlang.org) を備えた `curl`（または `requests` を備えた Python 3、あるいは Node.js 18+）です。アカウントに残高があれば、所要時間は約 2 分です。

これらのページでは、[Seedance API](https://kerox.ai/ja/seedance-api)、[Kling API](https://kerox.ai/ja/kling-api)、[AI 画像生成 API](https://kerox.ai/ja/ai-image-generator-api)、[テキストから動画生成 API](https://kerox.ai/ja/text-to-video-api)、[画像から動画生成 API](https://kerox.ai/ja/image-to-video-api)の各モデルグループを対象に、1 件のリクエストを順を追って説明します。

<a id="key"></a>

## API キーと残高を用意する
1. [Console](https://kerox.ai/ja/console/api-keys) に、メールでお送りする6桁のコードでサインインします。初回のサインインでアカウントが作成されます。
2. **API** → **API キー** を開き、キーを作成します。キー全体が表示されるのは作成時の1回だけなので、その場でコピーしてください。
3. **ウォレット** を開き、利用可能な残高を確認します。資金を追加するには、そこでカードまたは Alipay でチャージします。詳しくは [チャージ](https://kerox.ai/ja/docs/pricing-billing.md#topups) をご覧ください。残高が見積額に満たない場合、タスクは HTTP `402` で拒否されます。

キーを環境変数に設定します。すべてのリクエストでキーは `Authorization: Bearer <your-api-key>` として送信されます。キーはサーバー上で保管し、ブラウザアプリには決して含めないでください。ローテーションと、任意で設定できる制限については [API キー](https://kerox.ai/ja/docs/authentication.md) をご覧ください。


```bash
export KEROX_API_KEY="kx_live_your_api_key_here"
```


<a id="submit"></a>

## 送信、ポーリング、ダウンロード
1つのスクリプトで一連の流れをすべて実行します。`POST /v1/tasks` は HTTP `201` を返し、レスポンスにはタスクの `id` と `status: "processing"` が含まれます。スクリプトは `GET /v1/tasks/{id}` を3秒ごとにポーリングし、`status` が `succeeded` または `failed` になると、ファイルを保存するか、失敗の理由を出力します。10分経過するとクライアントは待機を終了します。出力されたタスク ID を控えておき、後で再度ポーリングしてください。サーバー側のタイムアウトは `failed` として表示され、`error.code: "timeout"` を伴います。代わりのタスクは、失敗が確認された後にのみ送信してください（[タイムアウト](https://kerox.ai/ja/docs/tasks.md#retention)）。


```bash
# Needs curl and jq. KEROX_API_KEY is your key.
set -euo pipefail
API=https://api.kerox.ai/v1
AUTH="Authorization: Bearer $KEROX_API_KEY"
BODY='{
  "model": "bytedance/seedream-5.5",
  "input": {
    "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
    "resolution": "2K"
  }
}'

# 1. Submit: HTTP 201 with the task's id.
TASK_ID=$(curl -sS --fail-with-body -X POST "$API/tasks" \
  -H "$AUTH" -H "Content-Type: application/json" -d "$BODY" | jq -r .id)
echo "Submitted $TASK_ID"

# 2. Poll every 3 seconds, for up to 10 minutes.
DEADLINE=$(( $(date +%s) + 600 ))
STATUS=processing
while [ "$STATUS" = "processing" ] && [ "$(date +%s)" -lt "$DEADLINE" ]; do
  sleep 3
  REM=$(( DEADLINE - $(date +%s) ))
  [ "$REM" -le 0 ] && break
  [ "$REM" -gt 30 ] && REM=30
  TASK=$(curl -sS --fail-with-body --max-time "$REM" "$API/tasks/$TASK_ID" -H "$AUTH")
  STATUS=$(echo "$TASK" | jq -r .status)
done

# 3. Save the file, or show why it failed.
if [ "$STATUS" = "processing" ]; then
  echo "Still running: TASK_ID=$TASK_ID, read it later with GET /v1/tasks/{id}"
  exit 1
elif [ "$STATUS" != "succeeded" ]; then
  echo "Task $TASK_ID is $STATUS: $(echo "$TASK" | jq -c .error)"
  exit 1
fi
curl -sS --fail-with-body -o result.png "$(echo "$TASK" | jq -r '.outputs[0].url')"
echo "Saved result.png"
```
```python
# pip install requests
import os
import time
import requests

API = "https://api.kerox.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['KEROX_API_KEY']}"}

# 1. Submit: HTTP 201 with the task's id.
resp = requests.post(
    f"{API}/tasks",
    headers=HEADERS,
    json={
        "model": "bytedance/seedream-5.5",
        "input": {
            "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
            "resolution": "2K",
        },
    },
    timeout=60,
)
if resp.status_code != 201:
    raise SystemExit(f"HTTP {resp.status_code}: {resp.json()['error']}")
task = resp.json()
print("Submitted", task["id"])

# 2. Poll every 3 seconds, for up to 10 minutes.
deadline = time.time() + 600
while task["status"] == "processing" and time.time() < deadline:
    time.sleep(3)
    remaining = max(1, min(30, deadline - time.time()))
    poll = requests.get(f"{API}/tasks/{task['id']}", headers=HEADERS, timeout=remaining)
    poll.raise_for_status()
    task = poll.json()

# 3. Save the file, or show why it failed.
if task["status"] == "processing":
    raise SystemExit(f"Still running: task {task['id']}, read it again later")
if task["status"] != "succeeded":
    raise SystemExit(f"Task {task['id']} is {task['status']}: {task['error']}")
file = requests.get(task["outputs"][0]["url"], timeout=60)
file.raise_for_status()
with open("result.png", "wb") as fh:
    fh.write(file.content)
print("Saved result.png")
```
```javascript
// Node.js 18 or later: fetch is built in.
import fs from 'node:fs/promises';

const API = 'https://api.kerox.ai/v1';
const headers = { Authorization: `Bearer ${process.env.KEROX_API_KEY}` };

// 1. Submit: HTTP 201 with the task's id.
const res = await fetch(`${API}/tasks`, {
  method: 'POST',
  headers: { ...headers, 'Content-Type': 'application/json' },
  body: JSON.stringify({
    model: 'bytedance/seedream-5.5',
    input: {
      prompt: 'editorial portrait of a ceramicist in morning sunlight, 35mm film',
      resolution: '2K',
    },
  }),
});
let task = await res.json();
if (res.status !== 201) throw new Error(`HTTP ${res.status}: ${task.error.message}`);
console.log('Submitted', task.id);

// 2. Poll every 3 seconds, for up to 10 minutes.
const deadline = Date.now() + 10 * 60 * 1000;
while (task.status === 'processing' && Date.now() < deadline) {
  await new Promise((resolve) => setTimeout(resolve, 3000));
  const poll = await fetch(`${API}/tasks/${task.id}`, {
    headers,
    signal: AbortSignal.timeout(Math.max(1000, Math.min(30_000, deadline - Date.now()))),
  });
  if (!poll.ok) throw new Error(`HTTP ${poll.status}`);
  task = await poll.json();
}

// 3. Save the file, or show why it failed.
if (task.status === 'processing') {
  throw new Error(`Still running: task ${task.id}, read it later with GET /v1/tasks/{id}`);
}
if (task.status !== 'succeeded') {
  throw new Error(`Task ${task.id} is ${task.status}: ${JSON.stringify(task.error)}`);
}
const file = await fetch(task.outputs[0].url);
if (!file.ok) throw new Error(`Download failed: HTTP ${file.status}`);
await fs.writeFile('result.png', Buffer.from(await file.arrayBuffer()));
console.log('Saved result.png');
```


送信のレスポンスが `201` 以外の場合、本文はエラーオブジェクトです。各コードの意味と対処方法は [エラー](https://kerox.ai/ja/docs/errors.md#next-steps) をご覧ください。

> **出力は7日以内に保存してください**
>
> 生成されたファイルは、タスク完了から7日後に利用できなくなります（`expires_at`）。必要なものはご自身のストレージに保存してください（[保持期間](https://kerox.ai/ja/docs/tasks.md#retention)）。

<a id="webhook"></a>

### ポーリングしたくない場合は `webhook_url` を指定
以下のデフォルトのリクエストではポーリングを使用します。コールバックを受け取るには、送信時に独自の公開 HTTPS 受信先を指定し、配信が遅れた場合にポーリングできるようタスク ID を控えておいてください。詳しくは [Webhook](https://kerox.ai/ja/docs/webhooks.md) をご覧ください。


```json
{
  "model": "bytedance/seedream-5.5",
  "input": {
    "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
    "resolution": "2K"
  }
}
```


<a id="result"></a>

## 結果を確認する
スクリプトが最後に読み取ったタスクは次のようになります。`succeeded` の場合、ファイルは `outputs` に 1 ファイルにつき 1 項目ずつ格納され、それぞれに `type` と `url` が含まれます。`cost` は確定した金額（USD）です（料金：[モデル](https://kerox.ai/ja/docs/models.md)）。`failed` の場合、理由は `error` に記載され、保留額は返金されます。`input` には、リクエストの変換後のモデル固有パラメータが表示されます（この例では `resolution` が `size` になりました）。全フィールドの説明：[タスクオブジェクト](https://kerox.ai/ja/docs/tasks.md#submit-response)。


```json
{
  "id": "task_01JD8X9B4Q2M7T8N3K5P6R1S0V",
  "object": "task",
  "model": "bytedance/seedream-5.5",
  "status": "succeeded",
  "source": "api",
  "format": "unified",
  "input": {
    "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
    "size": "2K"
  },
  "outputs": [
    {
      "type": "image",
      "url": "https://cdn.kerox.ai/t/task_01JD8X9B4Q2M7T8N3K5P6R1S0V/5f2b8c1e9d3a4f6b8a7c0d1e2f3a4b5c/0.png",
      "content_type": "image/png",
      "width": 2048,
      "height": 2048
    }
  ],
  "outputs_deleted": false,
  "error": null,
  "cost": {
    "amount": "0.0280",
    "currency": "USD",
    "status": "settled"
  },
  "metadata": null,
  "warnings": [],
  "created_at": "2026-11-20T08:01:02Z",
  "started_at": "2026-11-20T08:01:02Z",
  "completed_at": "2026-11-20T08:01:10Z",
  "expires_at": "2026-11-27T08:01:10Z"
}
```


<a id="next"></a>

## 次のステップ
- [Webhook](https://kerox.ai/ja/docs/webhooks.md): タスクが完了すると、そのタスクがサーバーへ自動で送信されます。
- [ファイルと入力](https://kerox.ai/ja/docs/files.md): 参照画像をアップロードしてタスクで使用します。
- [MCP サーバー](https://kerox.ai/ja/docs/mcp.md): Claude Code や Cursor から Kerox を呼び出せるようにします。
