Skip to navigation

Webhooks

View as Markdown

POST https://api.beatapi.io/v1/webhooks

Create a webhook endpoint for optional BeatAPI task completion callbacks.

Authorization

Authorization   string   required

Send your BeatAPI API key as a Bearer token. Create one on the Dashboard.

Authorization: Bearer <BEATAPI_API_KEY>

Keep permanent API keys on trusted servers. Content-Type: application/json is required for the request body. Idempotency-Key is optional when the endpoint exposes it and is recommended for safe retries with the exact same body.

Request body

url   string   required

Public HTTPS callback URL that accepts BeatAPI task events. Do not use localhost or a private-network URL.

Format: uri


description   string   optional

Optional internal label for identifying the endpoint in your account.


events   string[]   optional

Task events to deliver. Omit to subscribe to both task.succeeded and task.failed.

Response

A successful request returns HTTP 201.

{
"data": {
"id": "wh_9aBcD",
"object": "webhook_endpoint",
"url": "https://example.com/beatapi-webhook",
"description": "Production webhook",
"events": [
"task.succeeded",
"task.failed"
],
"status": "active",
"secret": "whsec_example_store_this_once",
"created_at": 1782210000,
"updated_at": 1782210000
}
}

Events

BeatAPI sends one event when a task reaches a final state. There are two event types, task.succeeded and task.failed. An endpoint receives both unless its events list names only one.

The event body has four fields: id (the event ID, evt_ followed by random characters), event, created_at (Unix seconds) and data. data is the task object, identical to the data that GET /v1/tasks/{task_id} returns for the finished task, so one parser handles both.

task.succeeded

{
"id": "evt_Qx8mTz2LpR4vN7sKa1WcY9bH",
"event": "task.succeeded",
"created_at": 1791993691,
"data": {
"id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
"object": "task",
"task_kind": "image",
"capability_id": "nano-banana-2",
"capability_version": 1,
"media_type": "image",
"model": "nano-banana-2",
"status": "succeeded",
"stage": "succeeded",
"created_at": 1791993600,
"updated_at": 1791993690,
"completed_at": 1791993690,
"output": {
"media": [
{
"type": "image",
"url": "https://media.beatapi.io/outputs/task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ/0.png",
"mime_type": "image/png"
}
],
"url": "https://media.beatapi.io/outputs/task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ/0.png",
"r2_url": "https://media.beatapi.io/outputs/task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ/0.png"
},
"usage": {
"credits_reserved": 0.02,
"credits_settled": 0.02,
"credits_refunded": 0,
"credits_charged": 0.02
},
"request_id": "202611260307541272151438268d9d6mNDNwzi9",
"error_code": null,
"error_message": null
}
}

task.failed

{
"id": "evt_Hn4cWz7QpT2vR8sKa1Lm3YbD",
"event": "task.failed",
"created_at": 1791993651,
"data": {
"id": "task_3Lp9Zd5NqW7xB2cMa8Vf4TgR6hJ1yKeU",
"object": "task",
"task_kind": "image",
"capability_id": "nano-banana-2",
"capability_version": 1,
"media_type": "image",
"model": "nano-banana-2",
"status": "failed",
"stage": "failed",
"created_at": 1791993600,
"updated_at": 1791993650,
"completed_at": 1791993650,
"output": null,
"usage": {
"credits_reserved": 0.02,
"credits_settled": 0,
"credits_refunded": 0.02,
"credits_charged": 0
},
"request_id": "202611260308049384136558268d9d6P01m6VVH",
"error_code": "content_policy_violation",
"error_message": "The request was blocked by content moderation. Please change the prompt or the input and try again.",
"retryable": false,
"error": {
"code": "content_policy_violation",
"message": "The request was blocked by content moderation. Please change the prompt or the input and try again.",
"retryable": false
}
}
}

Headers

HeaderValue
x-beatapi-eventtask.succeeded or task.failed.
x-beatapi-timestampUnix seconds when this attempt was sent. A retry carries a new timestamp.
x-beatapi-signatureHex HMAC-SHA256 signature; see below.
Content-Typeapplication/json
User-Agentbeatapi-webhook/1.0

