> ## 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/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/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，也无需向 AI 客户端提供 API 密钥。

连接成功后，可以试试这段提示词：

```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/llm)。

> [card] [连接 APIXO MCP](https://apixo.ai/docs/zh/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/concepts/how-apixo-works.md)
>
> 了解生成 API 与 Chat API 的区别

> [card] [生成 API 概览](https://apixo.ai/docs/zh/models.md)
>
> 浏览图像、视频和音频模型的 API 文档

> [card] [Chat API](https://apixo.ai/docs/zh/llm)
>
> 使用与 Claude、OpenAI 和 Gemini 兼容的 API

> [card] [最佳实践](https://apixo.ai/docs/zh/guides/best-practices.md)
>
> 优化轮询、重试机制，提升生产环境的可靠性


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