> ## 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/ja/models/image/nano-banana.md) で画像を 1 枚生成します。送信が成功するとタスク ID が返ります。タスクが `success` になったら `data.resultJson` を解析し、`resultUrls` のリンクから画像をダウンロードしたら完了です。

REST API を直接呼ぶ場合は、API キーを用意して次の 3 ステップに進んでください。AI コーディングツールを設定する場合は、先に MCP の接続手順を確認します。

## 前提条件

* APIXO アカウント（[無料で登録](https://apixo.ai)）
* 以下の REST サンプルを実行するには API キーが必要です（[API キーを取得する手順](https://apixo.ai/docs/ja/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 API の処理をプロジェクトに実装できます。`get_profile` では接続中のアカウントを無料で確認できます。`generate_task` などの生成ツールは有料です。タスクの状態と結果は `get_generation` で確認できます。

MCP で言語モデルを検索するには、`list_models` に `integration_type: llm_gateway` を指定し、モデル ID を `get_integration_guide` に渡します。返された SDK 設定と APIXO API キーを使って、アプリのサーバーから [Chat API](https://apixo.ai/docs/ja/llm) を呼び出します。

> [card] [APIXO MCP に接続](https://apixo.ai/docs/ja/integrations/mcp/installation.md)
>
> Codex、Claude Code、Cursor などのリモート接続を設定します。ブラウザーでのサインインと無料の接続確認ツールが利用できます。

API を直接組み込む場合は、以下の手順に進んでください。

## 手順 1：生成タスクを送信する

いずれか 1 つの例でタスクを送信し、返された ID を保存します。送信からポーリングまでを 1 つのスクリプトで試すには、[完全なサンプル](#complete-example)に進み、1 回だけ実行してください。

> [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 の例は 1 回だけ、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` 配列には、生成された画像への直接リンクが含まれます。URL をブラウザーで開くか、プログラムでダウンロードしてください。

> [!NOTE]
>
> 生成した画像の標準の保存期間は 15 日です。実際の期間は API キーのストレージ設定によって変わるため、大切な画像は早めにダウンロードして保存してください。

## 完全なサンプle

環境変数 `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/ja/concepts/how-apixo-works.md)
>
> 生成 API と Chat API の違いを確認できます。

> [card] [生成 API の概要](https://apixo.ai/docs/ja/models.md)
>
> 画像、動画、音声モデルの API ドキュメントを参照できます。

> [card] [Chat API](https://apixo.ai/docs/ja/llm)
>
> Claude、OpenAI、Gemini と互換性のある API を利用できます。

> [card] [ベストプラクティス](https://apixo.ai/docs/ja/guides/best-practices.md)
>
> ポーリングとリトライを最適化し、本番環境での信頼性を高めます。


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