Media generation runs as a background job, which means your app shouldn’t sit and wait on one open request for an image, video, or song. A webhook callback lets Apiframe notify your server when a job changes status or the media is ready, instead of your code checking over and over. This guide walks through building that flow with a unified API, including event design, endpoint security, payload checks, retries, and production monitoring.
Step 1: Define the Webhook Workflow and Event Contract
Start by writing down what happens after your app submits a media job. This gives your webhook handler a clear plan to follow before you write any code.
With Apiframe, your server sends a generation request and gets back a jobId and a status. From there, you can either poll the job, meaning your code checks it on a timer, or wait for a callback. Apiframe documents three webhook events:
completed: the media is ready, and the result is included.failed: the job failed, and an error message is included.progress: the job’s progress percentage changed.
Write the flow in plain terms:
- Your app accepts a prompt or media request.
- Your backend submits the job.
- The API returns a job ID.
- Apiframe sends a callback when the event you chose happens.
- Your worker checks the event and updates your own job record.
- Your app shows the result or a useful error.
Keep Apiframe’s job ID stored next to your own internal request ID. The two IDs solve different problems: your ID ties the job to a user or order, while Apiframe’s ID lets you look up the current state of the generation.
Choose your events carefully. A progress event can help a long video job show movement, but it adds more traffic to handle, and Apiframe sends progress events on a best-effort basis with a single attempt, so don’t depend on them. A completed and failed pair is usually enough for a first release. The Apiframe webhook documentation lists the event fields and verification steps to map into your handler.
Also decide what your app should do if a callback never arrives. Apiframe retries completed and failed events up to 10 times, starting after 5 seconds and waiting longer after each try. A delivery only counts as successful when your endpoint answers with a 2xx response, so a slow or erroring handler will burn through those attempts. If every retry fails, the delivery is marked as failed. Keep polling as a safety net for jobs that stay unfinished longer than expected, because recovering from a missed callback is still your system’s job.
Key takeaway: Treat the webhook as one event inside your job’s status flow, not as a replacement for your own job database.
Step 2: Create the Generation Request and Callback URL
To set up webhook callbacks for media generation, start by exposing a stable HTTPS endpoint on your server. Then pass that endpoint’s URL in your generation request.
Use a route like POST /hooks/apiframe. It should accept a JSON body and return a success response quickly. Apiframe’s own guidance is to answer within a few seconds, so don’t make the callback request wait while you download a large video file or run a long moderation check in the same request.
Your generation request needs the model, the prompt, and the callback settings, webhookUrl and webhookEvents:
curl -X POST https://api.apiframe.ai/v2/images/generate \
-H "X-API-Key: afk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"model": "your_allowed_model_id",
"prompt": "a red bicycle on a wet street",
"webhookUrl": "https://yourapp.example/hooks/apiframe",
"webhookEvents": ["completed", "failed"]
}'The URL must start with https:// or http://, can’t be longer than 2,048 characters, and can’t point to a private or internal address such as localhost, 10.x.x.x, or 192.168.x.x. Use HTTPS in production.
For images, Apiframe uses POST /v2/images/generate. Videos use POST /v2/videos/generate, and music uses POST /v2/music/generate. The same basic job pattern applies across all three media types, which saves you from maintaining separate provider integrations. If video is your main use case, our AI video generation API guide shows the full flow, and our AI music API guide does the same for audio.
The response arrives before the media is ready. Store the returned jobId next to your internal request record. Store the model name too, since it helps you check cost and compare speed later.
Keep the callback URL and any API key on your server, not in browser code. This matters more than usual here, because your webhook signing secret is derived from your API key, so exposing the key also breaks your ability to trust callbacks. If users can choose a model, send that choice to your backend and let the backend map it to an allowed model ID. Our guide to integrating a unified media API with React shows this pattern in a front-end app.
A single Apiframe integration can cover image, video, and music jobs. You can use one callback route if your handler reads the media type from the payload, or separate routes if different teams own each workflow and you want simpler access rules. Pick one pattern and write it down before adding more models.
Test with one small image job first, then add video and music once your receiver handles the shared fields correctly. If you’re new to the platform, our Getting Started with Apiframe guide covers the first request. If you’re replacing existing providers, our guide on migrating to one media API covers how to move callbacks across without downtime.
Step 3: Secure and Authenticate the Webhook Endpoint
A webhook endpoint is a public web address, so security needs to be part of the first version, not an afterthought. Authentication confirms that a callback really came from the expected sender and wasn’t changed along the way.
Apiframe signs every webhook with two headers: X-Webhook-Signature and X-Webhook-Event. To check a signature:
- Create your signing secret by taking the SHA-256 hash of your API key, as a hex string.
- Compute an HMAC-SHA256 value of the raw request body using that secret. HMAC is a way of using a secret key and a hash function together to confirm a message hasn’t been changed.
- Compare the result with the
X-Webhook-Signatureheader. The header value starts withsha256=, so include that prefix in the value you build. - Use a constant-time comparison, which always takes the same amount of time no matter where the two values differ. That way an attacker can’t guess the signature by measuring how fast you respond.
Read the body as raw bytes before your JSON parser has a chance to change spacing or reorder keys. This is worth being careful about, because the sample code in many webhook docs, Apiframe’s included, rebuilds the body from parsed JSON. That works until a payload comes through with different spacing, and then signatures start failing for no obvious reason. Capture the raw body in your framework and verify against that.
Your handler should follow this order:
- Accept the HTTPS request.
- Read the raw body.
- Read the signature header.
- Compute the expected signature.
- Compare both values in constant time.
- Parse the JSON only after the signature passes.
- Queue the event for later work.
Never log the API key, the signing secret, or the full payload if it contains sensitive data. Instead, log a short request ID, the job ID, the event name, and whether the check passed. Those fields let you trace a problem without putting secrets in your logs.
Use an allowlist for expected event names, reject unexpected HTTP methods, and add a request size limit. If you add your own extra check, such as a secret token in the URL, treat it as a second layer, never as a reason to skip signature checks.
Security setups vary across providers. Some use no authentication at all, while others rely on an API key or a signature. For your own service, the rule is simple: reject unsigned or invalid callbacks before they reach your business logic. Our AI media API security and authentication guide covers the same ideas in more depth, including key management and access control, and our compliance and data privacy overview covers what auditors tend to ask about event data.
Tip: Save the exact raw request body during a test run so you can replay it later if you update your signature-checking code.
Step 4: Validate Payloads, Track Jobs, and Handle Media Results
Payload validation keeps a bad or broken callback from corrupting your job table. A good handler checks the event before it touches any data your users can see.
After the signature check, parse the JSON body. Confirm the payload includes a job ID and a status you recognize. Webhook payloads share a common shape, though not every field appears on every event. A completed event carries result but no error, while a failed event carries error and no result. Here is what to check for each field:
| Field | Check | Action |
|---|---|---|
| event | Match an allowed event name | Route to the correct handler |
| jobId | Match a stored job | Update that job only |
| status | Use a known state | Move the state machine forward |
| result | Present on completed events only | Queue download or storage work |
| error | Present on failed events only | Mark the job failed and alert if needed |
| model and creditCost | Record both for reporting | Track spend per model and per project |
One detail that catches people out: the shape of result depends on the media type. Images return an images array, video returns a single videoUrl, and music returns a tracks array with per-track details. If you plan to use one callback route for all three, write the handler to branch on media type rather than assuming an array of images.
Return a success response as soon as you’ve safely queued the event, not after finishing all your processing. The callback handler shouldn’t try to download a large video file inside the same request. Let a background worker fetch the file from the CDN, which is the fast file host Apiframe delivers results from, run any checks your product needs, and move the file into storage you control. Our AI content moderation guide covers which of those checks you can automate.
Apiframe hosts generated media and task history for 90 days on every plan. That’s useful for short-lived workflows, but it isn’t a permanent archive, so copy files to your own storage whenever a customer saves them or your retention policy requires it.
Keep the original result URL in your job record, and add your own storage key once the download succeeds. This gives your support team a clear trail if a file fails to copy or a user reports a missing file.
Don’t mark a job complete just because the callback arrived. Mark it complete only after the payload passes your checks and your file handoff succeeds. If the download happens later, use a middle status such as MEDIA_READY before moving to STORED.
Step 5: Add Idempotency, Retries, and Failure Handling
Webhook delivery can repeat, arrive late, or fail while your server happens to be down. Apiframe’s docs note that in rare cases a webhook may be delivered more than once and suggest using the jobId to avoid repeats. Your handler needs to make repeated events safe.
Start with an idempotency record, which is a safeguard that makes sure the same event is only acted on once, even if it arrives more than once. Use the job ID plus the event name as a unique key. When a callback arrives, try to save that key. If it already exists, return success without repeating the work.
This protects you from duplicate work, like sending two customer notifications or copying the same file twice. It also makes it safe to replay events if you ever need to recover from a worker failure.
Separate receiving an event from processing it. Your HTTP route should verify the request, save the event, and place a message on a queue. A background worker can then retry downloads, moderation checks, or database updates without making Apiframe’s callback wait for a response.
Use a retry schedule for the parts you control. For example, retry a temporary storage error after a short delay, then wait longer after each failed attempt. Stop after a set number of tries and move the event to a separate holding queue for failed messages, often called a dead-letter queue, so someone can review it. Don’t retry a bad signature or an invalid payload, since those errors won’t fix themselves.
Apiframe retries delivery on its side, but if all attempts fail, nobody will resend the event for you. Each job carries a webhookStatus field that reflects the delivery outcome, covering states such as pending, delivered, and failed. Build a recovery task that finds jobs stuck in a non-final state or with a failed webhook status, calls GET /v2/jobs/:id to check the current status, and repairs your local record if needed. Apiframe suggests polling every 2 to 3 seconds for images and every 5 to 10 seconds for video and music, which is a sensible pace for a recovery sweep too.
Record the last callback time and the last processing error for each job. If the same job keeps failing, alert on that pattern instead of sending a separate alert for every attempt. A small operations table makes this easy to track, with fields like:
- Job ID and internal request ID
- Current local status
- Last event received
- Attempt count
- Next retry time
- Final error, if any
A failed generation is refunded automatically under Apiframe’s billing rules, and a failed job reports a credit cost of zero, but your app still needs to show users a clear status. Don’t tell someone their file is ready until your own checks have passed.
Step 6: Test, Deploy, and Monitor the Production Integration
Testing webhook callbacks means testing bad timing and edge cases, not just the path where everything works. Use a development endpoint and send a known generation request before connecting real customer traffic. Apiframe can’t send callbacks to localhost or private addresses, so use a public test URL, such as a tunnel to your local machine. Our guide to testing AI-generated video quality is a useful companion if you’re also checking the media itself, not just the delivery pipeline.
Test these cases one at a time:
- A valid completed event
- A valid failed event
- An invalid signature
- A broken JSON body
- An unknown job ID
- The same event sent twice
- A callback that arrives after the job is already complete
- A temporary database or storage failure
For each case, check both sides of the exchange. The sender needs a clear HTTP response, and your system needs a lasting record that explains what happened.
Deploy the receiver behind HTTPS with a stable route. Set a short timeout for the callback itself, and keep any longer work in a queue or background worker. If you run several app instances, make sure the idempotency store is shared across all of them.
Watch the numbers that reflect real customer impact: callback receipt rate, signature failures, processing time, stuck jobs, duplicate events, and failed media downloads. Add a dashboard for jobs that stay unfinished past your normal limit. For a deeper look at measuring and improving these numbers, see our unified media API latency and performance guide.
Keep polling available during your first production release. If callbacks fail because of a wrong route or an expired secret, the poller gives you a way to recover jobs while you fix the receiver. Remove that fallback only once you trust the delivery path and have a clear recovery plan.
When your integration spans several models, track the model ID with each job. Apiframe supports 70+ models behind one API, so you can change the model value without rewriting your callback handler. That makes it easier to compare quality, cost, or completion time while your event format stays the same. Our model switching speed comparison explains how to test that fairly. If you’re weighing model costs, our guide to estimating AI video costs can help you budget across models.
Set alerts for symptoms, not noise. A rise in invalid signatures usually points to a secret mismatch, which often means someone rotated the API key without updating the receiver. A rise in valid but unprocessed events points to a queue or worker problem. A rise in failed downloads points to storage, expiry, or network issues.
Key takeaway: A production-ready webhook is one that can reject bad input, handle duplicates, recover missed events, and explain failures clearly in its logs.
FAQ
What is a webhook callback for media generation?
A webhook callback is an HTTP POST request that tells your app when a background media job changes status. Instead of repeatedly checking for status, your server receives an event once an image, video, or song is ready. You still need a job record and a fallback check, since delivery can occasionally fail. Our explainer on what a unified AI media API is covers how this fits the wider job pattern.
How do I secure a media generation webhook?
Use HTTPS and signature checks. Read the raw request body, calculate the expected HMAC signature, and compare it with the signature header using a constant-time comparison. Reject invalid requests before parsing or processing them, keep secrets out of your source code, and avoid logging the raw key or the full payload.
Should I poll or use a webhook for AI media jobs?
Use a webhook as your main path and polling as a recovery path. Polling is easy to add, but repeated checks waste requests and can delay how quickly you handle results. A callback lets your system react as soon as the job reaches an event you chose, while a recovery task can poll any jobs that stay unresolved.
What should a webhook payload contain?
A useful payload includes an event name, the job ID, a status, and either result data or an error. Apiframe also sends the model name and the credit cost, which are worth storing for reporting. Your handler should record the time it received the event and link the provider’s ID to your internal request. Check every field before changing anything your users can see, and for completed media, confirm the result links look the way you expect.
How do I prevent duplicate webhook processing?
Use an idempotency key stored in a unique database field. The job ID combined with the event name works well. Save the key before any work runs. If the key already exists, return a success response and skip the work.
Conclusion
Build the callback as a small, verified intake route backed by a lasting job record and a queue. Apiframe gives you one consistent job pattern across image, video, and music generation, with automatic retries for completed and failed events and polling available whenever you need a recovery path. Start with a single completed event, test duplicate delivery, then use our pricing calculator comparison to plan costs before moving your first workflow into production. If you’re new to the platform, the Getting Started guide walks you through your very first API call.