Dashboard

Cookbook Recipe

Webhooks

Receive and verify webhooks

A webhook receiver that accepts only deliveries signed with your secret, processes each delivery once, and replies within moments.

POSThttps://api.devupai.com/v1/inference/{model}

What you'll build

You send an inference request with a webhook URL, the API replies at once with queued, and the result arrives later as a signed POST to your endpoint. The receiver in this recipe checks the X-DevUp-Signature header against the raw body, skips deliveries it has already seen, replies 200 right away, and then handles the result.

Before you start

  • A DEVUP AI account and an API key (sk-devup-...) in DEVUP_API_KEY to send the request. See Authentication.
  • Your signing secret: open Webhooks in the dashboard. Reveal shows the full whsec_... string. Store it in DEVUP_WEBHOOK_SECRET on the server that runs the receiver.
  • A real https:// URL on a server you control and that is reachable from the internet, pointing at the receiver (port 8000 in the example).
  • Python 3.10 or later, or Node.js 22.12 or later for the devupai SDK.
pip install fastapi uvicorn httpx
Terminal
export DEVUP_API_KEY=sk-devup-your-api-key
export DEVUP_WEBHOOK_SECRET=whsec_your-signing-secret

The complete program

One file per language. Save it as receiver.py or receiver.mjs, set DEVUP_WEBHOOK_SECRET, and run it. The receiver listens on POST /devup-webhook. The Node.js program uses the official devupai SDK: constructWebhookEvent checks the signature and the timestamp, then parses the body.

"""Receive DEVUP AI webhooks: verify each delivery, skip duplicates, reply fast.

Install: pip install fastapi uvicorn httpx
Run:     DEVUP_WEBHOOK_SECRET=whsec_... python receiver.py
"""

import hashlib
import hmac
import json
import logging
import os
import time
from collections.abc import Callable

from fastapi import BackgroundTasks, FastAPI, Request
from fastapi.responses import JSONResponse

logger = logging.getLogger("devup_webhooks")
app = FastAPI()

# Example only: production keeps delivery ids in a durable store with a unique key.
seen_delivery_ids: set[str] = set()


def verify_signature(
    raw_body: bytes,
    header: str,
    secret: str,
    tolerance: int = 300,
    now: float | None = None,
) -> bool:
    """Return True when any v1 signature in the X-DevUp-Signature header matches raw_body."""
    if not header or not secret:
        return False
    timestamp = None
    signatures = []
    for part in header.split(","):
        key, separator, value = part.partition("=")
        key, value = key.strip(), value.strip()
        if not separator:
            return False
        if key == "t":
            # Digits only, at most 12 of them: a Unix time in seconds.
            if timestamp is not None or len(value) > 12 or not (value.isascii() and value.isdigit()):
                return False
            timestamp = value
        elif key == "v1":
            signatures.append(value)
    if timestamp is None or not signatures:
        return False

    current = time.time() if now is None else now
    if abs(current - int(timestamp)) > tolerance:
        return False

    # Signed string: "<t>." followed by the exact body bytes. Key: the full whsec_ secret.
    signed_payload = f"{timestamp}.".encode("utf-8") + raw_body
    expected = hmac.new(secret.encode("utf-8"), signed_payload, hashlib.sha256).hexdigest()
    # One v1 per active secret: accept when any of them matches.
    return any(
        hmac.compare_digest(expected.encode("ascii"), signature.encode("utf-8"))
        for signature in signatures
    )


def process_delivery(event: dict) -> None:
    """Handle one verified delivery. Branch on status only."""
    if event.get("status") == "succeeded":
        results = event.get("results")
        for result in results if isinstance(results, list) else [results]:
            # Text models return {"generated_text": ...}; other models return their own fields.
            logger.info("Delivery %s result: %s", event["id"], result)
    elif event.get("status") == "failed":
        logger.error("Delivery %s: %s", event["id"], (event.get("error") or {}).get("message"))


