# 快速入門

> 生成第一張圖片並儲存成檔案：登入、建立 API 金鑰、提交任務、輪詢狀態、下載結果。

依照本頁步驟操作後，你會透過一次 API 呼叫生成一張 PNG 圖片，並將檔案儲存到本機。你需要一個電子郵件地址、大於零的餘額，以及 `curl` 搭配 [`jq`](https://jqlang.org)（或 Python 3 搭配 `requests`，或 Node.js 18+）。帳號中已有餘額的話，大約只需兩分鐘。

以下頁面會針對一組模型逐步說明一次請求：[Seedance API](https://kerox.ai/zh-hant/seedance-api)、[Kling API](https://kerox.ai/zh-hant/kling-api)、[AI 圖片生成 API](https://kerox.ai/zh-hant/ai-image-generator-api)、[文字轉影片 API](https://kerox.ai/zh-hant/text-to-video-api) 與 [圖片轉影片 API](https://kerox.ai/zh-hant/image-to-video-api)。

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

## 取得 API 金鑰與餘額
1. 輸入我們透過電子郵件寄給你的 6 位數驗證碼，登入[主控台](https://kerox.ai/zh-hant/console/api-keys)。首次登入時會自動建立帳號。
2. 開啟 **API** → **API 金鑰** 並建立 API 金鑰。完整的 API 金鑰只會在建立時顯示一次，請當下複製。
3. 開啟**錢包**並查看可用餘額。如需儲值，可在該處刷卡或使用支付寶：[儲值](https://kerox.ai/zh-hant/docs/pricing-billing.md#topups)。若餘額不足以支付任務的預估費用，任務會被拒絕並傳回 HTTP `402`。

將金鑰放入環境變數。每個請求都會以 `Authorization: Bearer <your-api-key>` 傳送金鑰；請只在伺服器端保存，切勿放在瀏覽器應用程式中。金鑰輪替與可視需要設定的限制：[API 金鑰](https://kerox.ai/zh-hant/docs/authentication.md)。


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


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

## 提交、輪詢、下載
一個指令碼即可完成整個流程：`POST /v1/tasks` 會傳回 HTTP `201`，並附上任務的 `id` 與 `status: "processing"`；指令碼每 3 秒輪詢一次 `GET /v1/tasks/{id}`，直到 `status` 為 `succeeded` 或 `failed`，然後儲存檔案或輸出失敗原因。10 分鐘後用戶端會停止等待。請保留輸出的任務 ID，稍後再次輪詢。伺服器逾時會顯示為 `failed`，並附上 `error.code: "timeout"`。請先確認原任務已失敗，再提交新任務（[逾時](https://kerox.ai/zh-hant/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/zh-hant/docs/errors.md#next-steps)。

> **請在 7 天內儲存輸出結果**
>
> 生成檔案的連結會在任務完成 7 天後失效（`expires_at`）。請將需要的檔案儲存到你自己的儲存空間（[保留期限](https://kerox.ai/zh-hant/docs/tasks.md#retention)）。

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

### 不想輪詢？傳入 `webhook_url`
下方的範例請求採用輪詢。若要接收回呼，請在提交時設定你自己的公開 HTTPS 接收端，並保留任務 ID，以便在傳送延遲時改用輪詢。請參閱[Webhook](https://kerox.ai/zh-hant/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`，每個檔案一個項目，各自帶有 `type` 和 `url`；`cost` 是以美元計的結算金額（價格：[模型](https://kerox.ai/zh-hant/docs/models.md)）。狀態為 `failed` 時，原因位於 `error`，且預扣金額會退還。`input` 顯示你的請求轉換後傳給模型的參數（此例中 `resolution` 轉換為 `size`）。所有欄位說明：[任務物件](https://kerox.ai/zh-hant/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/zh-hant/docs/webhooks.md): 任務完成時，將任務推送到你的伺服器。
- [檔案與輸入](https://kerox.ai/zh-hant/docs/files.md): 上傳參考圖片並在任務中使用。
- [MCP 伺服器](https://kerox.ai/zh-hant/docs/mcp.md): 讓 Claude Code 或 Cursor 呼叫 Kerox。
