# Receive signed webhooks

> Register an HTTPS endpoint with POST /v1/webhooks to be told when a batch job finishes or a monitored page changes, send it a test ping, read its deliveries, rotate its secret, and verify each signature in Node or Python.

Source: https://docs.spicrawl.com/guides/webhooks

Use a webhook when you would rather be told a batch job has finished than poll for it. Spicrawl sends a signed `POST` to your URL when the event happens. The notification carries the job or monitor summary, not the results: fetch those yourself. Requires an API key with the `webhooks` scope. GET routes also accept `read`.

> **Note:** A webhook is notify-only. Deliveries are retried on a fixed ladder, and an endpoint that keeps failing is switched off. Your receiver must answer quickly with a `2xx`; do the real work after you have answered.

 

## Register an endpoint

```bash title="curl"
curl -X POST https://api.spicrawl.com/v1/webhooks \
  -H "Authorization: Bearer $SPICRAWL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://hooks.example.com/spicrawl",
    "name": "nightly-catalog",
    "events": ["batch.completed", "batch.failed"],
    "format": "json"
  }'
```

```python title="Python"
import os
from spicrawl import Spicrawl

with Spicrawl() as client:  # reads SPICRAWL_API_KEY
    endpoint = client.webhooks.create(
        "https://hooks.example.com/spicrawl",
        name="nightly-catalog",
        events=["batch.completed", "batch.failed"],
    )
    print(endpoint["secret"])  # shown once: store it now
```

