Claude API Webhook Callback Implementation Guide
Anthropic's Claude API does not have a native webhook system — there's no "callback_url" field you can pass to /v1/messages that fires an event when generation finishes. The Messages API is request/response: you send a prompt, you get a reply (or a stream). If you searched for "Claude API webhook callback implementation," what you actually need is a pattern for turning that synchronous API into an asynchronous, callback-driven workflow in your own backend.
This is a common requirement when Claude calls take a long time (large context, extended tool-use chains, batch jobs) and you don't want your client holding an open HTTP connection or polling in a loop. The fix is to build a thin job queue in front of the Claude call and deliver results via your own signed webhook callback. Below is the architecture and working code for that.
Why There's No Native Webhook
Claude's API is stateless and synchronous by design, even when streaming. The closest thing to "async" Anthropic offers is the Batch API, which accepts a set of requests and makes you poll a batch status endpoint until results are ready — still pull-based, not push-based. If you want push notifications (a webhook POST to your own server when a job completes), you have to implement that layer yourself, sitting between your clients and the Claude API.
The Callback Architecture Pattern
The pattern has four parts:
- Intake endpoint — accepts the prompt plus a
callback_url, validates it, enqueues a job, returns202 Acceptedwith a job ID immediately. - Worker — pulls the job, calls Claude (streaming or not), assembles the final result.
- Delivery — POSTs a signed JSON payload to the
callback_urlwith retries and backoff. - Idempotency — the job ID and a signature let the receiving system safely dedupe retried deliveries.
Step 1: Accept the Request and Return Immediately
app.post("/jobs", async (req, res) => {
const { prompt, callback_url } = req.body;
if (!callback_url || !/^https:\/\//.test(callback_url)) {
return res.status(400).json({ error: "valid https callback_url required" });
}
const jobId = crypto.randomUUID();
await queue.add("claude-job", { jobId, prompt, callback_url });
res.status(202).json({ job_id: jobId, status: "queued" });
});
Never call Claude inside the request handler that your client is waiting on if the call might take more than a few seconds — that's what leads to timeouts and retried duplicate requests from the client side.
Step 2: Process the Claude API Call Asynchronously
The worker does the actual Claude call. Whether you call Anthropic directly or through a proxy like SubToAPI, the logic is identical — only the base URL and bearer token change:
async function runJob({ jobId, prompt, callback_url }) {
const resp = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.SUBTOAPI_KEY}`
},
body: JSON.stringify({
model: "claude-sonnet-4",
max_tokens: 1024,
messages: [{ role: "user", content: prompt }]
})
});
const data = await resp.json();
await deliverCallback(callback_url, { jobId, status: "completed", result: data });
}
If your job involves tool use, keep looping inside this worker until the model returns a final stop_reason of end_turn rather than tool_use — only deliver the webhook once the full tool-resolution chain is done. See /docs/tools for the request/response shape of tool-use turns.
Step 3: Deliver the Webhook Callback
Sign every payload. Without a signature, anyone who guesses your callback URL can spoof job completions.
function sign(body, secret) {
return crypto.createHmac("sha256", secret).update(body).digest("hex");
}
async function deliverCallback(url, payload) {
const body = JSON.stringify(payload);
const signature = sign(body, process.env.WEBHOOK_SECRET);
for (let attempt = 0; attempt < 5; attempt++) {
try {
const res = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Webhook-Signature": signature
},
body,
signal: AbortSignal.timeout(10000)
});
if (res.ok) return;
} catch (_) { /* fall through to retry */ }
await new Promise(r => setTimeout(r, 2 ** attempt * 1000));
}
await deadLetterQueue.add({ url, payload });
}
On the receiving side, the client verifies the signature with the same shared secret before trusting the payload, and checks jobId against previously processed IDs to ignore duplicate deliveries caused by retries.
Handling Long Tool-Use Chains with Callbacks
If your Claude integration runs multi-step tool calls (search, code execution, database lookups), don't deliver a callback after every intermediate step — that creates noisy, hard-to-consume webhooks. Instead, accumulate the full conversation in the worker and fire a single callback once the model's response reaches a terminal state. If you need partial progress visibility, add an optional progress_url that receives lightweight status pings ("step": "tool_call", "name": "search") separate from the final callback_url.
Batch API + Webhook Combo
If you're running large volumes through Anthropic's Batch API, the same worker pattern applies, just at the polling layer instead of the request layer: a scheduled job checks batch status every N minutes, and when a batch moves to ended, it fans out one webhook callback per completed request in that batch, rather than making every client poll Anthropic directly.
Security Checklist
- Only accept
https://callback URLs, reject internal/private IP ranges to avoid SSRF. - Sign every payload with HMAC and a per-customer secret.
- Set a short connect/read timeout on the callback POST (5–10s) so a slow receiver doesn't block your queue.
- Retry with exponential backoff, cap at 5 attempts, then dead-letter.
- Include a monotonic
job_idandtimestampso receivers can reject stale or replayed deliveries.
If you're already routing Claude traffic through SubToAPI's sub_live_ keys for team usage tracking, this webhook layer sits cleanly on top — the intake/worker/delivery pattern above doesn't change, you just swap the target URL. /docs/quickstart covers the request format, and /docs/streaming is useful if your worker needs to consume a streamed response before firing the final callback.
FAQ
Does Claude's API support webhooks directly? No. Anthropic's Messages and Batch APIs are pull-based (request/response or poll-for-status). Any webhook/callback behavior has to be implemented in your own service layer that wraps the Claude API calls.
Should I deliver a webhook for every streaming token? No — streaming is for live client connections. Webhooks should fire once per completed job (or once per logical milestone), not per token, otherwise you'll overwhelm receivers and hit rate limits on their endpoint.
How do I prevent duplicate webhook deliveries from causing problems? Include a unique job_id in every payload and have receivers track which IDs they've already processed. Combine that with HMAC signature verification so retried deliveries are both idempotent and trusted.