def handle_webhook(
    raw_body: bytes,
    signature_header: str,
    delivery_id: str,
    secret: str,
    seen: set[str],
    schedule: Callable[..., object],
    now: float | None = None,
) -> tuple[int, dict]:
    """Decide the HTTP reply for one delivery and schedule its processing."""
    if not secret:
        # A 5xx gets the delivery retried, so nothing is lost while the secret is missing.
        return 503, {"error": "secret_not_configured"}
    if not verify_signature(raw_body, signature_header, secret, now=now):
        # A 4xx other than 408 or 429: retries stop for that delivery.
        return 400, {"error": "invalid_signature"}
    try:
        event = json.loads(raw_body)
    except ValueError:
        return 400, {"error": "invalid_json"}
    # The body id equals X-DevUp-Delivery-Id and, unlike the header, is covered by the signature.
    if not delivery_id or not isinstance(event, dict) or event.get("id") != delivery_id:
        return 400, {"error": "delivery_id_mismatch"}
    if delivery_id in seen:
        return 200, {"received": True, "duplicate": True}
    seen.add(delivery_id)
    schedule(process_delivery, event)
    return 200, {"received": True}


@app.post("/devup-webhook")
async def devup_webhook(request: Request, background_tasks: BackgroundTasks) -> JSONResponse:
    # Read the raw bytes before any JSON parsing: the signature covers these exact bytes.
    raw_body = await request.body()
    delivery_id = request.headers.get("x-devup-delivery-id", "")
    status_code, payload = handle_webhook(
        raw_body,
        request.headers.get("x-devup-signature", ""),
        delivery_id,
        os.environ.get("DEVUP_WEBHOOK_SECRET", ""),
        seen_delivery_ids,
        background_tasks.add_task,
    )
    if status_code >= 400:
        logger.warning("Rejected delivery %r: %s", delivery_id, payload["error"])
    return JSONResponse(payload, status_code=status_code)


if __name__ == "__main__":
    import uvicorn

    logging.basicConfig(level=logging.INFO)
    if not os.environ.get("DEVUP_WEBHOOK_SECRET"):
        logger.warning("DEVUP_WEBHOOK_SECRET is not set: deliveries get 503 until it is.")
    uvicorn.run(app, host="0.0.0.0", port=8000)

Without the SDK

The same receiver with the signature check written out with node:crypto. It is kept because it shows every step of the algorithm, so you can port it to a language that has no SDK. It needs Node.js 18 or later and npm install express, and it returns the responses listed under Errors this recipe handles.

JavaScript
// Receive DEVUP AI webhooks: verify each delivery, skip duplicates, reply fast.
// Install: npm install express
// Run:     DEVUP_WEBHOOK_SECRET=whsec_... node receiver.mjs
import { createHmac, timingSafeEqual } from "node:crypto";
import { pathToFileURL } from "node:url";
import express from "express";

const PORT = 8000;

// Example only: production keeps delivery ids in a durable store with a unique key.
const seenDeliveryIds = new Set();

/** Returns true when any v1 signature in the X-DevUp-Signature header matches rawBody (Buffer or string). */
export function verifySignature(rawBody, header, secret, { toleranceSec = 300, now = Math.floor(Date.now() / 1000) } = {}) {
  if (typeof header !== "string" || !header || !secret) return false;
  let timestamp = null;
  const signatures = [];
  for (const part of header.split(",")) {
    const separator = part.indexOf("=");
    if (separator === -1) return false;
    const key = part.slice(0, separator).trim();
    const value = part.slice(separator + 1).trim();
    if (key === "t") {
      // Digits only, at most 12 of them: a Unix time in seconds.
      if (timestamp !== null || !/^\d{1,12}$/.test(value)) return false;
      timestamp = value;
    } else if (key === "v1") {
      signatures.push(value);
    }
  }
  if (timestamp === null || signatures.length === 0) return false;

  if (Math.abs(now - Number(timestamp)) > toleranceSec) return false;

  // Signed string: "<t>." followed by the exact body bytes. Key: the full whsec_ secret.
  const body = typeof rawBody === "string" ? Buffer.from(rawBody, "utf8") : rawBody;
  const expected = Buffer.from(
    createHmac("sha256", secret).update(`${timestamp}.`).update(body).digest("hex"),
    "utf8",
  );
  // One v1 per active secret: accept when any of them matches.
  return signatures.some((signature) => {
    const received = Buffer.from(signature, "utf8");
    return received.length === expected.length && timingSafeEqual(received, expected);
  });
}

