> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.rasen.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.rasen.ai/_mcp/server.

# Receive call events with webhooks

> Register an HTTPS endpoint for call events, verify each signed request, test it, resend deliveries, rotate the secret, and disable or delete the endpoint.

## Summary

This guide registers a webhook endpoint for call events and verifies the signature of each request
to it. It also tests the endpoint, resends deliveries, rotates the secret, and replaces, disables or
deletes the endpoint. It does not list the event payloads; see
[Webhook events](/reference/webhook-events).

## Facts

| Item                     | Value                                                                                                                                                                                                                                                                                                                                                                                   |
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Operations               | `createWebhookEndpoint`, `listWebhookEndpoints`, `getWebhookEndpoint`, `replaceWebhookEndpoint`, `deleteWebhookEndpoint`, `rotateWebhookSigningSecret`, `sendWebhookTestEvent`, `listWebhookDeliveries`, `resendWebhookDelivery`                                                                                                                                                        |
| Paths                    | `POST /webhook-endpoints`, `GET /webhook-endpoints`, `GET /webhook-endpoints/{endpoint_id}`, `PUT /webhook-endpoints/{endpoint_id}`, `DELETE /webhook-endpoints/{endpoint_id}`, `POST /webhook-endpoints/{endpoint_id}/rotate-secret`, `POST /webhook-endpoints/{endpoint_id}/test`, `GET /webhook-endpoints/{endpoint_id}/deliveries`, `POST /webhook-deliveries/{delivery_id}/resend` |
| Capability               | `webhooks.manage` on every operation                                                                                                                                                                                                                                                                                                                                                    |
| Required headers         | `Authorization` on every request; `Idempotency-Key` on create, replace, delete, rotate, test and resend; `If-Match` on replace, delete and rotate                                                                                                                                                                                                                                       |
| `ETag`                   | The endpoint `revision`. It changes with `url`, `description`, `events`, `state` and the signing secret, not with delivery results                                                                                                                                                                                                                                                      |
| Endpoints                | At most 10 endpoints that are not deleted, for each workspace                                                                                                                                                                                                                                                                                                                           |
| Endpoint `url`           | Absolute `https` URL with a host, 9 to 2,048 characters; no user information and no fragment. The host must resolve only to public addresses. Redirects are never followed                                                                                                                                                                                                              |
| Event types              | `call.completed`, `call.failed`, `call.analyzed`: 1 to 3 in `events`, no value twice. `webhook.test` comes only from `sendWebhookTestEvent`                                                                                                                                                                                                                                             |
| New endpoint             | Receives only events created after its own `created_at`                                                                                                                                                                                                                                                                                                                                 |
| Delivery                 | At least once, with the same `webhook-id` on every attempt, retry and resend of one event. No ordering guarantee                                                                                                                                                                                                                                                                        |
| Attempts                 | 8 attempts in one chain (`max_attempts`). A resend starts a new chain of 8 attempts                                                                                                                                                                                                                                                                                                     |
| Success                  | Any `2xx` answer. A `3xx` answer fails the attempt. Rasen reads at most 16 KiB of the status line and headers, and never reads the response body                                                                                                                                                                                                                                        |
| Automatic disable        | `state: disabled_failing` after at least 72 hours and at least 10 failed call-event attempts with no success. Test attempts do not count                                                                                                                                                                                                                                                |
| Delivery history         | 30 days: `listWebhookDeliveries` and `resendWebhookDelivery`                                                                                                                                                                                                                                                                                                                            |
| Signing secret           | `whsec_` and the base64 of 32 random bytes. Only the first successful answer of create and rotate returns it; a replay returns `null`. `secret_hint` holds its last 4 characters                                                                                                                                                                                                        |
| Rotation grace           | The previous secret stays valid for 24 hours (`previous_secret_expires_at`); each attempt then carries two signatures                                                                                                                                                                                                                                                                   |
| Signed content           | `{webhook-id}.{webhook-timestamp}.{body}`, HMAC-SHA256 with the base64-decoded part of the secret after `whsec_`                                                                                                                                                                                                                                                                        |
| Timestamp window         | Refuse a `webhook-timestamp` more than 5 minutes from your clock                                                                                                                                                                                                                                                                                                                        |
| Request to your endpoint | `POST`, `content-type: application/json`, `user-agent: Rasen-Webhooks/1.0`, body at most 1 MiB                                                                                                                                                                                                                                                                                          |
| Page size                | `limit` 1 to 200, 50 by default                                                                                                                                                                                                                                                                                                                                                         |
| Environment              | `RASEN_API_BASE` (the base URL, ending in `/v1`), `RASEN_API_KEY`, `WEBHOOK_URL`, `ENDPOINT_ID`, `DELIVERY_ID`                                                                                                                                                                                                                                                                          |
| Python                   | 3.10 or later, with the `httpx` package                                                                                                                                                                                                                                                                                                                                                 |
| TypeScript               | Node.js 22 or later (built-in `fetch`)                                                                                                                                                                                                                                                                                                                                                  |