The response is `201` with the endpoint and its `secret`. The secret is returned only here and from [rotate-secret](#rotate-the-secret). Keep it in your secret store, not in source.

Then pass the endpoint's `id` when you submit a batch:

```json
{
  "urls": ["https://example.com/products/1", "https://example.com/products/2"],
  "webhook_endpoint_id": "0190f3a2-7c1e-7d4b-9a2f-3b8e5c6d7e80"
}
```

| Field    | Rule                                                                                                 |
| -------- | ---------------------------------------------------------------------------------------------------- |
| `url`    | Required. `https://` only, at most 2,048 characters. Private and internal addresses are refused.     |
| `name`   | Optional. At most 100 characters.                                                                    |
| `events` | Optional. A non-empty subset of the events below. Defaults to `["batch.completed", "batch.failed"]`. |
| `format` | Optional. `json` (default), `slack` or `discord`.                                                    |

An organization may hold 20 endpoints. A twenty-first is refused with a `409`; delete one first.

## Events

| Event             | Fires when                                                                                                                                     | Payload `data`                                                                                                                  |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `batch.completed` | A batch job finishes with every item settled.                                                                                                  | The job object, as `GET /v1/batch/{id}` returns it.                                                                             |
| `batch.failed`    | A batch job ends as `failed`, for example when `failure_threshold` is reached.                                                                 | The job object. Read `error_code`.                                                                                              |
| `monitor.changed` | A change is confirmed on a [monitored](https://docs.spicrawl.com/guides/monitors.md) page, or a site monitor's run finds a change (a [site digest](#site-digest-payload)). | `monitor_id`, `name`, `url`, `detected_at`, `previous_hash`, `new_hash`, `diff` (its first 4,000 characters) and `changes_url`. |
| `monitor.failed`  | A monitor is disabled after repeated failed checks.                                                                                            | `monitor_id`, `name`, `url`, `reason` (the last check error) and `failed_at`.                                                   |

`ping` is always delivered to every endpoint and is not listed in `events`. Subscribe only to the events your receiver handles, and ignore any other `type` you get.

Every event is a JSON document with this envelope:

```json
{
  "id": "01a1e8e1-c1d5-75fd-99eb-1573c72ced46",
  "type": "batch.completed",
  "created": 1763370000,
  "data": { "id": "01J9Z6T3W9E21T5TZARVJRVN5C", "status": "completed", "total_items": 2 }
}
```

`id` is the delivery id. It is the same on every retry of one event, so use it to drop duplicates. `created` is the Unix time the event was made, not the time of this attempt.

## Slack and Discord formats

Set `format` to `slack` or `discord` to post to an incoming-webhook URL instead of your own service. The body is a single line:

| `format`  | Body               | Example text                                                     |
| --------- | ------------------ | ---------------------------------------------------------------- |
| `slack`   | `{"text": "…"}`    | `Spicrawl batch 01J9Z6T3W9E21T5TZARVJRVN5C completed: 2/2 items` |
| `discord` | `{"content": "…"}` | the same line, at most 2,000 characters                          |

Use the incoming-webhook URL that Slack or Discord gives you as `url`. Signature headers are sent in these formats too. The `ping` line reads `Spicrawl webhook test`.

## Test ping

```bash title="curl"
curl -X POST https://api.spicrawl.com/v1/webhooks/$ENDPOINT_ID/test \
  -H "Authorization: Bearer $SPICRAWL_API_KEY"
```

```python title="Python"
ping = client.webhooks.test(endpoint["id"])
print(ping["delivery_id"])
```

The response is `202` with the `delivery_id` of a `ping` delivery. Its body is:

```json
{"id":"…","type":"ping","created":1764064800,"data":{"event":"ping","endpoint_id":"0190f3a2-7c1e-7d4b-9a2f-3b8e5c6d7e80","created_at":"2026-11-25T10:00:00Z"}}
```

A ping is signed and retried like any other delivery. Check that it arrived in the deliveries list below before you rely on the endpoint.

## Deliveries

```bash title="curl"
curl "https://api.spicrawl.com/v1/webhooks/$ENDPOINT_ID/deliveries?limit=20" \
  -H "Authorization: Bearer $SPICRAWL_API_KEY"
```

```python title="Python"
for d in client.webhooks.deliveries(endpoint["id"], limit=20):
    print(d["event_type"], d["status"], d["attempt"], d["last_error"])
```

The list is newest first and holds one row per event and endpoint, not one per attempt. Each row gives:

| Field                          | Meaning                                                                                                                                       |
| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`, `event_id`, `event_type` | The delivery, the object it is about, and the event.                                                                                          |
| `status`                       | `pending` (waiting for its first attempt or a retry), `delivering` (in flight), `delivered`, `failed` (will be retried) or `dead` (given up). |
| `attempt`, `max_attempts`      | Tries so far, and the most that will be made.                                                                                                 |
| `next_retry_at`                | When the next attempt is due, while it is `failed`.                                                                                           |
| `last_error`                   | Why the last attempt failed.                                                                                                                  |
| `created_at`                   | When the event was queued.                                                                                                                    |

## Retries and auto-disable

A delivery succeeds on any `2xx` response. Anything else, including a timeout, is retried on this ladder after the first attempt:

| Retry | Wait before it |
| ----- | -------------- |
| 1     | 30 seconds     |
| 2     | 1 minute       |
| 3     | 5 minutes      |
| 4     | 30 minutes     |
| 5     | 1 hour         |
| 6     | 1 day          |

Each wait has about ±10% jitter. That is seven attempts in all. When the ladder runs out, the delivery is `dead`.

An endpoint that fails 100 deliveries in a row is disabled: `enabled` becomes `false` and `disabled_reason` says why. A success resets the count. Fix the receiver, then turn the endpoint back on:

```bash title="curl"
curl -X PATCH https://api.spicrawl.com/v1/webhooks/$ENDPOINT_ID \
  -H "Authorization: Bearer $SPICRAWL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"enabled": true}'
```

Re-enabling also clears `disabled_reason` and resets `consecutive_failures` to 0.

## Rotate the secret

```bash title="curl"
curl -X POST https://api.spicrawl.com/v1/webhooks/$ENDPOINT_ID/rotate-secret \
  -H "Authorization: Bearer $SPICRAWL_API_KEY"
```

```python title="Python"
new = client.webhooks.rotate_secret(endpoint["id"])
store(new["secret"])  # shown once
```

Rotating returns a new `secret` and bumps `secret_version`. From then on, deliveries are signed with the new secret and carry `kid` equal to the new `secret_version`. Deliveries are not signed with the old secret any more, so change your receiver's secret in the same step you rotate it.

## Verify signatures

Every delivery carries a signature in `X-Spicrawl-Signature`. `X-ILayer-Signature` has the same value and is kept for receivers that already read it. Check the signature before you trust the body.

The header looks like this:

```
X-Spicrawl-Signature: t=1763370000,v1=9c1e5b…,kid=1
```

* `t` is the Unix time, in seconds, at which the delivery was signed.
* `v1` is HMAC-SHA256 as lowercase hex.
* `kid` is the endpoint's `secret_version`.

The signed string is the decimal `t`, a `.`, and the raw request body, byte for byte:

```
signed string = "<t>." + raw_body
v1            = hex(HMAC-SHA256(key = secret, message = signed string))
```

The key is the whole secret, `whsec_…`, as UTF-8 bytes. Then:

1. Read the body as raw bytes. Do not parse it and serialise it again; the JSON spacing and key order will differ and the check will fail.
2. Parse `t` and `v1` from the header.
3. Refuse the delivery if `t` is more than **300 seconds** from your clock. This stops a captured delivery being replayed later.
4. Compute the HMAC and compare it with `v1` in constant time.

```js title="Node"
import crypto from "node:crypto";

const TOLERANCE_SECONDS = 300;

// rawBody: the request body exactly as received (a Buffer or string).
// header: the X-Spicrawl-Signature value (X-ILayer-Signature works too).
export function verifySpicrawlSignature(rawBody, header, secret, now = Math.floor(Date.now() / 1000)) {
  const fields = Object.fromEntries(
    String(header ?? "")
      .split(",")
      .map((part) => part.trim().split("=", 2))
      .filter(([k, v]) => k && v !== undefined)
  );
  const t = Number(fields.t);
  const v1 = fields.v1;
  if (!Number.isInteger(t) || !v1) return false;
  if (Math.abs(now - t) > TOLERANCE_SECONDS) return false;

  const body = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody, "utf8");
  const expected = crypto
    .createHmac("sha256", secret)
    .update(`${t}.`)
    .update(body)
    .digest("hex");

  const a = Buffer.from(expected, "utf8");
  const b = Buffer.from(v1, "utf8");
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

// Express: keep the body raw for this route, then verify before JSON.parse.
// app.post("/spicrawl", express.raw({ type: "application/json" }), (req, res) => {
//   const ok = verifySpicrawlSignature(req.body, req.get("X-Spicrawl-Signature"), process.env.SPICRAWL_WEBHOOK_SECRET);
//   if (!ok) return res.status(401).end();
//   const event = JSON.parse(req.body);
//   res.status(200).end();
// });
```

```python title="Python"
import hashlib
import hmac
import time

TOLERANCE_SECONDS = 300


def verify_spicrawl_signature(
    raw_body: bytes, header: str, secret: str, now: int | None = None
) -> bool:
    """raw_body: the request body exactly as received. header: X-Spicrawl-Signature."""
    fields = {}
    for part in header.split(","):
        key, sep, value = part.strip().partition("=")
        if sep:
            fields[key.strip()] = value.strip()

    try:
        t = int(fields["t"])
    except (KeyError, ValueError):
        return False
    v1 = fields.get("v1", "")
    if not v1:
        return False

    now = int(time.time()) if now is None else now
    if abs(now - t) > TOLERANCE_SECONDS:
        return False

    signed = f"{t}.".encode() + raw_body
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, v1)


# Flask: request.get_data() returns the raw bytes; parse them only after verifying.
# ok = verify_spicrawl_signature(request.get_data(), request.headers["X-Spicrawl-Signature"], SECRET)
```

Two checks catch most mistakes: a signature that fails for every delivery usually means the body was re-serialised before it was checked, and a signature that fails only after a while usually means the receiver's clock has drifted by more than five minutes.

### Monitor payloads

A `monitor.changed` event carries the change, not the page. Fetch the full diff from `changes_url` if the first 4,000 characters are not enough:

```json
{
  "id": "01a1e8e1-c1d5-75fd-99eb-1573c72ced47",
  "type": "monitor.changed",
  "created": 1763370000,
  "data": {
    "monitor_id": "0190f5c4-2b7a-7e10-8d3f-6a1c9e4b2d70",
    "name": "pricing-page",
    "url": "https://example.com/pricing",
    "detected_at": "2026-11-25T10:00:00Z",
    "previous_hash": "3f1a…",
    "new_hash": "9c2e…",
    "diff": "- Pro: 49\n+ Pro: 59\n",
    "changes_url": "/v1/monitors/0190f5c4-2b7a-7e10-8d3f-6a1c9e4b2d70/changes"
  }
}
```

A `monitor.failed` event has `monitor_id`, `name`, `url`, `reason` and `failed_at` in `data`. It means the monitor has stopped checking; re-enable it with `PATCH /v1/monitors/{id}` once the page is back. See [Monitors](https://docs.spicrawl.com/guides/monitors.md).

### Site digest payload

A [whole-site monitor](https://docs.spicrawl.com/guides/monitors.md#watch-a-whole-site) sends one `monitor.changed` per run that found a change or an addition or removal, not one per page. `data` has `scope: "site"` and the run's totals, and lists the pages that changed, were added or were removed:

```json
{
  "id": "01a1e8e2-d2e6-76fe-8a00-2684d83dee58",
  "type": "monitor.changed",
  "created": 1763370000,
  "data": {
    "monitor_id": "0190f9a0-3c4d-7e21-8f5a-2b7d1e9c4f03",
    "name": "example-blog",
    "url": "https://example.com/",
    "scope": "site",
    "detected_at": "2026-11-25T10:00:00Z",
    "counts": {"checked": 12, "skipped": 180, "changed": 1, "added": 2, "removed": 0, "credits": 14},
    "truncated": false,
    "changed": [{"url": "https://example.com/blog/rates", "diff": "- Rate: 4%\n+ Rate: 5%\n"}],
    "added": ["https://example.com/blog/new-post", "https://example.com/blog/another-post"],
    "removed": [],
    "changes_url": "/v1/monitors/0190f9a0-3c4d-7e21-8f5a-2b7d1e9c4f03/changes"
  }
}
```

* `counts` has the run's totals: pages `checked`, `skipped` (not fetched, sitemap `lastmod` unchanged), `changed`, `added`, `removed`, and the `credits` it spent.
* `truncated` is `true` when `max_credits_per_run` stopped the run early.
* `changed` lists at most 50 pages, each with a diff of at most 2,000 characters. `added` and `removed` list at most 100 URLs each. The lists can be shorter than `counts`.
* `changes_url` returns each run's digest in the change history.

The signature is verified exactly as for any other delivery, on the raw body.

## Related

* [Watch a page for changes](https://docs.spicrawl.com/guides/monitors.md): the monitors that fire `monitor.changed` and `monitor.failed`
* [Scrape thousands of URLs with a batch job](https://docs.spicrawl.com/guides/batch.md): the job that fires `batch.completed`
* [Batch webhook\_endpoint\_id](https://docs.spicrawl.com/guides/batch.md#limits-and-options): attach an endpoint to one job
