Handling Asynchronous AI Video Generation with Webhooks: End-to-End Implementation
ToAPIs video generation is asynchronous: POST /v1/videos/generations returns a task, and the video URL is available only after the job finishes. Official docs fetched on 2026-11-30 describe Task Webhooks as a signed, at-least-once completion signal, with polling as the fallback when delivery is delayed or exhausted.
This tutorial implements that contract end to end. It does not invent a webhook_url field, a generic X-ToAPIs-Signature header, succeeded statuses, a 99.95% SLA, or sub-50ms notification latency — those claims appear in planning drafts and are not on the official pages. For a contract comparison of Seedance, Kling, Hailuo, and Wan IDs, see The Ultimate AI Video Generation API Benchmark 2026.
1. TL;DR & Performance Overview
- Primary signal. ToAPIs sends one final event when an asynchronous image or video task completes or permanently fails:
generation.completed,generation.failed, or the test typeendpoint.test. Delivery is at least once; persist the eventidand return2xxfor duplicates without repeating side effects. - Configure the Token before you send
callback_url. Set an HTTPS default callback URL, generate the 32-byte signing secret (shown only when generated or rotated), enable Task Webhooks, save, and send a test event. A missing configuration pluscallback_urlyields400 webhook_not_configured. - Same-origin request URLs. If the request omits
callback_url, the Token default is used. A request-level URL may only change the path and query; scheme, hostname, and port must match the default. - Verify the official signed bytes.
event_id + "." + timestamp + "." + raw_request_bodywith HMAC-SHA256. Reject a first delivery more than five minutes off local time. During the 24 hours after secret rotation, accept any validv1signature from the current or previous secret. - Poll as fallback. Official guidance is to use Webhooks as the primary completion signal and poll
GET https://toapis.com/v1/videos/generations/{task_id}no faster than every 5–10 seconds, with jitter andRetry-After. The official example uses 60 attempts at a 10-second interval (600 seconds).
2. Official IDs, Webhook Architecture, and What Is Documented
Generation examples use https://toapis.com (mainland China: https://toapis.cn) and a model API key:
POST https://toapis.com/v1/videos/generations
Authorization: Bearer <API_KEY>
GET https://toapis.com/v1/videos/generations/{task_id}
Ordinary image and video tasks may also be queried with GET /v1/tasks/{task_id}. Poll statuses are queued, in_progress, completed, and failed. On completed, read result.data[0].url. expires_at is a Unix timestamp; the Task Webhooks page states that result expiry is finish time plus 30 days, and the file-retention API documents a platform default of 30 days.
Request-level callback_url coverage (2026-11-30). The field is explicitly documented on Seedance generation pages (including seedance-2-5, seedance-2-5-flash, and the Seedance 2.0 IDs) and on MiniMax Hailuo 2.3 / H3 pages. It was not listed in the request parameter lists of the Wan 3.0, Wan 2.6 / Flash, or Kling generation pages we checked. The samples below therefore use seedance-2-5, a documented T2V ID that also lists callback_url. The platform Token default still applies when the field is omitted and Webhooks are enabled.
Two hosts, two tokens. Task submission and status queries use https://toapis.com with the model API key. Account webhook management (GET/PATCH /api/v1/webhook, rotate-secret, test, events) is documented at https://api.toapis.com and requires a system access token. Model keys are not accepted on those management endpoints. You can skip the management API entirely and configure the Token in the console.
The official first-time setup order on the Get Webhook configuration page is:
POST /api/v1/webhook/rotate-secret— thesecretis returned only once; save it immediately. This step does not enable callbacks.- Configure signature verification on the receiver (next section).
PATCH /api/v1/webhookwith the HTTPS callback URL andenabled=true. First enablement or a URL change creates anendpoint.testevent and returnsverification_event_id. A saved configuration does not mean the receiver passed verification.POST /api/v1/webhook/testorGET /api/v1/webhook/events/{event_id}to inspect delivery.
Callback endpoints must use HTTPS and cannot contain userinfo or fragments. Private, loopback, link-local, reserved, or disallowed DNS/IP destinations and illegal ports are rejected. DNS and SSRF checks run again for every delivery.