## Steps

Set `WEBHOOK_URL` to the HTTPS URL of your receiver, for example `https://hooks.example.com/rasen`.

### 1. Create an endpoint

**`curl`**

```bash curl
curl -sS -X POST "$RASEN_API_BASE/webhook-endpoints" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d "{\"url\": \"$WEBHOOK_URL\", \"description\": \"Call results\", \"events\": [\"call.completed\", \"call.failed\", \"call.analyzed\"]}"
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
WEBHOOK_URL = os.environ["WEBHOOK_URL"]

response = httpx.post(
    f"{BASE}/webhook-endpoints",
    headers={"Authorization": f"Bearer {KEY}", "Idempotency-Key": str(uuid.uuid4())},
    json={
        "url": WEBHOOK_URL,
        "description": "Call results",
        "events": ["call.completed", "call.failed", "call.analyzed"],
    },
)
response.raise_for_status()
endpoint = response.json()
print(endpoint["id"], endpoint["state"])
print(endpoint["secret"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, WEBHOOK_URL } = process.env;

const response = await fetch(`${RASEN_API_BASE}/webhook-endpoints`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    url: WEBHOOK_URL,
    description: "Call results",
    events: ["call.completed", "call.failed", "call.analyzed"],
  }),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const endpoint = await response.json();
console.log(endpoint.id, endpoint.state);
console.log(endpoint.secret);
```

The answer is `201` with the endpoint, its `ETag` and its signing `secret`. Store the `secret` in
your secret store now: no other answer returns it. A replay of the same `Idempotency-Key` and body
answers `201` with `"secret": null` and `Idempotent-Replayed: true`. Set `ENDPOINT_ID` to the `id`
of the endpoint.

### 2. Verify the signature in your receiver

This code runs in your receiver, not against the API. Give it the stored secret, the three
`webhook-*` request headers (with lower-case names) and the exact request body bytes, before you
parse the JSON. A Standard Webhooks library also verifies this signature. Each file ends with a self-check that signs a body with a random test secret.

**`Python`**

```python Python
import base64
import hashlib
import hmac
import os
import time

TOLERANCE_SECONDS = 5 * 60


def verify_webhook(secret: str, headers: dict[str, str], body: bytes) -> bool:
    webhook_id = headers.get("webhook-id", "")
    timestamp = headers.get("webhook-timestamp", "")
    signatures = headers.get("webhook-signature", "")
    if not webhook_id or not timestamp.isdigit() or not signatures:
        return False
    if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
        return False
    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{webhook_id}.{timestamp}.".encode() + body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
    for value in signatures.split(" "):
        version, _, signature = value.partition(",")
        if version == "v1" and hmac.compare_digest(signature, expected):
            return True
    return False


if __name__ == "__main__":
    test_secret = "whsec_" + base64.b64encode(os.urandom(32)).decode()
    test_body = b'{"type": "webhook.test"}'
    test_id = "wevt_01j00000000000000000000000"
    test_time = str(int(time.time()))
    test_key = base64.b64decode(test_secret.removeprefix("whsec_"))
    digest = hmac.new(test_key, f"{test_id}.{test_time}.".encode() + test_body, hashlib.sha256).digest()
    test_headers = {
        "webhook-id": test_id,
        "webhook-timestamp": test_time,
        "webhook-signature": "v1,AAAA v1," + base64.b64encode(digest).decode(),
    }
    print(verify_webhook(test_secret, test_headers, test_body))
```

