簡単な比較
| 側面 | ポーリング (非同期) | Webhook (コールバック) |
|---|---|---|
| セットアップ | 単純 | パブリックエンドポイントが必要です |
| リアルタイム | ほぼリアルタイム | インスタント |
| API コール | タスクごとに複数 | タスクごとに 1 つ |
| 最適な用途 | 開発、クライアントアプリ | 本番サーバー |
| インフラストラクチャ | なし | HTTPS エンドポイント |
ポーリングを使用する場合
次の場合にポーリングを選択します:- クライアント側アプリケーションの構築
- プロトタイピングまたはテスト
- 公開サーバーをお持ちではありません
- 少量のタスクの処理
基本的なポーリングの実装
async function pollForResult(model, taskId, apiKey) {
const interval = 3000; // 3 seconds
const maxAttempts = 60;
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();
if (data.state === 'success') {
return JSON.parse(data.resultJson).resultUrls;
}
if (data.state === 'failed') {
throw new Error(data.failMsg);
}
await new Promise(r => setTimeout(r, interval));
}
throw new Error('Timeout');
}
指数バックオフ
効率を高めるには、指数バックオフを使用します。async function pollWithBackoff(model, taskId, apiKey) {
let interval = 3000; // Start at 3s
const maxInterval = 30000; // Max 30s
const maxTime = 300000; // 5 min timeout
let elapsed = 0;
while (elapsed < maxTime) {
const response = await fetch(
`https://api.apixo.ai/api/v1/statusTask/${model}?taskId=${taskId}`,
{ headers: { 'Authorization': `Bearer ${apiKey}` } }
);
const { data } = await response.json();
if (data.state === 'success') {
return JSON.parse(data.resultJson).resultUrls;
}
if (data.state === 'failed') {
throw new Error(data.failMsg);
}
await new Promise(r => setTimeout(r, interval));
elapsed += interval;
interval = Math.min(interval * 1.5, maxInterval);
}
throw new Error('Timeout');
}
モデルタイプ別の推奨間隔
| モデルタイプ | 初期待機 | ポーリング間隔 | 最大待機時間 |
|---|---|---|---|
| 画像(高速) | 5s | 3s | 2分 |
| 画質) | 10s | 5s | 3分 |
| 動画 | 60s | 15s | 10分 |
| 音声 | 30s | 10s | 5分 |
Webhook を使用する場合
次の場合に Webhook を選択します:- 本番サーバーの実行
- 大量のタスクの処理
- リアルタイムの通知が必要です
- API 呼び出しを最小限に抑えたい
Webhook セットアップ
1。エンドポイントを作成します:- Express.js
- FastAPI
- Next.js
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);
// Process your images/videos
} else if (state === 'failed') {
console.error(`Task ${taskId} failed: ${failCode}`);
}
res.status(200).send('OK');
});
app.listen(3000);
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']}")
return {'status': 'ok'}
// 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 } = 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}`);
}
return NextResponse.json({ status: 'ok' });
}
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',
},
}),
});
Webhook 要件
- HTTPS 経由でパブリックにアクセスできる必要があります
- 30 秒以内に HTTP 200 と応答する必要があります
- 重複した配信を処理する必要があります (冪等性のために
taskIdを使用します)
再試行ポリシー
Webhook が失敗した場合:| 試み | 遅れ |
|---|---|
| 1回目のリトライ | 30秒 |
| 2回目の再試行 | 2分 |
| 3回目のリトライ | 10分 |
ハイブリッドアプローチ
信頼性を最大限に高めるには、両方のアプローチを組み合わせます。class TaskManager {
constructor(apiKey) {
this.apiKey = apiKey;
this.pendingTasks = new Map();
}
async submit(model, input, callbackUrl = null) {
const response = await fetch(
`https://api.apixo.ai/api/v1/generateTask/${model}`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
request_type: callbackUrl ? 'callback' : 'async',
callback_url: callbackUrl,
input,
}),
}
);
const { data } = await response.json();
if (!callbackUrl) {
// Fallback to polling if no webhook
return this.poll(model, data.taskId);
}
// Track task for webhook
this.pendingTasks.set(data.taskId, { model, status: 'pending' });
return data.taskId;
}
handleWebhook(body) {
const { taskId, state, resultJson, failMsg } = body.data;
if (state === 'success') {
this.pendingTasks.delete(taskId);
return JSON.parse(resultJson).resultUrls;
}
if (state === 'failed') {
this.pendingTasks.delete(taskId);
throw new Error(failMsg);
}
}
async poll(model, taskId) {
// Fallback polling implementation
return pollWithBackoff(model, taskId, this.apiKey);
}
}
ngrok を使用したローカル開発
Webhook をローカルでテストするには:# Install ngrok
npm install -g ngrok
# Start your local server
node server.js # runs on port 3000
# Tunnel to local server
ngrok http 3000
# Returns: https://abc123.ngrok.io
# Use ngrok URL as callback_url
まとめ
| シナリオ | おすすめ |
|---|---|
| 開発/テスト | ポーリング |
| クライアント側アプリ | ポーリング |
| 本番バックエンド | Webhook |
| 高負荷 | Webhook |
| 高い信頼性 | ハイブリッド(Webhook + ポーリング フォールバック) |
シンプルさを重視してポーリングから始め、アプリケーションの規模に応じて Webhook に移行します。