AI Video API Webhooks: Polling, Signatures and Idempotency
How asynchronous AI video APIs work, when to poll and when to use webhooks, how to verify a Magi2-Signature header in Node and Python, and how idempotency keys make retries safe.

An AI video API does not return a video in the response to your request. It returns a job id right away, renders in the background, and tells you when the job is done, either because you poll for its status or because it calls a webhook on your server. To build on one safely you need three pieces: a way to learn the result (polling, webhooks, or both), a way to trust a webhook (signature verification), and a way to retry without paying twice (idempotency keys). This guide shows all three with the Magi2 AI API.
Why video generation is asynchronous
A short clip from a modern video model takes anywhere from tens of seconds to several minutes to render, depending on the model, resolution and length. No HTTP connection should stay open that long; proxies, load balancers and serverless runtimes will cut it. So the API splits the work:
POST /api/v1/videoschecks your request, charges the credits and returns a video object with anidand astatusofpending.- The video moves through
processingto eithersuccessorfailed. - You read the final state with
GET /api/v1/videos/{id}, or receive it in a webhook.
If a video fails, its credits are refunded automatically, so a failure costs you nothing but time.
Polling: simple and always available
Polling means calling GET /api/v1/videos/{id} every few seconds until the status is final. It needs no public endpoint, works from a laptop or a cron job, and cannot miss a result. The trade-off is wasted requests and a small delay between the video finishing and you noticing.
Good polling habits:
- Wait a few seconds before the first check, then poll every five to ten seconds.
- Stop on
successorfailed; readoutputsfor the file URLs orerrorfor the reason. - Set an overall timeout in your own code and alert if it is reached.
Webhooks: push instead of pull
Add a webhook_url to the create request and we will POST to it once when the video finishes. The body looks like this:
{
"type": "video.succeeded",
"data": { "id": "…", "status": "success", "model": "seedance-2-fast", "outputs": ["https://…"] }
}
type is either video.succeeded or video.failed, and data is exactly the JSON that GET /api/v1/videos/{id} returns. The URL must be public https.
Delivery is a single attempt with a 10-second timeout and no retries. That is deliberate: webhooks are a fast path, and polling is the reliable path. The recommended pattern is to use both: react to the webhook when it arrives, and run a slower poll for any job still unfinished after a few minutes. Your handler should also be idempotent, because a poll and a webhook can both report the same video.
Verifying the Magi2-Signature header
Anyone can POST to a public URL, so check that a webhook really came from us before acting on it. Every webhook carries a header like:
Magi2-Signature: t=1764028800,v1=5f2b…
t is the Unix time the request was signed, and v1 is the hex HMAC-SHA256 of the string t + "." + raw body, keyed with your account's webhook secret. The secret starts with whsec_ and is shown on /settings/apikeys.
Three rules matter:
- Use the raw request body exactly as received. Parsing the JSON and serialising it again changes the bytes.
- Compare signatures in constant time.
- Reject old timestamps (five minutes is a sensible tolerance) to limit replays.
Node.js
import crypto from 'node:crypto';
export function verifyMagi2Signature(rawBody, header, secret, toleranceSec = 300) {
const match = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(header ?? '');
if (!match) return false;
const [, t, received] = match;
if (Math.abs(Date.now() / 1000 - Number(t)) > toleranceSec) return false;
const expected = crypto
.createHmac('sha256', secret)
.update(`${t}.${rawBody}`)
.digest('hex');
return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(received));
}
In Express, get the raw body with express.raw({ type: 'application/json' }) and pass req.body.toString('utf8').
Python
import hashlib
import hmac
import re
import time
def verify_magi2_signature(raw_body: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
match = re.fullmatch(r"t=(\d+),v1=([0-9a-f]{64})", header or "")
if not match:
return False
t, received = match.groups()
if abs(time.time() - int(t)) > tolerance:
return False
expected = hmac.new(
secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected, received)
In Flask, use request.get_data(); in FastAPI, await request.body().
Reply with a 2xx as soon as the signature checks out, then do the slow work (downloading the video, updating your database) in the background. A slow handler risks hitting the timeout.
Idempotency keys: retries without double charges
Networks fail in the worst place: after the server has accepted your request but before you see the response. If you simply retry, you may start two videos and pay for both. Send an Idempotency-Key header with every create request, and a retry with the same key returns the original video instead of starting a new one.
Use a key that identifies the intent, not the attempt: an order id plus a clip name works well. Generate it once, store it with your job, and reuse it on every retry.
Putting it together
curl https://magi2ai.dev/api/v1/videos \
-H "Authorization: Bearer $MAGI2_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order-4821-hero-clip" \
-d '{
"model": "seedance-2-fast",
"prompt": "Steam rising from a cup of coffee on a wooden table, morning light, slow push in",
"resolution": "480p",
"seconds": 5,
"webhook_url": "https://example.com/hooks/magi2"
}'
Store the returned id, mark the job pending, verify and handle the webhook, and keep a background poll as the safety net. The same flow works for every model, including MAGI-2 when it becomes available, since only the model value changes. MAGI and MAGI-2 are trademarks of their owner; this site is independent and not affiliated with or endorsed by Sand AI.
The full field list is in the API docs, payload details are on the webhooks page, and credit costs per model are on /pricing.
Try the API
Create a key, send one request and get a video back. The price is shown before anything runs.