> ## 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.

# Webhook · タスク完了のコールバックを受信

> ポーリングを使わず、APIXO の生成タスク完了コールバックを受信し、成功、失敗、再試行を処理します。

生成タスクが完了したら、公開 HTTPS エンドポイントで結果を受け取れます。アプリケーションが外部からのリクエストを受信できない場合は、[ポーリングと Webhook の比較](https://apixo.ai/docs/ja/guides/polling-vs-webhooks.md)を参照して結果の受け取り方法を選んでください。

## 概要

`callback` モードでは、タスク完了時に APIXO が指定された URL に POST リクエストを送ります。ポーリングの負荷をかけずにすぐ通知を受け取れるため、大量のタスクを処理する本番環境に適しています。

## 設定手順

**1. Webhook エンドポイントを作成する**

エンドポイントは POST リクエストを受け付け、30 秒以内に HTTP 200 を返す必要があります。また、HTTPS で外部からアクセスできる必要があります。

> [!WARNING]
>
> エンドポイントが 30 秒以内に HTTP 200 を返さない場合、APIXO は待機時間を延ばしながら最大 3 回再送します。

> [tab] Express.js
>
> ```javascript theme={null}
> const express = require('express');
> const app = express();
>
> app.use(express.json());
>
> app.post('/webhook/apixo', (req, res) => {
>   const { taskId, state, resultJson, failCode, failMsg } = req.body.data;
>
>   if (state === 'success') {
>     const urls = JSON.parse(resultJson).resultUrls;
>     console.log('Generated:', urls);
>   } else if (state === 'failed') {
>     console.error(`Task ${taskId} failed: ${failCode} - ${failMsg}`);
>   }
>
>   res.status(200).send('OK');
> });
>
> app.listen(3000);
> ```

> [tab] FastAPI
>
> ```python theme={null}
> from fastapi import FastAPI, Request
> import json
>
> app = FastAPI()
>
> @app.post('/webhook/apixo')
> async def handle_webhook(request: Request):
>     body = await request.json()
>     data = body['data']
>
>     if data['state'] == 'success':
>         urls = json.loads(data['resultJson'])['resultUrls']
>         print(f"Generated: {urls}")
>     elif data['state'] == 'failed':
>         print(f"Task {data['taskId']} failed: {data['failCode']} - {data['failMsg']}")
>
>     return {'status': 'ok'}
> ```

> [tab] Next.js
>
> ```typescript theme={null}
> // app/api/webhook/apixo/route.ts
> import { NextRequest, NextResponse } from 'next/server';
>
> export async function POST(request: NextRequest) {
>   const body = await request.json();
>   const { taskId, state, resultJson, failCode, failMsg } = body.data;
>
>   if (state === 'success') {
>     const urls = JSON.parse(resultJson).resultUrls;
>     console.log('Generated:', urls);
>   } else if (state === 'failed') {
>     console.error(`Task ${taskId} failed: ${failCode} - ${failMsg}`);
>   }
>
>   return NextResponse.json({ status: 'ok' });
> }
> ```

**2. コールバックを指定してタスクを送信する**

リクエストに `request_type: "callback"` と受信先の `callback_url` を含めます。

> [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": "callback",
>     "callback_url": "https://your-domain.com/webhook/apixo",
>     "input": {
>       "mode": "text-to-image",
>       "prompt": "A beautiful landscape",
>       "aspect_ratio": "16:9"
>     }
>   }'
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> const response = await fetch('https://api.apixo.ai/api/v1/generateTask/nano-banana', {
>   method: 'POST',
>   headers: {
>     'Authorization': 'Bearer YOUR_API_KEY',
>     'Content-Type': 'application/json',
>   },
>   body: JSON.stringify({
>     request_type: 'callback',
>     callback_url: 'https://your-domain.com/webhook/apixo',
>     input: {
>       mode: 'text-to-image',
>       prompt: 'A beautiful landscape',
>       aspect_ratio: '16:9',
>     },
>   }),
> });
> ```

> [tab] Python
>
> ```python theme={null}
> import requests
>
> response = requests.post(
>     'https://api.apixo.ai/api/v1/generateTask/nano-banana',
>     headers={
>         'Authorization': 'Bearer YOUR_API_KEY',
>         'Content-Type': 'application/json',
>     },
>     json={
>         'request_type': 'callback',
>         'callback_url': 'https://your-domain.com/webhook/apixo',
>         'input': {
>             'mode': 'text-to-image',
>             'prompt': 'A beautiful landscape',
>             'aspect_ratio': '16:9',
>         },
>     }
> )
> ```

## Webhook ペイロード

### 成功

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

### 失敗

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

### ペイロードのフィールド

**taskId** `string`

タスクを一意に識別する ID です。

**state** `string`

タスクの最終状態です。`success` または `failed` が返ります。

**resultJson** `string`

`resultUrls` 配列を含む JSON 文字列です。成功時にのみ返ります。

**costTime** `integer`

処理時間をミリ秒で示します。

**failCode** `string`

エラーコードです。失敗時にのみ返ります。

**failMsg** `string`

エラーを説明するメッセージです。失敗時にのみ返ります。

## 再送ポリシー

Webhook エンドポイントが HTTP 200 を返さない場合は、次の間隔で再送します。

| 再送回数 | 待機時間 |
| - | - |
| 1 回目の再送 | 30 秒 |
| 2 回目の再送 | 2 分 |
| 3 回目の再送 | 10 分 |

3 回の配信がすべて失敗すると、その Webhook の配信は終了します。その後も[タスク状態の確認](https://apixo.ai/docs/ja/api-reference/status-task.md)エンドポイントで状態を照会できます。

## セキュリティの推奨事項

### 冪等性を確保する

> [!NOTE]
>
> 同じ Webhook が複数回届くことがあります。`taskId` で重複を判定し、同じ結果を二重に処理しないようにしてください。

```javascript theme={null}
const processedTasks = new Set();

app.post('/webhook/apixo', (req, res) => {
  const { taskId } = req.body.data;
  
  if (processedTasks.has(taskId)) {
    return res.status(200).send('Already processed');
  }
  
  processedTasks.add(taskId);
  // Process the task...
  
  res.status(200).send('OK');
});
```

### HTTPS のみを使う

通信中のデータを暗号化するため、Webhook エンドポイントには常に HTTPS を使ってください。

## Webhook をテストする

開発中にローカルサーバーを外部からアクセスできるようにするには、[ngrok](https://ngrok.com) を使います。

```bash theme={null}
ngrok http 3000
# Returns: https://abc123.ngrok.io — use this as your callback_url
```

> [!TIP]
>
> コールバックモードでも、デバッグ時などに API でタスクの状態を確認できます。


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