**`TypeScript`**

```typescript TypeScript
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";

const TOLERANCE_SECONDS = 5 * 60;

export function verifyWebhook(secret: string, headers: Record<string, string | undefined>, body: Buffer): boolean {
  const webhookId = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  const signatures = headers["webhook-signature"];
  if (!webhookId || !timestamp || !/^[0-9]{1,12}$/.test(timestamp) || !signatures) return false;
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) return false;
  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = createHmac("sha256", key).update(`${webhookId}.${timestamp}.`).update(body).digest();
  return signatures.split(" ").some((value) => {
    const [version, signature] = value.split(",", 2);
    if (version !== "v1" || !signature) return false;
    const given = Buffer.from(signature, "base64");
    return given.length === expected.length && timingSafeEqual(given, expected);
  });
}

const testSecret = `whsec_${randomBytes(32).toString("base64")}`;
const testBody = Buffer.from('{"type": "webhook.test"}');
const testId = "wevt_01j00000000000000000000000";
const testTime = String(Math.floor(Date.now() / 1000));
const digest = createHmac("sha256", Buffer.from(testSecret.slice("whsec_".length), "base64"))
  .update(`${testId}.${testTime}.`)
  .update(testBody)
  .digest("base64");
console.log(
  verifyWebhook(
    testSecret,
    { "webhook-id": testId, "webhook-timestamp": testTime, "webhook-signature": `v1,AAAA v1,${digest}` },
    testBody,
  ),
);
```

The Python file prints `True` and the TypeScript file prints `true`. The `webhook-signature`
header holds one or two space-separated `v1,<signature>` values. During a rotation grace period it
holds one value for each secret. If no value matches, answer with a status that is not `2xx` and
do not process the event. Do the same if the timestamp is more than 5 minutes from your clock. If
the signature is valid, answer `2xx`.

### 3. Send a test event

**`curl`**

```bash curl
curl -sS -X POST "$RASEN_API_BASE/webhook-endpoints/$ENDPOINT_ID/test" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)"
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
ENDPOINT_ID = os.environ["ENDPOINT_ID"]

response = httpx.post(
    f"{BASE}/webhook-endpoints/{ENDPOINT_ID}/test",
    headers={"Authorization": f"Bearer {KEY}", "Idempotency-Key": str(uuid.uuid4())},
)
response.raise_for_status()
delivery = response.json()
print(delivery["id"], delivery["event_type"], delivery["state"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, ENDPOINT_ID } = process.env;

const response = await fetch(`${RASEN_API_BASE}/webhook-endpoints/${ENDPOINT_ID}/test`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
  },
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const delivery = await response.json();
console.log(delivery.id, delivery.event_type, delivery.state);
```

The answer is `201` with the queued delivery of one `webhook.test` event. Rasen sends it to this
endpoint only, whatever its `events` list. A disabled endpoint answers `409 conflict` with
`details.reason: endpoint_disabled`.

### 4. List the deliveries

**`curl`**

```bash curl
curl -sS -G "$RASEN_API_BASE/webhook-endpoints/$ENDPOINT_ID/deliveries" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  --data-urlencode "state=failed" \
  --data-urlencode "state=succeeded" \
  --data-urlencode "limit=50"
```

**`Python`**

```python Python
import os

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
ENDPOINT_ID = os.environ["ENDPOINT_ID"]

response = httpx.get(
    f"{BASE}/webhook-endpoints/{ENDPOINT_ID}/deliveries",
    headers={"Authorization": f"Bearer {KEY}"},
    params=[("state", "failed"), ("state", "succeeded"), ("limit", "50")],
)
response.raise_for_status()
page = response.json()
for delivery in page["items"]:
    print(delivery["id"], delivery["event_type"], delivery["state"], delivery["last_status_code"])
print(page["next_cursor"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, ENDPOINT_ID } = process.env;

const query = new URLSearchParams([
  ["state", "failed"],
  ["state", "succeeded"],
  ["limit", "50"],
]);
const response = await fetch(`${RASEN_API_BASE}/webhook-endpoints/${ENDPOINT_ID}/deliveries?${query}`, {
  headers: { Authorization: `Bearer ${RASEN_API_KEY}` },
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const page = await response.json();
for (const delivery of page.items) {
  console.log(delivery.id, delivery.event_type, delivery.state, delivery.last_status_code);
}
console.log(page.next_cursor);
```