/** Handles one verified delivery. Branch on status only. */
export function processDelivery(event, log = console) {
  if (event.status === "succeeded") {
    const results = Array.isArray(event.results) ? event.results : [event.results];
    for (const result of results) {
      // Text models return { generated_text }; other models return their own fields.
      log.info(`Delivery ${event.id} result:`, result);
    }
  } else if (event.status === "failed") {
    log.error(`Delivery ${event.id}: ${event.error?.message}`);
  }
}

/** Decides the HTTP reply for one delivery and schedules its processing. */
export function handleWebhook({ rawBody, signatureHeader, deliveryId, secret, seen, schedule, now, log = console }) {
  if (!secret) {
    // A 5xx gets the delivery retried, so nothing is lost while the secret is missing.
    return { status: 503, body: { error: "secret_not_configured" } };
  }
  if (!verifySignature(rawBody, signatureHeader, secret, { now })) {
    // A 4xx other than 408 or 429: retries stop for that delivery.
    return { status: 400, body: { error: "invalid_signature" } };
  }
  let event;
  try {
    event = JSON.parse(Buffer.isBuffer(rawBody) ? rawBody.toString("utf8") : rawBody);
  } catch {
    return { status: 400, body: { error: "invalid_json" } };
  }
  // The body id equals X-DevUp-Delivery-Id and, unlike the header, is covered by the signature.
  if (!deliveryId || event?.id !== deliveryId) {
    return { status: 400, body: { error: "delivery_id_mismatch" } };
  }
  if (seen.has(deliveryId)) {
    return { status: 200, body: { received: true, duplicate: true } };
  }
  seen.add(deliveryId);
  schedule(() => processDelivery(event, log));
  return { status: 200, body: { received: true } };
}

export function createApp({ secret, seen = seenDeliveryIds, log = console }) {
  const app = express();
  // express.raw keeps the exact bytes the signature covers. Raise the limit to fit your largest results.
  app.post("/devup-webhook", express.raw({ type: "application/json", limit: "10mb" }), (req, res) => {
    const deliveryId = req.get("x-devup-delivery-id") ?? "";
    const { status, body } = handleWebhook({
      rawBody: Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0),
      signatureHeader: req.get("x-devup-signature") ?? "",
      deliveryId,
      secret,
      seen,
      log,
      // Reply first, process afterwards.
      schedule: (task) =>
        setImmediate(() => {
          try {
            task();
          } catch (err) {
            log.error(`Could not process delivery ${deliveryId}:`, err);
          }
        }),
    });
    if (status >= 400) log.warn(`Rejected delivery ${JSON.stringify(deliveryId)}: ${body.error}`);
    res.status(status).json(body);
  });
  return app;
}

function main() {
  const secret = process.env.DEVUP_WEBHOOK_SECRET ?? "";
  if (!secret) console.warn("DEVUP_WEBHOOK_SECRET is not set: deliveries get 503 until it is.");
  createApp({ secret }).listen(PORT, () => {
    console.log(`Listening on http://localhost:${PORT}/devup-webhook`);
  });
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  main();
}

How it works

1Send a request with a webhook URL

Add a string webhook field to a POST /v1/inference/{model} request. This is the same request as on the Webhooks reference page, sent to your receiver's URL. The Node.js tab sends it with client.inference.run from the devupai SDK.

import os
import sys

import httpx

api_key = os.environ.get("DEVUP_API_KEY")
if not api_key:
    print("Set DEVUP_API_KEY.", file=sys.stderr)
    sys.exit(1)

response = httpx.post(
    "https://api.devupai.com/v1/inference/deepseek-ai/DeepSeek-V4-Pro",
    headers={"Authorization": f"Bearer {api_key}"},
    json={
        "input": "Explain quantum computing in three sentences.",
        "parameters": {"max_new_tokens": 200, "temperature": 0.7},
        "webhook": "https://your-app.example.com/devup-webhook",
    },
    timeout=60,
)
response.raise_for_status()
print(response.json())

A submitted request is not sent again automatically, so one request gives one delivery. The snippet sets the client timeout to 60 seconds and prints the id of the queued request. When no reply arrives within that time, the request may still have been queued, so check your receiver's deliveries before you send it again.

The API replies with HTTP 200 right away. Other output fields may also be present.

Output shape

