> ## Documentation Index
> Fetch the complete documentation index at: https://apixo.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 查詢任務狀態 API · 按任務 ID 輪詢生成結果

> 使用模型和任務 ID 輪詢 APIXO 生成任務，取得狀態、失敗詳情、計費資訊和最終結果連結。

在 URL 路徑中使用原先送出任務時的模型 ID，將回應中的 `data.taskId` 作為查詢參數 `taskId`。要查詢批次 ID，請使用[查詢批次狀態](https://apixo.ai/docs/zh-hant/api-reference/batch-status.md)。

| 傳回狀態 | 用戶端應如何處理 |
| - | - |
| `pending` 或 `processing` | 保留任務 ID，稍後再次輪詢。 |
| `success` | 停止輪詢，按送出時所用模型的結果格式解析 `data.resultJson`。 |
| `failed` | 停止輪詢。記錄 `failCode` 和 `failMsg`，並參照[錯誤碼](https://apixo.ai/docs/zh-hant/api-reference/errors.md)判斷如何恢復。 |

## 端點

```
GET https://api.apixo.ai/api/v1/statusTask/{model}?taskId={taskId}
```

## 參數

**model** `string` *required*

送出任務時使用的模型 ID，例如 `nano-banana` 或 `flux-2`。

**taskId** `string` *required*

[送出生成任務](https://apixo.ai/docs/zh-hant/api-reference/generate-task.md)端點傳回的任務 ID。

## 請求標頭

**Authorization** `string` *required*

用於 API 身分驗證的 Bearer 令牌。格式為 `Bearer YOUR_API_KEY`。

## 回應

```json theme={null}
{
  "code": 200,
  "message": "success",
  "data": {
    "taskId": "task_abc123xyz789",
    "state": "success",
    "resultJson": "{\"resultUrls\":[\"https://cdn.apixo.ai/output/abc123.jpg\"]}",
    "costTime": 12500,
    "createTime": 1704067200000,
    "completeTime": 1704067212500
  }
}
```

### 任務狀態

| 狀態 | 說明 |
| - | - |
| `pending` | 已接收任務，等待處理 |
| `processing` | AI 模型正在處理任務 |
| `success` | 生成成功 |
| `failed` | 生成失敗，請檢視錯誤詳情 |

### 回應欄位

**taskId** `string`

任務的唯一識別碼。

**state** `string`

目前的任務狀態，可能的值為 `pending`、`processing`、`success`、`failed`。

**resultJson** `string`

包含 `resultUrls` 陣列的 JSON 字串。只有 `state` 為 `success` 時才會傳回。使用 `JSON.parse()` 解析。

**costTime** `integer`

處理耗時，單位為毫秒。僅在處理完成時傳回。

**createTime** `integer`

任務建立時間戳，以 Unix 毫秒錶示。

**completeTime** `integer`

任務完成時間戳，以 Unix 毫秒錶示。僅在處理完成時傳回。

**failCode** `string`

錯誤碼。只有 `state` 為 `failed` 時才會傳回。

**failMsg** `string`

便於閱讀的錯誤訊息。只有 `state` 為 `failed` 時才會傳回。

**billing** `object`

選填的最終計費明細。僅當模型會在任務成功結束時的回應中公開結算詳情，才會傳回此欄位。

**billing.settlementState** `string`

計費明細的結算狀態。已完成結算的資料使用 `final`。

**billing.unit** `string`

按時長計費的欄位使用的單位，例如 `second`。

## 各狀態的回應示例

### 等待處理或處理中

```json theme={null}
{
  "code": 200,
  "message": "success",
  "data": {
    "taskId": "task_abc123xyz789",
    "state": "processing",
    "createTime": 1704067200000
  }
}
```

### 成功

```json theme={null}
{
  "code": 200,
  "message": "success",
  "data": {
    "taskId": "task_abc123xyz789",
    "state": "success",
    "resultJson": "{\"resultUrls\":[\"https://cdn.apixo.ai/output/abc123.jpg\"]}",
    "costTime": 12500,
    "createTime": 1704067200000,
    "completeTime": 1704067212500
  }
}
```

**解析 resultJson**

```javascript theme={null}
const result = JSON.parse(data.resultJson);
const urls = result.resultUrls; // Array of generated content URLs
```

### 失敗

```json theme={null}
{
  "code": 200,
  "message": "success",
  "data": {
    "taskId": "task_abc123xyz789",
    "state": "failed",
    "failCode": "CONTENT_VIOLATION",
    "failMsg": "Content violates usage policy",
    "createTime": 1704067200000,
    "completeTime": 1704067205000
  }
}
```

> [!NOTE]
>
> HTTP `200` 且傳回 `state: "failed"` 表示 API 請求成功，但任務本身失敗。請檢視 `failCode` 和 `failMsg` 以確認原因。所有錯誤碼見[錯誤碼](https://apixo.ai/docs/zh-hant/api-reference/errors.md)。

## 結果連結

`resultUrls` 陣列包含生成內容的直達連結。

```json theme={null}
{
  "resultUrls": [
    "https://cdn.apixo.ai/output/abc123.jpg",
    "https://cdn.apixo.ai/output/abc124.jpg"
  ]
}
```

> [!WARNING]
>
> 生成的檔案預設保留 15 天，實際保留期間可能因 API 金鑰的儲存設定而異。請儘快下載並儲存重要結果。

## 示例

> [tab] cURL
>
> ```bash theme={null}
> curl "https://api.apixo.ai/api/v1/statusTask/nano-banana?taskId=task_abc123" \
>   -H "Authorization: Bearer YOUR_API_KEY"
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> const response = await fetch(
>   'https://api.apixo.ai/api/v1/statusTask/nano-banana?taskId=task_abc123',
>   {
>     headers: { 'Authorization': 'Bearer YOUR_API_KEY' },
>   }
> );
> const { data } = await response.json();
>
> if (data.state === 'success') {
>   const urls = JSON.parse(data.resultJson).resultUrls;
>   console.log('Generated:', urls);
> }
> ```

> [tab] Python
>
> ```python theme={null}
> import json
>
> response = requests.get(
>     'https://api.apixo.ai/api/v1/statusTask/nano-banana',
>     params={'taskId': 'task_abc123'},
>     headers={'Authorization': 'Bearer YOUR_API_KEY'},
> )
>
> data = response.json()['data']
>
> if data['state'] == 'success':
>     urls = json.loads(data['resultJson'])['resultUrls']
>     print(f'Generated: {urls}')
> ```

## 輪詢示例

> [tab] JavaScript
>
> ```javascript theme={null}
> async function waitForResult(model, taskId, apiKey) {
>   const maxAttempts = 60;
>   const pollInterval = 3000; // 3 seconds
>
>   for (let i = 0; i < maxAttempts; i++) {
>     const response = await fetch(
>       `https://api.apixo.ai/api/v1/statusTask/${model}?taskId=${taskId}`,
>       { headers: { 'Authorization': `Bearer ${apiKey}` } }
>     );
>
>     const { data } = await response.json();
>
>     switch (data.state) {
>       case 'success':
>         return JSON.parse(data.resultJson).resultUrls;
>       case 'failed':
>         throw new Error(`${data.failCode}: ${data.failMsg}`);
>       default:
>         await new Promise(r => setTimeout(r, pollInterval));
>     }
>   }
>
>   throw new Error('Timeout waiting for result');
> }
> ```

> [tab] Python
>
> ```python theme={null}
> import time
> import json
>
> def wait_for_result(model: str, task_id: str, api_key: str) -> list[str]:
>     max_attempts = 60
>     poll_interval = 3  # seconds
>
>     for _ in range(max_attempts):
>         response = requests.get(
>             f'https://api.apixo.ai/api/v1/statusTask/{model}',
>             params={'taskId': task_id},
>             headers={'Authorization': f'Bearer {api_key}'},
>         )
>
>         data = response.json()['data']
>
>         if data['state'] == 'success':
>             return json.loads(data['resultJson'])['resultUrls']
>         elif data['state'] == 'failed':
>             raise Exception(f"{data['failCode']}: {data['failMsg']}")
>
>         time.sleep(poll_interval)
>
>     raise Exception('Timeout waiting for result')
> ```

## 錯誤回應

| 代碼 | 說明 |
| - | - |
| `401` | API 金鑰無效或缺失 |
| `404` | 未找到任務 |
| `429` | 超出速率限制 |

詳細的錯誤處理方法見[錯誤碼](https://apixo.ai/docs/zh-hant/api-reference/errors.md)。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.