The answer is one page of deliveries of the last 30 days, newest first. A repeated parameter
matches any of its values; different parameters must all match. `state` takes `pending`, `held`,
`delivering`, `retrying`, `succeeded`, `failed` and `cancelled`; `event_type` takes the four event
types. `failed` means that all 8 attempts of the current chain failed; `last_error_class` gives the
class of the last failure. The list never carries a request body, a response body or response
headers. To get the next page, send `next_cursor` as `cursor` with the same filters and `limit`.

### 5. Resend a delivery

Set `DELIVERY_ID` to the `id` of a delivery in `state: succeeded` or `state: failed`, from step 4.

**`curl`**

```bash curl
curl -sS -X POST "$RASEN_API_BASE/webhook-deliveries/$DELIVERY_ID/resend" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)"
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
DELIVERY_ID = os.environ["DELIVERY_ID"]

response = httpx.post(
    f"{BASE}/webhook-deliveries/{DELIVERY_ID}/resend",
    headers={"Authorization": f"Bearer {KEY}", "Idempotency-Key": str(uuid.uuid4())},
)
response.raise_for_status()
delivery = response.json()
print(delivery["state"], delivery["chain_no"], delivery["attempt_count"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, DELIVERY_ID } = process.env;

const response = await fetch(`${RASEN_API_BASE}/webhook-deliveries/${DELIVERY_ID}/resend`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
  },
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const delivery = await response.json();
console.log(delivery.state, delivery.chain_no, delivery.attempt_count);
```

The answer is `200` with the delivery in `state: pending`, `chain_no` one higher and
`attempt_count: 0`. Rasen sends the same `webhook-id` and the same body bytes again, in a new
chain of 8 attempts. `created_at` of the delivery does not change.

### 6. Rotate the signing secret

The sample reads the endpoint first and sends its `ETag` as `If-Match`.

**`curl`**

```bash curl
ETAG=$(curl -fsS -D - -o /dev/null "$RASEN_API_BASE/webhook-endpoints/$ENDPOINT_ID" \
  -H "Authorization: Bearer $RASEN_API_KEY" | tr -d '\r' | awk 'tolower($1) == "etag:" {print $2}')

curl -sS -X POST "$RASEN_API_BASE/webhook-endpoints/$ENDPOINT_ID/rotate-secret" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "If-Match: $ETAG"
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
ENDPOINT_ID = os.environ["ENDPOINT_ID"]
AUTH = {"Authorization": f"Bearer {KEY}"}

current = httpx.get(f"{BASE}/webhook-endpoints/{ENDPOINT_ID}", headers=AUTH)
current.raise_for_status()

response = httpx.post(
    f"{BASE}/webhook-endpoints/{ENDPOINT_ID}/rotate-secret",
    headers={**AUTH, "Idempotency-Key": str(uuid.uuid4()), "If-Match": current.headers["ETag"]},
)
response.raise_for_status()
endpoint = response.json()
print(endpoint["secret"])
print(endpoint["previous_secret_expires_at"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, ENDPOINT_ID } = process.env;

const current = await fetch(`${RASEN_API_BASE}/webhook-endpoints/${ENDPOINT_ID}`, {
  headers: { Authorization: `Bearer ${RASEN_API_KEY}` },
});
if (!current.ok) throw new Error(`HTTP ${current.status}`);

const response = await fetch(`${RASEN_API_BASE}/webhook-endpoints/${ENDPOINT_ID}/rotate-secret`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
    "If-Match": current.headers.get("ETag")!,
  },
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const endpoint = await response.json();
console.log(endpoint.secret);
console.log(endpoint.previous_secret_expires_at);
```