JSON
{
  "id": "inf-<uuid>",
  "model": "<model ID>",
  "inference_status": { "status": "queued" },
  "_devup": {
    "reserved_dzd": <reserved_dzd>,
    "status": "pending_settlement",
    "request_id": "req_<id>"
  }
}

reserved_dzd is a number in DZD reserved for the request; the final amount arrives as cost_dzd in the delivery.

2Read the raw body first

Each delivery is a JSON POST with these headers:

http
POST /devup-webhook HTTP/1.1
Content-Type: application/json
User-Agent: DevUp-Webhook/1.0
X-DevUp-Delivery-Id: whd_<uuid>
X-DevUp-Signature: t=<unix seconds>,v1=<hex>

The signature covers the exact bytes of the body. Parsing JSON and serialising it again changes those bytes, so the receiver reads the raw body before anything else and parses it only after the signature verifies. constructWebhookEvent takes those bytes as a Buffer or a string.

If a delivery is larger than the body limit you set, Express answers 413 and retries stop for that delivery, so size the limit for your largest results.

# Read the raw bytes before any JSON parsing: the signature covers these exact bytes.
raw_body = await request.body()

3Check the timestamp

t is a Unix time in seconds, set fresh for each attempt. The receiver rejects the header when it is malformed, when t is not an integer, or when t is more than 300 seconds from its own clock, as on Webhooks. A recorded delivery cannot be replayed after that window, and inside it the delivery id check in Step 5 catches the repeat.

In the Node.js program, constructWebhookEvent runs this check and the signature check in one call, with a window of 300 seconds unless you pass toleranceSeconds.

current = time.time() if now is None else now
if abs(current - int(timestamp)) > tolerance:
    return False

Without the SDK

JavaScript
if (Math.abs(now - Number(timestamp)) > toleranceSec) return false;

4Check every v1 in constant time

The signed string is <t>.<raw body>, signed with HMAC-SHA256 and written as lowercase hex. The key is the whole secret as UTF-8 text, whsec_ prefix included, with no decoding.

The header carries one v1 per active signing secret, so it has two or more while secrets rotate. The receiver accepts the delivery when any of them matches. hmac.compare_digest and crypto.timingSafeEqual do not stop at the first differing byte, so the time a comparison takes reveals nothing about the expected signature. timingSafeEqual needs equal lengths, hence the length check first.

When a check does not pass, constructWebhookEvent throws a DevupWebhookVerificationError. Its reason is malformed_header, timestamp_outside_tolerance, no_matching_signature or, for a verified body that is not JSON, invalid_json. The receiver answers invalid_json for the last one and invalid_signature for the others.

# Signed string: "<t>." followed by the exact body bytes. Key: the full whsec_ secret.
signed_payload = f"{timestamp}.".encode("utf-8") + raw_body
expected = hmac.new(secret.encode("utf-8"), signed_payload, hashlib.sha256).hexdigest()
# One v1 per active secret: accept when any of them matches.
return any(
    hmac.compare_digest(expected.encode("ascii"), signature.encode("utf-8"))
    for signature in signatures
)

Without the SDK

JavaScript
// Signed string: "<t>." followed by the exact body bytes. Key: the full whsec_ secret.
const body = typeof rawBody === "string" ? Buffer.from(rawBody, "utf8") : rawBody;
const expected = Buffer.from(
  createHmac("sha256", secret).update(`${timestamp}.`).update(body).digest("hex"),
  "utf8",
);
// One v1 per active secret: accept when any of them matches.
return signatures.some((signature) => {
  const received = Buffer.from(signature, "utf8");
  return received.length === expected.length && timingSafeEqual(received, expected);
});

5Skip duplicates and reply at once

A delivery can arrive more than once. X-DevUp-Delivery-Id is the same on every retry of a delivery, while the signature and t change, so the delivery id is the key for deduplication. It also equals the id in the signed body, and the receiver checks the two match before trusting the header.

A duplicate gets 200 as well, so it is not sent again. A new delivery is recorded, its processing is scheduled after the reply (BackgroundTasks in FastAPI, setImmediate in Node.js), and the receiver answers 200 straight away. Respond within a few seconds; the delivery timeout is on the Webhooks reference page.