Figure 1. A documented ToAPIs flow: submit the task, receive a signed final event, and query the official status endpoint if delivery is delayed or exhausted.
Related: Task Webhooks · Get Video Task Status · Async task rate limits · Seedance 2.5 reference · Video family comparison
3. Production Implementation: cURL & Python
Step 1: Configure the Token (console or management API)
# Management API — system access token, not the sk- model key.
# Mainland China: https://api.toapis.cn
curl --request POST \
--url 'https://api.toapis.com/api/v1/webhook/rotate-secret' \
--header 'Authorization: Bearer '"$TOAPIS_SYSTEM_ACCESS_TOKEN" \
--header 'Content-Type: application/json' \
--data '{"api_key_id": 123}'
curl --request PATCH \
--url 'https://api.toapis.com/api/v1/webhook' \
--header 'Authorization: Bearer '"$TOAPIS_SYSTEM_ACCESS_TOKEN" \
--header 'Content-Type: application/json' \
--data '{
"api_key_id": 123,
"url": "https://example.com/webhooks/toapis/tasks",
"enabled": true
}'
curl --request POST \
--url 'https://api.toapis.com/api/v1/webhook/test' \
--header 'Authorization: Bearer '"$TOAPIS_SYSTEM_ACCESS_TOKEN" \
--header 'Content-Type: application/json' \
--data '{"api_key_id": 123}'
Replace 123 with the positive integer ID of your ordinary model key, not the sk- secret. Store the rotated secret as TOAPIS_WEBHOOK_SECRET. During rotation, keep the previous secret until previous_secret_expires_at.
Step 2: Submit a seedance-2-5 job, optionally with callback_url
curl --request POST \
--url 'https://toapis.com/v1/videos/generations' \
--header 'Authorization: Bearer '"$TOAPIS_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"model": "seedance-2-5",
"prompt": "A lantern-lit alley after rain, slow push-in, soft synchronized footsteps",
"duration": 5,
"resolution": "1080p",
"aspect_ratio": "16:9",
"generate_audio": true,
"client_business_id": "order_webhook_demo_001",
"callback_url": "https://example.com/webhooks/toapis/tasks"
}'
If you omit callback_url, the Token default is used. The request-level URL in this example is valid only when it keeps the same scheme, hostname, and port as that default (path and query may differ).
Step 3: Receiver that verifies the official signature
Use the raw request body. The snippet below follows the official Python example on the Task Webhooks page, then maps the documented event types.
import hashlib
import hmac
import os
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
SECRETS = [s for s in (os.environ.get("TOAPIS_WEBHOOK_SECRET"), os.environ.get("TOAPIS_WEBHOOK_SECRET_PREV")) if s]
SEEN_EVENTS: set[str] = set() # replace with Redis / a database in production
def verify(headers: dict[str, str], raw_body: bytes, secrets: list[str]) -> bool:
event_id = headers["X-ToAPIs-Webhook-Id"]
timestamp = int(headers["X-ToAPIs-Webhook-Timestamp"])
if abs(time.time() - timestamp) > 300:
return False
signed = f"{event_id}.{timestamp}.".encode() + raw_body
received = [v.removeprefix("v1=") for v in headers["X-ToAPIs-Webhook-Signature"].split(",")]
return any(
hmac.compare_digest(hmac.new(s.encode(), signed, hashlib.sha256).hexdigest(), r)
for s in secrets
for r in received
)
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
length = int(self.headers.get("Content-Length", "0"))
raw_body = self.rfile.read(length)
try:
headers = {k: v for k, v in self.headers.items()}
if not verify(headers, raw_body, SECRETS):
self.send_response(401)
self.end_headers()
return
except (KeyError, ValueError):
self.send_response(400)
self.end_headers()
return
import json
event = json.loads(raw_body)
event_id = event["id"]
if event_id in SEEN_EVENTS:
self.send_response(200)
self.end_headers()
return
SEEN_EVENTS.add(event_id)
event_type = event.get("type")
data = event.get("data") or {}
if event_type == "endpoint.test":
# Verification or console test; no generation asset.
pass
elif event_type == "generation.completed" and data.get("status") == "SUCCESS":
task_id = data["task_id"]
url = ((data.get("result") or {}).get("data") or [{}])[0].get("url")
# Persist task_id, url, data.billing, data.expires_at; download promptly.
_ = (task_id, url)
elif event_type == "generation.failed" and data.get("status") == "FAILURE":
# Failed events arrive after refund / billing finalization.
_ = data.get("task_id"), data.get("error")
self.send_response(200)
self.end_headers()
if __name__ == "__main__":
HTTPServer(("0.0.0.0", 8080), Handler).serve_forever()
A webhook is a snapshot from event creation time. Task queries read the latest confirmed usage and billing. Do not wait for a webhook before you can observe the task, and do not expect retries to backfill later amounts — retries reuse the original payload.
Step 4: Bounded poller fallback
import os
import random
import time
import requests
API_KEY = os.environ["TOAPIS_API_KEY"]
BASE = "https://toapis.com"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}
def poll_task(task_id: str, deadline_s: int = 600) -> str:
url = f"{BASE}/v1/videos/generations/{task_id}"
interval = 10.0
start = time.time()
time.sleep(5)
while time.time() - start < deadline_s:
poll = requests.get(url, headers=HEADERS, timeout=15)
if poll.status_code in {429, 503}:
retry_after = poll.headers.get("Retry-After")
wait = float(retry_after) if retry_after else min(interval * 2, 120)
time.sleep(wait + random.uniform(0, 1.5))
continue
poll.raise_for_status()
data = poll.json()
status = data.get("status")
if status == "completed":
return data["result"]["data"][0]["url"]
if status == "failed":
raise RuntimeError(f"Generation failed: {data.get('error')}")
time.sleep(interval + random.uniform(0, 1.5))
interval = min(interval * 1.5, 30.0)
raise TimeoutError(
f"Task {task_id} exceeded {deadline_s}s; query the same id before submitting a duplicate"
)
4. Error Handling & Status Matrix
| Signal | Contract | Handling |
|---|---|---|
generation.completed + data.status=SUCCESS | Webhook | Read data.task_id and data.result.data[0].url. Billing, when present, uses data.billing.status of settled or refunded. Amounts are decimal strings. |
generation.failed + data.status=FAILURE | Webhook | Sent after internal retries and refund or billing finalization. Temporary failures do not emit an event. data.error does not guarantee the reason field available on some task queries. |
endpoint.test | Webhook | Same signed contract; data.task_id is endpoint_test in the official example. Do not treat it as a real generation. |
queued / in_progress / completed / failed | Poll path | Lowercase statuses and integer progress. Use this path as the source of truth if the webhook is late or exhausted. |
400 webhook_not_configured | Submit | Enable Webhooks, set the default URL, and generate a secret before sending callback_url. |
Non-2xx or 10s timeout | Delivery | ToAPIs retries on the official schedule. Return 2xx only after the event id is persisted. |
429 / 503 | Submit or poll | Honor Retry-After, add jitter, and back off. Status queries remain available when the submit limiter is temporarily unavailable. |
| URL expiry | Both | Result URLs can expire. Download and store required assets promptly. Webhook URLs are a snapshot; they are not rewritten on retry. |
Webhook task_type is image or video. Official examples show that results never contain channel IDs, upstream task IDs or keys, internal credentials, or private task data. Real-avatar verification callbacks, payment Webhooks, and OAuth callbacks keep their existing contracts and are not Task Webhooks.
5. Pricing & FinOps ROI
Webhooks do not change how a video job is billed. Charge types on the completed task (and on a successful event’s data.usage) are per_request, per_second, or per_token. When a charge is confirmed, both the webhook and the task query return billing.status=settled with credits and cost_usd as decimal strings. Failed events that have finished refunding are refunded with both amounts "0". If the amount cannot be confirmed, the whole data.billing object is omitted — that does not mean the task was free.
Planning drafts sometimes claim that polling every 3 seconds for 10,000 daily jobs “saves” a fixed request budget. Official guidance is the opposite on the poll interval: do not poll faster than every 5–10 seconds. Use Webhooks to avoid tight loops, then keep a bounded poller for missed deliveries. There is no official “sub-50ms notification” figure and no 99.95% webhook SLA on the pages checked on 2026-11-30.
For dated catalog quotes of the video families used in the samples, see the comparison article. seedance-2-5 is billed per_token on the 2026-11-30 public catalog; do not invent a per-second budget for it. Unauthenticated GET /api/v1/pricing returned 401; credits are the primary snapshot, and USD uses the public page’s 1 credit ≈ $0.005 estimate.
6. Frequently Asked Questions
The header FAQ covers per-model callback_url coverage, the official signature headers, callback outages and the retry schedule, poll vs webhook status values, and why model API keys cannot call the management API. Two implementation notes worth repeating:
- Persist the event
idbefore you start download or billing side effects, so a delayed retry can return2xxsafely. - Media URLs on a webhook can differ from a later task query because access policies differ. Prefer
url(and, for some Seedance results, usefallback_urlonly if the primary URL cannot be accessed).
7. Action Checklist
- In the console or via
https://api.toapis.com/api/v1/webhook, set an HTTPS default callback URL, generate and store the signing secret, enable Task Webhooks, and sendendpoint.test. - Verify
X-ToAPIs-Webhook-Signatureoverevent_id.timestamp.raw_bodywith HMAC-SHA256 and a five-minute timestamp window. Accept eitherv1value during the 24-hour rotation overlap. - Submit documented model IDs to
POST https://toapis.com/v1/videos/generations. Includecallback_urlonly when the Token is already configured; keep path/query changes same-origin. - Branch on
generation.completed/generation.failedanddata.statusSUCCESS/FAILURE. Persistdata.task_idand downloaddata.result.data[0].urlpromptly. - Keep a bounded poller on
GET /v1/videos/generations/{task_id}(queued/in_progress/completed/failed), with 5–10 second intervals, jitter, andRetry-After, for delayed or exhausted delivery.