The answer is `200` with the new `secret`, once. Store it, and give it to your receiver before
`previous_secret_expires_at`. The previous secret stays valid for 24 hours. Until then each attempt
carries two signatures, one for each secret, so a receiver with either secret accepts it. A
rotation during a grace period makes the current secret the previous one, with a new 24-hour grace
period. The older previous secret then stops working at once.

### 7. Replace, disable or enable the endpoint

A replace is a full replacement of `url`, `description`, `events` and `enabled`: send every field.
An omitted or `null` `description` removes the description. This sample disables the endpoint;
send `"enabled": true` to enable it again.

**`curl`**

```bash curl
ETAG=$(curl -fsS -D - -o /dev/null "$RASEN_API_BASE/webhook-endpoints/$ENDPOINT_ID" \
  -H "Authorization: Bearer $RASEN_API_KEY" | tr -d '\r' | awk 'tolower($1) == "etag:" {print $2}')

curl -sS -X PUT "$RASEN_API_BASE/webhook-endpoints/$ENDPOINT_ID" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "If-Match: $ETAG" \
  -H "Content-Type: application/json" \
  -d "{\"url\": \"$WEBHOOK_URL\", \"description\": \"Call results\", \"events\": [\"call.completed\", \"call.failed\", \"call.analyzed\"], \"enabled\": false}"
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
ENDPOINT_ID = os.environ["ENDPOINT_ID"]
WEBHOOK_URL = os.environ["WEBHOOK_URL"]
AUTH = {"Authorization": f"Bearer {KEY}"}

current = httpx.get(f"{BASE}/webhook-endpoints/{ENDPOINT_ID}", headers=AUTH)
current.raise_for_status()

response = httpx.put(
    f"{BASE}/webhook-endpoints/{ENDPOINT_ID}",
    headers={**AUTH, "Idempotency-Key": str(uuid.uuid4()), "If-Match": current.headers["ETag"]},
    json={
        "url": WEBHOOK_URL,
        "description": "Call results",
        "events": ["call.completed", "call.failed", "call.analyzed"],
        "enabled": False,
    },
)
response.raise_for_status()
endpoint = response.json()
print(endpoint["state"], endpoint["disabled_at"], endpoint["revision"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, ENDPOINT_ID, WEBHOOK_URL } = process.env;

const current = await fetch(`${RASEN_API_BASE}/webhook-endpoints/${ENDPOINT_ID}`, {
  headers: { Authorization: `Bearer ${RASEN_API_KEY}` },
});
if (!current.ok) throw new Error(`HTTP ${current.status}`);

const response = await fetch(`${RASEN_API_BASE}/webhook-endpoints/${ENDPOINT_ID}`, {
  method: "PUT",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
    "If-Match": current.headers.get("ETag")!,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    url: WEBHOOK_URL,
    description: "Call results",
    events: ["call.completed", "call.failed", "call.analyzed"],
    enabled: false,
  }),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const endpoint = await response.json();
console.log(endpoint.state, endpoint.disabled_at, endpoint.revision);
```

The answer is `200` with the endpoint and its new `ETag`. What each change does:

| Change                                                         | Effect                                                                                                                                                                                        |
| -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `enabled: false` on an `enabled` endpoint                      | `state: disabled`. Pending deliveries are held and make no attempt                                                                                                                            |
| `enabled: false` on a `disabled_failing` endpoint              | The endpoint stays `disabled_failing`                                                                                                                                                         |
| `enabled: true` on a `disabled` or `disabled_failing` endpoint | `state: enabled`. Clears `failing_since` and the failure count, and releases held deliveries. A held delivery whose event is older than 30 days is cancelled (`cancel_reason: event_expired`) |
| A new `url`                                                    | The destination check runs again. A pending delivery uses the new `url` at its next attempt                                                                                                   |
| An event type removed from `events`                            | Pending deliveries of that type are cancelled (`cancel_reason: event_unsubscribed`)                                                                                                           |
| No change                                                      | `200` with the same `revision`                                                                                                                                                                |

### 8. Delete the endpoint

**`curl`**