# The body id equals X-DevUp-Delivery-Id and, unlike the header, is covered by the signature.
if not delivery_id or not isinstance(event, dict) or event.get("id") != delivery_id:
    return 400, {"error": "delivery_id_mismatch"}
if delivery_id in seen:
    return 200, {"received": True, "duplicate": True}
seen.add(delivery_id)
schedule(process_delivery, event)
return 200, {"received": True}

The Node.js route handler is async. Express 4 does not catch a rejected promise, so the handler catches any other error itself and answers 500, and the delivery is retried.

6Process the result by status

Branch on status only. "succeeded" carries results; "failed" carries error with a type and a message. A delivery has one or the other. results can be a list or a single object, so the code checks before it loops.

def process_delivery(event: dict) -> None:
    """Handle one verified delivery. Branch on status only."""
    if event.get("status") == "succeeded":
        results = event.get("results")
        for result in results if isinstance(results, list) else [results]:
            # Text models return {"generated_text": ...}; other models return their own fields.
            logger.info("Delivery %s result: %s", event["id"], result)
    elif event.get("status") == "failed":
        logger.error("Delivery %s: %s", event["id"], (event.get("error") or {}).get("message"))

Output shape: a delivery with results

JSON
{
  "id": "whd_<uuid>",
  "status": "succeeded",
  "usage": { "prompt_tokens": <prompt_tokens>, "completion_tokens": <completion_tokens> },
  "cost_dzd": <cost_dzd>,
  "settlement": "settled",
  "results": [
    { "generated_text": "<text>" }
  ]
}

Output shape: a delivery without results

JSON
{
  "id": "whd_<uuid>",
  "status": "failed",
  "usage": { "prompt_tokens": 0, "completion_tokens": 0 },
  "cost_dzd": null,
  "settlement": "failed",
  "error": {
    "type": "inference_failed",
    "message": "The inference request did not complete successfully."
  }
}

cost_dzd is a number in DZD, or null when settlement is "failed". settlement is the string "settled" or "failed", and usage holds prompt_tokens and completion_tokens. status and settlement are separate fields: a "succeeded" delivery can carry either settlement value.

In production

  • Durable deduplication: replace the in-memory set with a store that has a unique key on the delivery id, so every server instance and every restart sees the same ids. Insert the id and the processing job in one transaction, and treat a unique-key conflict as a duplicate.
  • Background jobs: run the processing in a job runner outside the web process, with its own retries. The reply only confirms receipt.
  • Secrets and rotation: keep the signing secret in a secret store, not in code. While you roll out a new secret, accept a delivery that verifies with either the old or the new one: the header carries a v1 for each active secret.
  • No accidental 400s: deploy a new signing secret to the receiver before the old one stops being used, and keep the server clock synchronised, because a delivery answered with 400 is not sent again. Log X-DevUp-Delivery-Id with every rejection and every processed result.
  • The request side: for a full retry policy on the request in Step 1, see Production error handling.

Errors this recipe handles

These are the responses your receiver returns, and what each one means for the delivery. Return a 5xx for a temporary problem on your side so the delivery is retried. A 4xx other than 408 or 429 stops retries for that delivery.

StatusBodyWhenEffect
200{"received": true}The signature verifies and the delivery id is new. Processing starts after the reply.Delivered. No retry.
200{"received": true, "duplicate": true}The same delivery id arrived before. Nothing is processed a second time.Delivered. No retry.
400{"error": "invalid_signature"}The X-DevUp-Signature header is missing or malformed, t is more than 300 seconds from your clock, or no v1 matches your secret.Retries stop for that delivery.
400{"error": "invalid_json"}The signed body is not JSON.Retries stop for that delivery.
400{"error": "delivery_id_mismatch"}X-DevUp-Delivery-Id is missing or differs from the id in the signed body.Retries stop for that delivery.
503{"error": "secret_not_configured"}DEVUP_WEBHOOK_SECRET is missing or empty. Set it and restart the receiver.The delivery is retried.
5xxanyAny other temporary problem on your side, such as a store that is not reachable.The delivery is retried.

The request in Step 1 can return an API error. The Node.js snippet prints its HTTP status, code and request id, and exits with status 1.

Retries and timing

Retry timing and the delivery timeout are on the Webhooks reference page.

Next steps