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

> 從第一個影像生成請求開始：完成身分驗證、送出任務、輪詢狀態，最後取得結果 URL。

本教程將使用 [Nano Banana](https://apixo.ai/docs/zh-hant/models/image/nano-banana.md) 生成一張圖片。提交成功後，回應會傳回任務 ID。等任務狀態變為 `success`，解析 `data.resultJson`，再用 `resultUrls` 中的連結下載圖片。

直接呼叫 REST API 時，請準備 API 金鑰並按下面三個步驟操作。如果要配置 AI 程式設計工具，請先按照 MCP 連線說明完成設定。

## 開始前的準備

* 一個 APIXO 帳號（[免費註冊](https://apixo.ai)）
* 執行下方的 REST 範例需要 API 金鑰（[取得金鑰](https://apixo.ai/docs/zh-hant/concepts/authentication.md)）。遠端 MCP 連線則透過瀏覽器使用 OAuth 登入。

## 使用 AI 程式開發工具整合 APIXO

將 **Cursor**、**Claude Code**、**Codex** 或其他支援遠端 MCP 和 OAuth 的用戶端連線到 `https://mcp.apixo.ai/mcp` 上的 **APIXO MCP**，連線名稱填寫 `apixo-mcp`。在瀏覽器中透過 apixo.ai 的 OAuth 流程登入。這個流程無須在本機安裝 MCP 或 Node.js，也無須將 API 金鑰提供給 AI 用戶端。

連線成功後，可以試用下列提示詞：

```text theme={null}
Use the apixo-mcp connection. Add a server route to my Next.js app that calls
nano-banana to generate a 16:9 image from a prompt field in the request body,
and polls until the result URL is ready. Read its schema first. Use my existing
fetch helpers and TypeScript types. Keep application credentials server-side.
Do not submit a generation while writing the code.
```

AI 助手可以用免費的只讀工具 `list_models` 和 `get_model_schema` 查詢模型引數，再將送出任務（`generateTask`）和查詢狀態（`statusTask`）的 REST 呼叫寫入專案。用 `get_profile` 可免費確認當前連線的帳戶。使用 `generate_task` 等 MCP 生成工具需要付費，`get_generation` 可查詢生成任務的狀態和結果。

透過 MCP 查詢語言模型時，為 `list_models` 指定 `integration_type: llm_gateway`，然後將模型 ID 傳給 `get_integration_guide`。根據傳回的 SDK 設定，在應用服務端使用 APIXO API 金鑰呼叫 [Chat API](https://apixo.ai/docs/zh-hant/llm)。

> [card] [連線到 APIXO MCP](https://apixo.ai/docs/zh-hant/integrations/mcp/installation.md)
>
> 為 Codex、Claude Code、Cursor 等用戶端設定遠端連線，並透過瀏覽器登入和免費工具驗證連線。

如果想直接整合 API，請繼續下方的步驟。

## 步驟 1：送出生成任務

選擇一種示例送出任務，並儲存傳回的 ID。如果希望用一個指令碼完成提交和輪詢，可直接跳到[完整示例](#complete-example)，執行一次即可。

> [tab] cURL
>
> ```bash theme={null}
> curl -X POST https://api.apixo.ai/api/v1/generateTask/nano-banana \
>   -H "Authorization: Bearer YOUR_API_KEY" \
>   -H "Content-Type: application/json" \
>   -d '{
>     "request_type": "async",
>     "input": {
>       "mode": "text-to-image",
>       "prompt": "A serene Japanese garden with cherry blossoms, golden hour lighting, photorealistic",
>       "aspect_ratio": "16:9"
>     }
>   }'
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> const API_KEY = 'YOUR_API_KEY';
> const MODEL = 'nano-banana';
>
> // Step 1: Submit task
> const submitResponse = await fetch(
>   `https://api.apixo.ai/api/v1/generateTask/${MODEL}`,
>   {
>     method: 'POST',
>     headers: {
>       'Authorization': `Bearer ${API_KEY}`,
>       'Content-Type': 'application/json',
>     },
>     body: JSON.stringify({
>       request_type: 'async',
>       input: {
>         mode: 'text-to-image',
>         prompt: 'A serene Japanese garden with cherry blossoms, golden hour lighting, photorealistic',
>         aspect_ratio: '16:9',
>       },
>     }),
>   }
> );
>
> const { data } = await submitResponse.json();
> console.log('Task ID:', data.taskId);
> ```

> [tab] Python
>
> ```python theme={null}
> import requests
>
> API_KEY = 'YOUR_API_KEY'
> MODEL = 'nano-banana'
>
> # Step 1: Submit task
> response = requests.post(
>     f'https://api.apixo.ai/api/v1/generateTask/{MODEL}',
>     headers={
>         'Authorization': f'Bearer {API_KEY}',
>         'Content-Type': 'application/json',
>     },
>     json={
>         'request_type': 'async',
>         'input': {
>             'mode': 'text-to-image',
>             'prompt': 'A serene Japanese garden with cherry blossoms, golden hour lighting, photorealistic',
>             'aspect_ratio': '16:9',
>         },
>     }
> )
>
> task_id = response.json()['data']['taskId']
> print(f'Task ID: {task_id}')
> ```

**回應範例**

```json theme={null}
{
  "code": 200,
  "message": "success",
  "data": {
    "taskId": "task_abc123xyz"
  }
}
```

## 步驟 2：輪詢任務結果

將 `TASK_ID` 替換為第 1 步傳回的 `data.taskId`，並使用同一模型和 API 金鑰。cURL 示例只查詢一次，JavaScript 和 Python 示例最多查詢 60 次。檢視 `data.state` 即可判斷任務已成功、已失敗還是仍在進行中。

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

> [tab] JavaScript
>
> ```javascript theme={null}
> const apiKey = 'YOUR_API_KEY';
>
> async function pollImage(taskId) {
>   const url = new URL('https://api.apixo.ai/api/v1/statusTask/nano-banana');
>   url.searchParams.set('taskId', taskId);
>
>   for (let attempt = 0; attempt < 60; attempt++) {
>     await new Promise(resolve => setTimeout(resolve, 3000));
>     const response = await fetch(url, {
>       headers: { Authorization: `Bearer ${apiKey}` },
>       signal: AbortSignal.timeout(30000),
>     });
>     if (!response.ok) throw new Error(`Status lookup failed (HTTP ${response.status})`);
>
>     const { data, message } = await response.json();
>     if (!data?.state) throw new Error(message || 'Missing task state');
>     if (data.state === 'success') return JSON.parse(data.resultJson).resultUrls;
>     if (data.state === 'failed') throw new Error(`${data.failCode}: ${data.failMsg}`);
>   }
>   throw new Error(`Polling limit reached. Check task ${taskId} again later.`);
> }
>
> console.log(await pollImage('TASK_ID'));
> ```

> [tab] Python
>
> ```python theme={null}
> import json
> import time
>
> import requests
>
> API_KEY = 'YOUR_API_KEY'
>
> def poll_image(task_id):
>     for _ in range(60):
>         time.sleep(3)
>         response = requests.get(
>             'https://api.apixo.ai/api/v1/statusTask/nano-banana',
>             params={'taskId': task_id},
>             headers={'Authorization': f'Bearer {API_KEY}'},
>             timeout=30,
>         )
>         response.raise_for_status()
>         lookup = response.json()
>         data = lookup.get('data') or {}
>         if not data.get('state'):
>             raise RuntimeError(lookup.get('message') or 'Missing task state')
>         if data['state'] == 'success':
>             return json.loads(data['resultJson'])['resultUrls']
>         if data['state'] == 'failed':
>             raise RuntimeError(f"{data.get('failCode')}: {data.get('failMsg')}")
>     raise TimeoutError(f'Polling limit reached. Check task {task_id} again later.')
>
> print(poll_image('TASK_ID'))
> ```

**成功回應範例**

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

## 步驟 3：下載影像

`resultUrls` 陣列包含生成影像的直接連結。可以在瀏覽器中開啟連結，也可以用程式下載。

> [!NOTE]
>
> 生成的圖片預設保留 15 天，實際保留時間取決於 API 金鑰的儲存設定。重要結果請及時下載儲存。

## 完整範例

在環境中設定 `APIXO_API_KEY`，選擇一個指令碼從頭執行。每次執行都會新建影像任務、列印任務 ID，並最多輪詢 60 次。如果已有第 1 步或上次執行傳回的 ID，請直接按[第 2 步](#step-2-poll-for-results)查詢；即使輪詢超時，也可以繼續用原 ID 查詢。

> [tab] JavaScript
>
> ```javascript theme={null}
> const generateImage = async (prompt) => {
>   const API_KEY = process.env.APIXO_API_KEY;
>   const MODEL = 'nano-banana';
>
>   // Submit
>   const submit = await fetch(`https://api.apixo.ai/api/v1/generateTask/${MODEL}`, {
>     method: 'POST',
>     signal: AbortSignal.timeout(30000),
>     headers: {
>       'Authorization': `Bearer ${API_KEY}`,
>       'Content-Type': 'application/json',
>     },
>     body: JSON.stringify({
>       request_type: 'async',
>       input: { mode: 'text-to-image', prompt, aspect_ratio: '1:1' },
>     }),
>   });
>
>   if (!submit.ok) throw new Error(`Submission failed (HTTP ${submit.status})`);
>   const submitted = await submit.json();
>   const taskId = submitted.data?.taskId;
>   if (!taskId) throw new Error(submitted.message || 'Missing task ID');
>   console.log('Submitted:', MODEL, taskId);
>
>   // Poll
>   for (let attempt = 0; attempt < 60; attempt++) {
>     await new Promise(r => setTimeout(r, 3000));
>     const status = await fetch(
>       `https://api.apixo.ai/api/v1/statusTask/${MODEL}?taskId=${taskId}`,
>       { headers: { 'Authorization': `Bearer ${API_KEY}` }, signal: AbortSignal.timeout(30000) }
>     );
>     if (!status.ok) throw new Error(`Status lookup failed (HTTP ${status.status})`);
>     const lookup = await status.json();
>     if (!lookup.data?.state) throw new Error(lookup.message || 'Missing task state');
>     const { data } = lookup;
>
>     if (data.state === 'success') {
>       return JSON.parse(data.resultJson).resultUrls;
>     }
>     if (data.state === 'failed') {
>       throw new Error(`${data.failCode}: ${data.failMsg}`);
>     }
>   }
>   throw new Error(`Polling limit reached. Resume ${MODEL} task ${taskId}.`);
> };
>
> // Usage
> const urls = await generateImage('A cute robot drinking coffee');
> console.log(urls);
> ```

> [tab] Python
>
> ```python theme={null}
> import requests
> import json
> import time
> import os
>
> def generate_image(prompt: str) -> list[str]:
>     api_key = os.environ['APIXO_API_KEY']
>     model = 'nano-banana'
>     base_url = 'https://api.apixo.ai/api/v1'
>     headers = {
>         'Authorization': f'Bearer {api_key}',
>         'Content-Type': 'application/json',
>     }
>
>     # Submit
>     response = requests.post(
>         f'{base_url}/generateTask/{model}',
>         headers=headers,
>         timeout=30,
>         json={
>             'request_type': 'async',
>             'input': {'mode': 'text-to-image', 'prompt': prompt, 'aspect_ratio': '1:1'},
>         }
>     )
>     response.raise_for_status()
>     submitted = response.json()
>     task_id = (submitted.get("data") or {}).get("taskId")
>     if not task_id:
>         raise RuntimeError(submitted.get("message") or "Missing task ID")
>     print("Submitted:", model, task_id)
>
>     # Poll
>     for _ in range(60):
>         time.sleep(3)
>         response = requests.get(
>             f'{base_url}/statusTask/{model}',
>             params={'taskId': task_id},
>             headers=headers,
>             timeout=30,
>         )
>         response.raise_for_status()
>         lookup = response.json()
>         data = lookup.get('data') or {}
>         if not data.get('state'):
>             raise RuntimeError(lookup.get('message') or 'Missing task state')
>
>         if data['state'] == 'success':
>             return json.loads(data['resultJson'])['resultUrls']
>         if data['state'] == 'failed':
>             raise RuntimeError(f"{data.get('failCode')}: {data.get('failMsg')}")
>
>     raise TimeoutError(f"Polling limit reached. Resume {model} task {task_id}.")
>
> # Usage
> urls = generate_image('A cute robot drinking coffee')
> print(urls)
> ```

## 後續步驟

> [card] [APIXO 的運作方式](https://apixo.ai/docs/zh-hant/concepts/how-apixo-works.md)
>
> 了解生成 API 與 Chat API 的差異

> [card] [生成 API 概覽](https://apixo.ai/docs/zh-hant/models.md)
>
> 瀏覽影像、影片和音訊模型的 API 文件

> [card] [Chat API](https://apixo.ai/docs/zh-hant/llm)
>
> 使用與 Claude、OpenAI 以及 Gemini 相容的 API

> [card] [最佳實務](https://apixo.ai/docs/zh-hant/guides/best-practices.md)
>
> 優化輪詢、重試機制，提升正式環境的穩定性


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