A Real Case of Wasted Waiting Time
Many indie developers go through this flow the first time they work with async tasks: send a request → get a task_id → write a while True polling loop → check the status every few seconds → wait for the result.
Sounds harmless? Do the math. Suppose your tasks take an average of 3 minutes, with a 5-second polling interval—that's 36 idle queries per task. If you run 200 tasks a day, that's 7,200 worthless query requests, and during all that time you have to keep the script alive—you can't shut your laptop or lose your internet connection.
It's even worse in team scenarios. Our small team once used a polling approach for batch copywriting generation. The script was running on someone's laptop, that person went to a meeting, the laptop went to sleep, and polling for 20+ tasks was completely interrupted. Afterward, we had to rerun everything by hand—an entire afternoon gone. This isn't a technical difficulty problem; it's a hidden labor cost created by an architectural choice.
That's exactly where webhook callbacks deliver value: turning "you go find the result" into "the result comes to you." When a task completes, the server actively POSTs to your designated URL. Your code does whatever it needs to do, and the time cost of handling results approaches zero.
Why We Chose ThisToken.AI for This Demo
For indie developers and small teams, integrating async task APIs raises two big fears: first, callback formats vary from vendor to vendor, making adaptation costly; second, callback security (how to verify that a request genuinely comes from the provider) is something you have to figure out from scratch.
ThisToken.AI aggregates multiple model capabilities under a unified API. Async tasks and webhook callbacks follow the same format, and it works right after registration—no need to open accounts with each vendor separately or read each of their docs. As for pricing, refer to the official pricing page; we make no numeric promises here.
Step 1: Register and Get Your API Key
- Go to https://api.thistoken.ai/register and sign up with your email;
- After logging in, go to the console, click "Create" on the "API Keys" page, then copy and store the key safely (we recommend putting it in an environment variable rather than hardcoding it into your repo—if you've read our previous article on key management, you know the cost of leakage);
- Make sure your server has a publicly accessible address. For local development, you can use a tunneling tool like
ngrokto generate a temporary one.
Step 2: Get Your First Code Running
The following Python code demonstrates the complete loop: create an async task, register a webhook callback URL, and receive the callback with Flask.
import os
import time
import hmac
import hashlib
import requests
from flask import Flask, request, abort
# 建议通过环境变量注入,避免硬编码
API_KEY = os.environ.get("THISTOKEN_API_KEY")
client = requests.Session()
client.headers.update({"Authorization": f"Bearer {API_KEY}"})
app = Flask(__name__)
# ========== 1. 发起异步任务,并声明回调地址 ==========
def create_task(prompt: str, webhook_url: str) -> str:
resp = client.post(
"https://api.thistoken.ai/v1/tasks",
json={
"type": "text_generation",
"input": {"prompt": prompt},
"callback": {
"url": webhook_url,
# 回调事件类型:任务完成 / 失败都通知
"events": ["task.completed", "task.failed"],
},
},
timeout=30,
)
resp.raise_for_status()
return resp.json()["task_id"]
# ========== 2. 接收回调 ==========
@app.post("/webhook/thistoken")
def receive_webhook():
# 验证签名:确认请求确实来自服务商,防止伪造
signature = request.headers.get("X-Signature", "")
raw_body = request.get_data()
secret = os.environ["WEBHOOK_SECRET"].encode()
expected = hmac.new(secret, raw_body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(signature, expected):
abort(401)
payload = request.get_json()
event = payload["event"]
task_id = payload["task_id"]
if event == "task.completed":
result = payload["result"]
# 这里做你的业务处理:入库、发通知、触发下一步
print(f"[完成] task={task_id}, 结果长度={len(result['text'])}")
elif event == "task.failed":
print(f"[失败] task={task_id}, 原因={payload['error']}")
return {"ok": True}, 200
if __name__ == "__main__":
# 本地开发:先用内网穿透工具暴露 5000 端口
create_task(
prompt="为一款便携咖啡机写一段 100 字的电商文案",
webhook_url="https://your-tunnel.example.com/webhook/thistoken",
)
app.run(port=5000)Three key points are worth noting:
Don't skip signature verification. Your callback endpoint is exposed to the public internet—anyone who knows the URL can forge requests. HMAC signature verification is the most basic line of defense.
Callback handling must be idempotent. Network jitter can cause the same event to be delivered multiple times. Use task_id for deduplication to avoid processing business logic twice.
The callback endpoint should only receive, not do heavy work. Return 200 immediately upon receiving a callback, and hand off time-consuming business processing to a queue or background thread. Otherwise, the provider may treat the delivery as a timeout failure and retry, creating an avalanche.
Before and After: The Math Is Easy
After switching to the webhook approach, the changes for our small team were immediate:
- Polling requests: from ~7,200 per day down to 0, keeping only the two necessary request types—creating tasks and receiving callbacks;
- Human supervision time: from "whoever's laptop hosts the script is responsible" down to zero—completed tasks land in the database automatically, with async notifications delivered to the right place;
- Failure recovery: from "discover the interruption, rerun everything by hand for half a day" down to fallback polling when callbacks don't arrive (we recommend keeping a low-frequency scheduled reconciliation task to catch missed callbacks—it's the last line of defense for fault tolerance).
What you save isn't just a few cents in request fees—it's the psychological burden of "I don't dare close my laptop."
Summary
Async tasks + webhooks are the standard way for small teams to gain reliable task processing at minimal cost: integrate once, maintenance-free for the long run. Today you can spend ten minutes registering an account, getting the code above running, verifying the callback chain first, and then gradually connecting it to your real business.
Registration link: https://api.thistoken.ai/register
---
Ready to try it yourself? Sign up at https://api.thistoken.ai/register to get your API key and start building.
Token.AI を試してみませんか?
プロジェクトレベルの API Key を作成し、コンソールでチャネルを有効にして、ルーティング、予算、監査ログを設定しましょう。
注册 ThisToken.AI 并获取 API Key