```bash curl
ETAG=$(curl -fsS -D - -o /dev/null "$RASEN_API_BASE/webhook-endpoints/$ENDPOINT_ID" \
  -H "Authorization: Bearer $RASEN_API_KEY" | tr -d '\r' | awk 'tolower($1) == "etag:" {print $2}')

curl -sS -X DELETE "$RASEN_API_BASE/webhook-endpoints/$ENDPOINT_ID" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "If-Match: $ETAG"
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
ENDPOINT_ID = os.environ["ENDPOINT_ID"]
AUTH = {"Authorization": f"Bearer {KEY}"}

current = httpx.get(f"{BASE}/webhook-endpoints/{ENDPOINT_ID}", headers=AUTH)
current.raise_for_status()

response = httpx.delete(
    f"{BASE}/webhook-endpoints/{ENDPOINT_ID}",
    headers={**AUTH, "Idempotency-Key": str(uuid.uuid4()), "If-Match": current.headers["ETag"]},
)
response.raise_for_status()
print(response.json()["deleted_at"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, ENDPOINT_ID } = process.env;

const current = await fetch(`${RASEN_API_BASE}/webhook-endpoints/${ENDPOINT_ID}`, {
  headers: { Authorization: `Bearer ${RASEN_API_KEY}` },
});
if (!current.ok) throw new Error(`HTTP ${current.status}`);

const response = await fetch(`${RASEN_API_BASE}/webhook-endpoints/${ENDPOINT_ID}`, {
  method: "DELETE",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
    "If-Match": current.headers.get("ETag")!,
  },
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log((await response.json()).deleted_at);
```

The answer is `200` with the endpoint as it was left, with `deleted_at` set. The endpoint stops
receiving events at once. Rasen cancels its pending, held, delivering and retrying deliveries
(`cancel_reason: endpoint_deleted`) and destroys every version of its signing secret. An attempt
already in flight is not recalled. After the delete, every operation on the endpoint answers
`404 not_found`, a second delete included. Delete works in a suspended workspace.

## Rules

* MUST store the `secret` from `createWebhookEndpoint` and `rotateWebhookSigningSecret` when the
  answer arrives. Rasen keeps no plaintext copy, and a replay returns `"secret": null`.
* MUST verify `webhook-signature` over `{webhook-id}.{webhook-timestamp}.{body}` with the exact
  request body bytes, before you parse the body.
* MUST accept the request when any `v1` value in `webhook-signature` matches.
* MUST refuse a request whose `webhook-timestamp` is more than 5 minutes from your clock.
* MUST deduplicate on `webhook-id`. Delivery is at least once, and every attempt, retry and resend
  of one event carries the same `webhook-id` and the same body bytes.
* MUST NOT depend on the order of events. Rasen gives no ordering guarantee.
* MUST answer `2xx` to accept an event. Any other status, a `3xx` included, or a timeout fails the
  attempt.
* MUST answer `2xx` to an event `type` that you do not know, and ignore it.
* MUST read the call with `getCall` when `data.truncated` is `true`: the body is in the reduced
  form.
* MUST treat an endpoint `state` that you do not know as not enabled.
* MUST send the `ETag` of the endpoint as `If-Match` on replace, delete and rotate. After a
  `stale_revision` conflict, read the endpoint again and check the change before you send it with
  the new `ETag`.
* MUST send a new `Idempotency-Key` for each new action, and the same key, body and `If-Match` to
  retry an action whose answer was lost.
* MUST NOT put user information (`user:password@`) or a fragment in the endpoint `url`. A query
  string is allowed; every workspace member who can read the endpoint sees the whole `url`.

## Verify

Run this before you delete the endpoint in step 8. It lists the `webhook.test` deliveries that
your receiver accepted.

```bash
curl -sS -G "$RASEN_API_BASE/webhook-endpoints/$ENDPOINT_ID/deliveries" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  --data-urlencode "event_type=webhook.test" \
  --data-urlencode "state=succeeded"
```

Expected output: at least one item with `"state": "succeeded"` and a `2xx` `last_status_code`.

```json
{"items": [{"id": "wdl_01j00000000000000000000000", "event_type": "webhook.test", "call_id": null, "state": "succeeded", "chain_no": 1, "attempt_count": 1, "max_attempts": 8, "last_status_code": 200, "last_error_class": null}], "next_cursor": null}
```

