Failure Cases First
When integrating AI-powered asynchronous APIs, many indie developers and small teams fall into the same traps. If you're doing anything similar to the four scenarios below, chances are you've already been caught out.
Crash #1: Calling an async API with a synchronous mindset. You call a batch document summarization task API, get back a task_id, and then write a while True loop to poll endlessly. Everything works fine in local testing, but once you go live and tasks pile up, your server's CPU gets eaten up by polling, and the remote API starts rate-limiting you. Worse, tasks take two or three minutes on average, so your request timeout has long since expired, and all the user sees is a blank screen.
Crash #2: The Webhook callback URL is a dead end. During registration, you casually filled in a callback URL pointing to your local dev localhost:8000. The task finishes, and ThisToken.AI's servers try to push the result to you—to whom? To themselves? All the results are lost, and you have to fish them back one by one via the polling API, with no idea which result corresponds to which task.
Crash #3: The callback arrives, but nobody claims it. You finally got the callback working—the Webhook's POST request hits your service—but your code has no logic to handle this event at all. The request lands in the logs, nobody parses it, and the task status stays "processing" forever. The user waits forever, then checks the backend only to find the result actually arrived long ago.
Crash #4: Skipping callback signature verification, leaving the API exposed. You think, "I'm the only one using this project, so signature verification doesn't matter." Then your callback URL gets discovered by a scanner, forged requests with fake data come flooding in, and your system accepts them all and writes them to the database. When something goes wrong, you can't even tell whether the data is real or fake.
The common thread across these four pitfalls: treating asynchronous tasks as synchronous ones, and treating Webhooks as decorations. Here's the right way to do it.
The Right Path: Getting ThisToken.AI Async Tasks + Webhooks Working
Step 1: Register and Get Your API Key
- Go to https://api.thistoken.ai/register and sign up with your email (pricing and plans are subject to the official pricing page).
- After logging in, go to the console, create a Key on the "API Keys" page, and copy and store it securely—it's only shown once.
- In "Webhook Settings," fill in your callback URL. It must be a publicly accessible HTTPS address. For local development, use a tunneling tool like ngrok to create a temporary mapping.
Step 2: Get Your First Code Working
Using Python as an example, first install the dependencies:
pip install requests flaskThe following code has two parts: submitting an async task, and receiving the Webhook callback with Flask.
import os
import hmac
import hashlib
import requests
from flask import Flask, request, jsonify
API_KEY = os.environ["THISTOKEN_API_KEY"]
BASE_URL = "https://api.thistoken.ai/v1"
WEBHOOK_SECRET = "your-webhook-secret" # 控制台 Webhook 设置页可查看
app = Flask(__name__)
results = {} # 生产环境请用数据库
def submit_task(text: str) -> str:
"""提交一个异步摘要任务,返回 task_id"""
resp = requests.post(
f"{BASE_URL}/tasks/summarize",
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"text": text,
"callback_url": "https://your-domain.com/webhook/thistoken",
},
timeout=30,
)
resp.raise_for_status()
return resp.json()["task_id"]
@app.route("/webhook/thistoken", methods=["POST"])
def webhook():
# 1. 验签:确认请求确实来自 ThisToken.AI
signature = request.headers.get("X-Signature", "")
expected = hmac.new(
WEBHOOK_SECRET.encode(),
request.get_data(),
hashlib.sha256,
).hexdigest()
if not hmac.compare_digest(signature, expected):
return jsonify({"error": "invalid signature"}), 401
# 2. 解析事件,认领结果
payload = request.get_json()
if payload.get("event") == "task.completed":
task_id = payload["task_id"]
results[task_id] = payload["result"]
print(f"任务 {task_id} 完成,已入库")
# 3. 快速返回 200,告诉对方"收到了"
return "", 200
if __name__ == "__main__":
task_id = submit_task("这里放一段需要摘要的长文本……")
print(f"任务已提交:{task_id},等待回调…")
app.run(port=8000)A few key points—compare them against the crash scenes above:
- Return as soon as you get the task_id; don't wait for the result.
submit_taskfinishes immediately after sending the request, leaving the waiting to the Webhook. - The callback URL must be a publicly reachable HTTPS address. Use a tunnel for local debugging, then switch to your production domain after launch.
- Signature verification is not optional. Compare
X-Signatureusing HMAC, and usehmac.compare_digestinstead of==to prevent timing attacks. The exact signature algorithm and header names are subject to the official docs, but the approach is the same. - Handle callbacks quickly. On receiving a request, persist it to storage first and return 200 fast; push complex processing to background tasks. Callback timeouts with retries are a common platform-side mechanism—if your endpoint takes too long, you'll receive duplicate pushes, so your processing logic must be idempotent (check whether a task_id already exists before writing duplicates).
- Polling is a fallback, not the main path. Keep a task-status query by task_id as a compensating measure for when Webhooks get lost, but don't rely on it as your primary mechanism.
Pre-Launch Checklist
- The callback URL is publicly accessible and configured with HTTPS;
- Signature verification is enabled, and the secret is not hardcoded in the repository;
- Callback handling is idempotent—duplicate pushes won't produce dirty data;
- Task failure events (e.g.,
task.failed) also have corresponding handling and alerts; - There's a fallback endpoint for manually querying task status.
Once you get this workflow running, integrating async tasks goes from "hoping for the best" to "fully traceable": every submission has a task_id, every callback is verified and persisted, and when something goes wrong, you can follow the logs to pinpoint the exact step.
If you haven't registered yet, you can start here: https://api.thistoken.ai/register
---
Tired of juggling provider integrations? Register at https://api.thistoken.ai/register and call every model through one base_url.
Хотите попробовать Token.AI?
Создайте API Key уровня проекта, включите каналы в консоли и настройте маршрутизацию, бюджеты и журналы аудита.
注册 ThisToken.AI 并获取 API Key