Delivery, retries and duplicates

  • Endpoint requirements. The url must be public HTTPS. BeatAPI does not follow redirects, so a 3xx answer counts as a failed attempt.
  • Acknowledge fast. Answer with any 2xx within 10 seconds. A slower answer is a timeout and counts as a failed attempt. Queue the work and process it afterwards.
  • Retries. A delivery is attempted at most 3 times in total: right after the task finishes, again about 1 minute later, and a last time about 5 minutes after that. Timeouts, network errors, 3xx, 429 and 5xx answers are retried. Any other 4xx answer is not retried, so return a 2xx for an event you have already handled, and a 4xx only for a request you reject. After the third failure the event is dropped.
  • Duplicates are possible. The same event can arrive more than once, for example when your server processes it but answers too late. A retry carries the same event id and body. Deduplicate by event id (or by data.id and event) before you act on it.
  • Order is not guaranteed. Use data.status and data.completed_at rather than arrival order.
  • Disabled endpoints. An endpoint whose status is disabled receives nothing.
  • Failures BeatAPI ends itself. A task still unfinished after the processing window (at most 24 hours) is failed with error_code: processing_timeout and sends task.failed like any other failure. A task whose dispatch never completed, and a task whose channel could not be read, also fail and send task.failed. Read usage in the event for what was charged.

When no event is sent

Webhooks are a convenience; polling GET /v1/tasks/{task_id} is the source of truth. Keep a slow reconciliation poll for tasks that stay queued or processing for much longer than usual. No event is sent in these cases.

  • Data tasks. A data capability run as a task (web research) is polled; it sends no event.
  • Intermediate statuses. There is no event for queued, processing or the Music Video review states.
  • A result that cannot be resolved. If the finished task’s files cannot be listed when the event is built, the event is skipped; the poll still answers correctly.

One-off callback

A request to POST /v1/images/tasks or POST /v1/videos/tasks can carry an optional callback_url. When that task succeeds or fails, BeatAPI sends the event to this address as well as to your account endpoints. It is meant for a caller that wants the result of one task delivered to one place without a global subscription.

{
"model": "nano-banana-2",
"prompt": "A red kite over a green hill.",
"callback_url": "https://example.com/beatapi-webhook"
}
  • Register an endpoint first. BeatAPI has no separate signing key for callbacks. The callback_url must have the same scheme, host and port as one of your enabled webhook endpoints, and that endpoint’s secret signs the delivery, so verify it as described under Verify callback signatures. The path may differ from the endpoint’s.
  • Address rules. Public HTTPS only, at most 2048 characters. A private, loopback or link-local address is refused, and BeatAPI does not follow redirects.
  • Both outcomes. task.succeeded and task.failed are both sent, whatever events the signing endpoint subscribes to. The event body, headers, timeout and retry rules are the same as for an account endpoint.
  • Alongside your endpoints. An account endpoint subscribed to the event receives it too. When the callback_url is exactly that endpoint’s URL, the event is sent once.
  • When it stops. If the signing endpoint is deleted, disabled, or changed to another host, the callback is void: nothing is sent, and a retry still pending is dropped.
  • Not accepted elsewhere. Workflows, Effects and Capabilities Run do not take callback_url.

A callback_url that cannot be used is 400 bad_request and no task is created. The message names the field:

MessageCause
"callback_url" must be a string.The value is not a string.
"callback_url" must be at most 2048 characters.The address is too long.
"callback_url" must be a valid https URL.It is not a URL, or it has no host or no http or https scheme.
"callback_url" must be a public HTTPS URL.It uses http, or it points to a private, loopback, link-local or otherwise non-public address.
"callback_url" must be on the host of one of your active webhook endpoints, whose secret signs it; register one with POST /v1/webhooks.No enabled endpoint has the same scheme, host and port.

Verify callback signatures

BeatAPI sends x-beatapi-event, x-beatapi-timestamp, and x-beatapi-signature with every delivery. Compute the expected hex HMAC-SHA256 value over:

