Task Completion Callback (Webhook)
Include a callback URL when submitting an async generation task, and we'll POST the result once it finishes, with an optional language for failure messages and a signing secret to verify callbacks.
← Вся документация/v1/videos/generationsWhen submitting async generation tasks such as video / image / audio, you can include a callback URL. Once the task finishes (succeeds or fails), we'll actively POST the result to your URL, so you don't have to keep polling. For video and image generation tasks, you can also use language to choose the language of failure messages.
Примеры запросов
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
class H(BaseHTTPRequestHandler):
def do_POST(self):
n = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(n)
data = json.loads(body)
print("Received task callback:", data["id"], data["status"])
# TODO: deduplicate by id, verify the signature, then process
self.send_response(200); self.end_headers()
self.wfile.write(b'{"ok":true}')
HTTPServer(("0.0.0.0", 443), H).serve_forever()Quick start
When submitting a task, add webhook at the top level of the request body. To translate failure messages, also add language:
curl -X POST https://your-access-domain/v1/images/generations \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-image-2",
"prompt": "a red apple on a table",
"size": "1024x1024",
"webhook": "https://your-server.com",
"language": "en"
}'After the task is done, we'll send a POST request to your URL + /callback.
Note
Other async task endpoints (video, audio, etc.) use
webhookin the same way.languagecurrently applies toPOST /v1/videos/generationsandPOST /v1/images/generations; both fields belong at the top level of the request body.
Tip
In production, we recommend configuring a signing secret for callbacks so you can confirm they really come from APISea. See Signature verification below.
Choose the error message language
language is an optional string parameter that only affects error.message in failure callbacks. Task IDs, status, progress, cost, and result URLs do not change with the language. If omitted, the original error message from the upstream provider or platform is returned.
| Language | Value | Language | Value |
|---|---|---|---|
| English | en | Russian | ru |
| Simplified Chinese | zh | French | fr |
| Japanese | ja | German | de |
| Korean | ko | Indonesian | id |
| Portuguese | pt | Spanish | es |
- Values are case-insensitive, and surrounding whitespace is trimmed. For example,
"EN"and" en "are both treated asen. - Use the two-letter codes in the table. Regional tags such as
zh-CN,en-US, andpt-BRare not recognized. - Unsupported values do not cause task submission to fail; the callback keeps the original error message.
- If the original message is already in the target language, it is returned unchanged instead of being translated again.
- If translation fails, the original message is returned without delaying or dropping the callback.
Note
When polling, use the
languagequery parameter on the task status endpoint to choose the same error message language. A webhook has no query string, solanguagemust be specified when submitting the task.
Warning
POST /mj/submit/*andPOST /v1/images/editsdo not supportwebhook/language. Official xAI image models do not supportlanguageand return400 parameter "language" is not supportedwhen it is included. Do not send this parameter to those models.
URL rules
The webhook you provide is the base URL, and we automatically append /callback:
Your webhook | Where we actually POST |
|---|---|
https://your-server.com | https://your-server.com/callback |
https://your-server.com/api | https://your-server.com/api/callback |
https://your-server.com/api/ | https://your-server.com/api/callback |
So your server needs an endpoint that accepts POST .../callback.
What you'll receive
The pushed payload is exactly the same as what the "Get Task Status" endpoint returns — you can process it with the same parsing logic.
{
"id": "task_01KV7FXR8BEYS1BWHJCT3JMCJ5",
"status": "completed",
"progress": 100,
"created": 1781589029,
"completed": 1781589058,
"actual_time": 29,
"cost": 0.006,
"credits_cost": 0.06,
"result": {
"images": [{ "url": ["https://.../result.png"], "expires_at": 1781675458 }]
}
}{
"id": "task_xxx",
"status": "failed",
"progress": 100,
"created": 1781589029,
"completed": 1781589050,
"error": {
"message": "The input image cannot be accessed. Make sure the URL is publicly accessible.",
"type": "task_failed",
"param": "",
"code": "task_failed"
}
}Note
For video tasks the result is in
result.videos, and for audio inresult.audios.
Note
The failure example above uses
"language": "en". The language parameter only changeserror.message; all other fields remain the same.
Warning
We only push when a task reaches a terminal state (
completed/failed); we don't push while processing.
Retries and deduplication (important)
- Retries: If your server doesn't return
2xxwithin about 10 seconds, or returns5xx, we'll retry automatically, up to 3 times, at intervals of roughly 10s, 30s, and 60s. If all 3 fail we give up (within about 2 minutes). - No retry: If your endpoint returns
4xx(treated as a bad URL / request), we give up immediately without retrying. - Deduplication: Normally a task is pushed only once. But in extreme cases (e.g. a restart on our side after sending but before confirmation) you may receive duplicate pushes. Be sure to deduplicate idempotently by
id(task_id) to avoid double-processing.
Recommendations for your receiving endpoint:
1. Return 2xx as soon as possible
Accept and enqueue first, then process asynchronously — don't make us wait for your processing to finish.
2. Deduplicate by id
Use id (task_id) as the idempotency key to avoid double-processing.
3. Configure and verify the signature
In production, configure a signing secret and verify X-Webhook-Signature to reject forged requests. See Signature verification below.
Signature verification
Once a signing secret is configured, every callback includes this request header:
X-Webhook-Signature: <hex(HMAC-SHA256(secret, raw request body bytes))>Your server recomputes the signature with the same secret and compares the two. Only a match proves the callback came from APISea and was not tampered with. If no secret is configured, callbacks are still sent, but without this header.
Configure a signing secret
There are two ways; use either one:
[tab] Console
Sign in to the console → API Keys page → Callback signing at the top right. Enter a secret or click Generate, copy it first, then save. It applies to all tasks under your account.
- The secret is write-only: after saving, the console shows only the last 4 characters and the plaintext can't be viewed again, so configure it on your server first.
- If you no longer need signing, you can clear the secret in the same dialog.
[tab] Per request
Add
webhook_secretat the top level of the request body. It applies to that task only:{ "model": "gpt-image-2", "prompt": "a red apple on a table", "webhook": "https://your-server.com", "webhook_secret": "your-shared-secret" }
- The key must be lowercase
webhook_secret. Case variants such asWebhook_Secretreturn400.- This secret is never sent to upstream model providers and does not appear in task details or usage logs.
If more than one secret exists, the first available one in this order is used:
| Priority | Source | Scope |
|---|---|---|
| 1 | webhook_secret in the task submission body | That task only |
| 2 | Secret configured under Callback signing in the console | All tasks under the account |
| 3 | Webhook secret in the legacy notification settings (kept for existing accounts) | All tasks under the account |
| — | None | Not signed; callbacks have no X-Webhook-Signature |
Secret requirements (same for both methods):
- 8–256 bytes, counted in UTF-8 (a CJK character takes 3 bytes). We recommend a 64-character hex string generated from 32 random bytes.
- Must not contain whitespace or control characters, such as spaces, line breaks, tabs, non-breaking spaces (U+00A0), or U+FEFF (BOM).
- The secret is used for signing exactly as-is; leading and trailing spaces are not trimmed.
- If the
webhook_secretpassed at submission doesn't meet these requirements, the endpoint returns400and no task is created.
How to verify
The signature is computed over the raw request body bytes. Always read the raw bytes before verifying; if your framework parses the JSON and re-serializes it, the result will not match. Use a constant-time comparison and compare bytes: if the signature header contains non-ASCII characters, comparing strings throws an exception.
import hashlib
import hmac
from fastapi import FastAPI, Request, Response
SECRET = b"your-shared-secret"
app = FastAPI()
@app.post("/callback")
async def callback(request: Request):
raw = await request.body() # must be the raw bytes
expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest().encode()
got = request.headers.get("X-Webhook-Signature", "").encode("utf-8")
if not hmac.compare_digest(expected, got): # compare bytes; don't use ==
return Response(status_code=401)
payload = await request.json()
# deduplicate by payload["id"], then process
return Response(status_code=200)const express = require("express");
const crypto = require("crypto");
const SECRET = "your-shared-secret";
const app = express();
// Key point: use express.raw to get the raw body, not express.json()
app.post("/callback", express.raw({ type: "application/json" }), (req, res) => {
const expected = crypto.createHmac("sha256", SECRET).update(req.body).digest("hex");
const got = Buffer.from(req.get("X-Webhook-Signature") || "", "utf8");
const want = Buffer.from(expected, "utf8");
// Compare byte length first: timingSafeEqual throws when lengths differ
if (got.length !== want.length || !crypto.timingSafeEqual(got, want)) {
return res.sendStatus(401);
}
const payload = JSON.parse(req.body.toString("utf8"));
// deduplicate by payload.id, then process
res.sendStatus(200);
});Rotating the secret
The secret used to sign a callback is fixed when the task finishes and the callback enters the delivery queue; all retries reuse it. So after you save a new secret in the console:
- Tasks that finish afterwards are signed with the new secret;
- Callbacks that were already retrying or waiting for delivery before you saved are still signed with the old secret, for up to about 20 minutes.
Warning
While rotating, have your server accept both the old and new secrets (either one passing is enough), and retire the old secret after about 20 minutes. Otherwise callbacks during this window will fail verification.
Requirements for the callback URL
For security, the callback URL must meet the following:
| Requirement | Description |
|---|---|
| Publicly accessible | Cannot be an internal / local address (e.g. 127.0.0.1, 10.x, 192.168.x will be rejected) |
| Protocol | http or https (https recommended) |
| Port | Use standard ports (80 / 443); non-standard ports may be blocked |
| Domain | Cannot point to our own service domain |
URLs that don't meet these requirements are dropped (no push, no retry).
FAQ
[accordion] I submitted a task with a webhook but didn't receive a push?
Check the following one by one:
- Did the task actually finish? Check the task details — is
statuscompleted/failed(no push while processing)?- Is your URL publicly accessible? Can we reach your
/callback?- Is the port a standard port (80 / 443)? Non-standard ports may be blocked by security policies.
- Did your
/callbackreturn 2xx promptly? Returning 4xx is given up immediately.- Are you using
https? Is the certificate valid?
[accordion] Why is url in the result an array?
Some models produce multiple images at once, so
images[].urlmay be an array — just handle it as an array.
[accordion] Do result links expire?
If
resultincludesexpires_at(a Unix timestamp), it indicates the link's expiration time — transfer/store it promptly.
[accordion] Do you push the 'processing' status?
No. We only push once, when the task finally succeeds or fails.
[accordion] Callbacks have no X-Webhook-Signature header?
That task had no signing secret available: no
webhook_secretwas passed at submission, nothing is configured under Callback signing in the console (or it was cleared), and the account has no secret in the legacy notification settings. Once you configure a secret in the console, tasks that finish afterwards will include the header.
[accordion] Signatures never match?
Check the following one by one:
- Are you computing over the raw request body bytes? Parsing the JSON and re-serializing it breaks the signature.
- Is the secret on your server exactly the same as the one saved in the console (including case, with no extra leading or trailing spaces)?
- If you passed
webhook_secretwhen submitting the task, that task uses the secret from the request instead of the console one.- Did you just rotate the secret? Callbacks within about 20 minutes may still be signed with the old secret. See Rotating the secret.
Minimal receiver example
Return 200 as soon as possible, and run your processing logic asynchronously in the background.
Нашли ошибку в документации? Напишите на support@apisea.ai.