ToAPIs
    AccueilToAPIs
    Génération d'imagesGPT Image 2.6, Gemini, FLUX…Génération de vidéosSeedance, Veo, Kling, Sora…Chat et rédactionGPT-5.6, Claude, DeepSeek…Voix et musiqueVoix off, TTS, audio
    Nouvelle sortieSeedance 2.5
    TarifsDocumentation APIMCP
    BlogAlternatives
    Se connecterCommencer gratuitement
    Tous les modèlesTarifsDocumentation APIMCPBlogAlternatives
    Se connecterCommencer gratuitement

    Langue

    1. Accueil
    2. Blog
    3. Tutoriel
    4. Handling Asynchronous AI Video Generation with Webhooks: End-to-End Implementation
    Retour à tous les articles
    tutorial2026-11-307 min de lecture

    Handling Asynchronous AI Video Generation with Webhooks: End-to-End Implementation

    End-to-end ToAPIs tutorial for async video jobs: configure Task Webhooks, verify official HMAC-SHA256 signatures, handle generation.completed and generation.failed, and fall back to the documented poll path when delivery is delayed or exhausted.

    ToAPIs Engineering & Evaluation Team
    WebhooksAsync VideoTask StatusPollingAPI
    TL;DR - Points clés
    • ToAPIs documents a signed Task Webhooks contract for asynchronous image and video tasks: one final event on completion or permanent failure, delivered at least once. Deduplicate by event id. Official pages fetched on 2026-11-30 do not publish a 99.95% SLA or sub-50ms notification latency.
    • Configure the Token first: HTTPS default callback URL, 32-byte signing secret, enable Task Webhooks, then send a test event. You can do this in the console or via the account management API on https://api.toapis.com (system access token, not the model API key).
    • If a request omits callback_url, ToAPIs uses the Token default. A request-level URL may only change the path and query and must keep the same scheme, hostname, and port. Sending callback_url when Webhooks are not configured returns 400 webhook_not_configured.
    • Verify X-ToAPIs-Webhook-Id, X-ToAPIs-Webhook-Timestamp, and X-ToAPIs-Webhook-Signature (HMAC-SHA256 over event_id.timestamp.raw_body). Do not invent an X-ToAPIs-Signature header or treat poll statuses as webhook statuses: payloads use SUCCESS / FAILURE, queries use queued / in_progress / completed / failed.
    • Only 2xx is success. ToAPIs does not follow redirects, times out after 10 seconds, and retries after about 10s, 30s, 2min, 10min, 1h, 6h, and 24h. Keep a bounded poller on GET /v1/videos/generations/{task_id} as the fallback.

    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 type endpoint.test. Delivery is at least once; persist the event id and return 2xx for 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 plus callback_url yields 400 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_body with HMAC-SHA256. Reject a first delivery more than five minutes off local time. During the 24 hours after secret rotation, accept any valid v1 signature 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 and Retry-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:

    text
    POST https://toapis.com/v1/videos/generations
    Authorization: Bearer <API_KEY>
    
    text
    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:

    1. POST /api/v1/webhook/rotate-secret — the secret is returned only once; save it immediately. This step does not enable callbacks.
    2. Configure signature verification on the receiver (next section).
    3. PATCH /api/v1/webhook with the HTTPS callback URL and enabled=true. First enablement or a URL change creates an endpoint.test event and returns verification_event_id. A saved configuration does not mean the receiver passed verification.
    4. POST /api/v1/webhook/test or GET /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.

    Submit a video job through the gateway, deliver a signed callback, and fall back to a dotted poll path

    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)

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

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

    python
    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

    python
    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

    SignalContractHandling
    generation.completed + data.status=SUCCESSWebhookRead 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=FAILUREWebhookSent 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.testWebhookSame signed contract; data.task_id is endpoint_test in the official example. Do not treat it as a real generation.
    queued / in_progress / completed / failedPoll pathLowercase statuses and integer progress. Use this path as the source of truth if the webhook is late or exhausted.
    400 webhook_not_configuredSubmitEnable Webhooks, set the default URL, and generate a secret before sending callback_url.
    Non-2xx or 10s timeoutDeliveryToAPIs retries on the official schedule. Return 2xx only after the event id is persisted.
    429 / 503Submit or pollHonor Retry-After, add jitter, and back off. Status queries remain available when the submit limiter is temporarily unavailable.
    URL expiryBothResult 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 id before you start download or billing side effects, so a delayed retry can return 2xx safely.
    • Media URLs on a webhook can differ from a later task query because access policies differ. Prefer url (and, for some Seedance results, use fallback_url only 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 send endpoint.test.
    • Verify X-ToAPIs-Webhook-Signature over event_id.timestamp.raw_body with HMAC-SHA256 and a five-minute timestamp window. Accept either v1 value during the 24-hour rotation overlap.
    • Submit documented model IDs to POST https://toapis.com/v1/videos/generations. Include callback_url only when the Token is already configured; keep path/query changes same-origin.
    • Branch on generation.completed / generation.failed and data.status SUCCESS / FAILURE. Persist data.task_id and download data.result.data[0].url promptly.
    • Keep a bounded poller on GET /v1/videos/generations/{task_id} (queued / in_progress / completed / failed), with 5–10 second intervals, jitter, and Retry-After, for delayed or exhausted delivery.

    Découvrir les modèles cités dans cet article

    ByteDanceVIDEO

    Seedance 2.5

    Tarif actuel : Input 2,000 credits/1M, Output 2,000 credits/1M
    Guide du modèleEssayer dans la consoleObtenir une clé d'API
    MiniMaxVIDEO

    minimax-hailuo-2.3

    Tarif actuel : 38.8 credits /request
    Guide du modèleEssayer dans la consoleObtenir une clé d'API

    Articles associés

    tutorial2026-11-23T10:00:00+08:008 min de lecture

    OpenAI Sora 2 API Reference: Endpoints, Bearer Auth, and Character Creation

    Documented ToAPIs Sora 2 API reference (sora-2-vvip, sora-2, sora-2-pro, character creation, remix, Bearer auth) plus 2026-11-25 production availability warning and live video alternatives.

    TO
    ToAPIs Engineering & Evaluation Team
    #Sora 2
    tutorial2026-11-11T10:00:00+08:007 min de lecture

    Intégration de l'API MiniMax Hailuo 2.3 : générer des mouvements humains complexes en vidéo IA

    Guide développeur de l'API vidéo MiniMax Hailuo 2.3 sur ToAPIs : schémas de prompt pour le mouvement humain, contrat de requête actuel pour les tâches de 6 et 10 secondes en 768P et 1080P, et exemples cURL et Python.

    TO
    ToAPIs Engineering & Evaluation Team
    #MiniMax Hailuo
    tutorial2026-11-09T14:00:00+08:006 min de lecture

    Test de l'API Seedance 2.0 Mini : génération vidéo à haut débit avec un petit budget

    Guide développeur pour ByteDance Seedance 2.0 Mini (seedance-2-mini) sur ToAPIs : sortie 480p/720p, durée 4-15s, références multimodales, audio synchronisé et tarification par token en direct ($1.8881/1M de tokens).

    TO
    ToAPIs Engineering & Evaluation Team
    #Seedance 2.0 Mini
    ToAPIs
    AccueilToAPIs
    Passerelle d'API d'IA pour l'entreprise. Accédez à GPT-5, Claude, Gemini et plus de 200 modèles via une API unifiée.

    Modèles populaires

    • Seedance 2.5 API
    • Seedance 2.0 API
    • Veo 3.1 Fast API
    • Kling 3.0 Turbo API
    Afficher plusAfficher moins
    • GPT Image 2 API
    • Claude Opus 4.8 API
    • Nano Banana 2 API
    • Seedance 2 Mini API
    • Tous les modèles

    Catégories d'API

    • API image IA
    • API vidéo IA
    • API texte-vers-vidéo
    • API image-vers-vidéo
    Afficher plusAfficher moins
    • API d'édition d'image IA
    • API LLM et raisonnement
    • Tous les outils API →

    Alternatives

    Alternatives
    • Alternative à Kie.ai
    • Alternative à Fal.ai
    • Alternative à OpenRouter
    • Alternative à Replicate
    • Alternative à Wavespeed AI
    • Toutes les comparaisons →

    Guides à la une

    Guides à la une
    • Tarifs de Seedance 2.0 et 2.5
    • Guide de l'API Seedance la moins chère
    • Guide d'intégration de MiniMax H3
    • Clé d'API Seedance 2 gratuite
    • Démarrage rapide de l'API Seedance 2
    • Tous les articles techniques →

    Développeurs et plateforme

    Développeurs et plateforme
    • Documentation API
    • MCP
    • Tarifs
    • Playground de modèles
    • LLMs.txt
    • Contacter le support
    • Annuaire des guides de modèles
    Entité exploitante :
    鯨樞智能科技有限公司
    JINGSHU INTELLIGENT LIMITED
    Siège social :
    ROOM 5042, 5/F, YAU LEE CENTRE, NO.45, HOI YUEN ROAD, KWUN TONG, KOWLOON, HONG KONG
    ConfidentialitéConditionsUsage acceptableSuppression des donnéesConservation des donnéesSous-traitants et régionsFacturation et remboursementsPolitique relative aux cookiesPlan du siteÀ propos

    © 2026 ToAPIs. Tous droits réservés.