timestamp + "." + raw_request_body

Use the endpoint secret returned by the create request (the whole string, including whsec_). It is shown once, so store it when you create the endpoint. Compare signatures in constant time, verify the exact raw bytes before JSON parsing, and reject timestamps older than 5 minutes to limit replay attacks.

Node.js (Express)

import crypto from "node:crypto";
import express from "express";
const app = express();
const SECRET = process.env.BEATAPI_WEBHOOK_SECRET; // whsec_... from the create response
const seen = new Set(); // use a database or Redis with an expiry in production
// express.raw keeps the exact bytes; do not use express.json() on this route.
app.post("/beatapi-webhook", express.raw({ type: "application/json" }), (req, res) => {
const timestamp = req.get("x-beatapi-timestamp") ?? "";
const signature = req.get("x-beatapi-signature") ?? "";
const expected = crypto
.createHmac("sha256", SECRET)
.update(`${timestamp}.`)
.update(req.body)
.digest("hex");
const given = Buffer.from(signature, "hex");
const wanted = Buffer.from(expected, "hex");
const fresh = Math.abs(Date.now() / 1000 - Number(timestamp)) <= 300;
if (!fresh || given.length !== wanted.length || !crypto.timingSafeEqual(given, wanted)) {
return res.status(400).end(); // a 4xx is not retried
}
const event = JSON.parse(req.body.toString("utf8"));
if (!seen.has(event.id)) {
seen.add(event.id);
if (event.event === "task.succeeded") {
// event.data.output.media[].url: download and store it now
} else {
// event.data.error_code, event.data.retryable
}
}
res.status(200).end(); // acknowledge quickly
});
app.listen(3000);

Python (Flask)

import hashlib
import hmac
import os
import time
from flask import Flask, abort, request
app = Flask(__name__)
SECRET = os.environ["BEATAPI_WEBHOOK_SECRET"].encode() # whsec_... from the create response
seen = set() # use a database or Redis with an expiry in production
@app.post("/beatapi-webhook")
def beatapi_webhook():
body = request.get_data() # the raw bytes, before any JSON parsing
timestamp = request.headers.get("x-beatapi-timestamp", "")
signature = request.headers.get("x-beatapi-signature", "")
expected = hmac.new(SECRET, timestamp.encode() + b"." + body, hashlib.sha256).hexdigest()
fresh = timestamp.isdigit() and abs(time.time() - int(timestamp)) <= 300
if not fresh or not hmac.compare_digest(signature, expected):
abort(400) # a 4xx is not retried
event = request.get_json(force=True)
if event["id"] not in seen:
seen.add(event["id"])
task = event["data"]
if event["event"] == "task.succeeded":
pass # task["output"]["media"][i]["url"]: download and store it now
else:
pass # task["error_code"], task["retryable"]
return "", 200 # acknowledge quickly

Manage endpoints

  • GET /v1/webhooks lists webhook endpoints.
  • GET /v1/webhooks/{id} gets a webhook endpoint.
  • PATCH /v1/webhooks/{id} updates a webhook endpoint. It accepts url, description, events and status (active or disabled).
  • DELETE /v1/webhooks/{id} deletes a webhook endpoint.

Next step

Verify every callback signature before parsing its payload. Polling GET /v1/tasks/{task_id} remains the source of truth if delivery is delayed or fails.

Errors

StatusMeaning
400Malformed JSON or a field, value or combination this endpoint does not accept (bad_request; the message names the field), or input refused by moderation (content_policy_violation). Not retryable unchanged.
401No API key (missing_api_key), or a key that is wrong, expired, disabled or exhausted (invalid_api_key; the message says which). Send it as Authorization: Bearer <key>; the key works with or without the sk- prefix. Not retryable.
429Too many requests (rate_limit_exceeded, including the free-model limits). Retryable after Retry-After seconds (also error.retry_after_seconds).
500Unexpected internal error (internal_error). Retryable; keep request_id for support if it persists.