## Errors

A resend tests its conflict reasons in this order: `endpoint_deleted`, `event_expired`,
`delivery_cancelled`, `delivery_in_progress`, `endpoint_disabled`, `event_unsubscribed`.

| Code                                                  | Cause                                                                                                                                                                          | Fix                                                                                                          |
| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ |
| `invalid_request`                                     | The request breaks the schema. Examples: a `url` with user information or a fragment, an event type twice in `events`, an empty filter value. `details.field` names the field. | Fix the field and send the request again with a new `Idempotency-Key`.                                       |
| `forbidden`                                           | The key lacks the `webhooks.manage` capability.                                                                                                                                | Use a key with `webhooks.manage`. `details.required_capabilities` lists what is missing.                     |
| `not_found`                                           | The endpoint or delivery is unknown, of another workspace, or the endpoint is deleted.                                                                                         | Check `ENDPOINT_ID` or `DELIVERY_ID` with `listWebhookEndpoints` or `listWebhookDeliveries`.                 |
| `outbound_destination_refused`                        | The `url` is not `https`, or its host does not resolve only to public addresses. Nothing is stored or changed.                                                                 | Use an `https` URL whose host resolves only to public addresses.                                             |
| `workspace_unavailable`                               | The workspace is suspended.                                                                                                                                                    | Send the request again when the workspace is active. `deleteWebhookEndpoint` works in a suspended workspace. |
| `revision_required`                                   | `If-Match` is missing on replace, delete or rotate.                                                                                                                            | Read the endpoint and send its `ETag` as `If-Match`.                                                         |
| `conflict` (`details.reason: stale_revision`)         | The `If-Match` is not the current `ETag` of the endpoint.                                                                                                                      | Read the endpoint again, check the change, then send it with the new `ETag` and a new `Idempotency-Key`.     |
| `conflict` (`details.reason: endpoint_limit_reached`) | The workspace has 10 endpoints that are not deleted.                                                                                                                           | Delete an endpoint, or add the event types to an existing endpoint with `replaceWebhookEndpoint`.            |
| `conflict` (`details.reason: endpoint_disabled`)      | A test event or a resend for an endpoint in `state: disabled` or `disabled_failing`.                                                                                           | Enable the endpoint with `replaceWebhookEndpoint` and `"enabled": true`, then send the request again.        |
| `conflict` (`details.reason: endpoint_deleted`)       | A resend of a delivery whose endpoint is deleted.                                                                                                                              | Do not retry. The delivery cannot be sent again.                                                             |
| `conflict` (`details.reason: event_expired`)          | A resend of a delivery whose event is older than 30 days.                                                                                                                      | Do not retry. Read the call with `getCall`.                                                                  |
| `conflict` (`details.reason: delivery_cancelled`)     | A resend of a delivery in `state: cancelled`.                                                                                                                                  | Do not retry. `cancel_reason` of the delivery says why it was cancelled.                                     |
| `conflict` (`details.reason: delivery_in_progress`)   | A resend of a delivery that is not finished, for example during a concurrent resend.                                                                                           | Wait until the delivery is in `state: succeeded` or `failed`, then resend it.                                |
| `conflict` (`details.reason: event_unsubscribed`)     | A resend of a call event whose type is not in the `events` of the endpoint.                                                                                                    | Add the event type to `events` with `replaceWebhookEndpoint`, then resend.                                   |
| `idempotency_key_reused`                              | The `Idempotency-Key` was used for a different request.                                                                                                                        | Send a new key for a new request.                                                                            |
| `idempotency_in_progress`                             | The same request is still running.                                                                                                                                             | Wait for `Retry-After` seconds, then send the identical request with the same key and `If-Match`.            |
| `idempotency_result_gone`                             | Rasen cannot return the original result of this `Idempotency-Key`.                                                                                                             | Read the endpoint or delivery to reconcile before you send a new request with a new key.                     |

## Related

* [Webhook events](/reference/webhook-events)
* [Idempotency and replay](/concepts/idempotency)
* [Revisions and ETags](/concepts/revisions)
* [Pagination](/concepts/pagination)
* [Errors](/concepts/errors)
* [API reference](/api-reference)