> ## Documentation Index
> Fetch the complete documentation index at: https://openwearables.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Outgoing Webhooks

> Receive real-time notifications when health data arrives for your users. Register HTTPS endpoints, filter by event type or user, verify signatures, and debug delivery.

## Overview

Outgoing webhooks let Open Wearables push events to your backend in real time, so you don't need to poll for new data. Each time a workout is saved, sleep is recorded, or a timeseries batch is ingested, Open Wearables fires an HTTP POST request to every registered endpoint that matches the event.

Webhooks are delivered via [Svix](https://svix.com/), which handles retries, signature signing, and delivery history.

> [!NOTE]
>
> **Self-hosting:** outgoing webhooks are **disabled by default**. To emit events, set `OUTGOING_WEBHOOKS_ENABLED=true` in the backend `.env` and restart — no command-line flags needed, plain `docker compose up`. The `svix-server` container runs either way, and the app runs fine when it is absent (e.g. a deployment without webhooks). On managed Postgres (AWS RDS / Railway), the app's database user must be allowed to create databases, or create a `svix` database up front — Svix keeps its schema there.

> [card] Things you can do
>
> Trigger downstream processing when a workout is synced, update your UI in real time when sleep data arrives, scope an endpoint to a single user's events, or verify payloads are genuinely from Open Wearables.

> [card] Requirements
>
> A developer account and a Bearer token (from `POST /api/v1/auth/login`), plus a publicly reachable HTTPS URL for your endpoint.

***

## Quickstart

**1. Register an endpoint**

Send the URL your server is listening on. This returns an endpoint object you'll use in subsequent calls.

```bash theme={null}
curl -X POST "http://localhost:8000/api/v1/webhooks/endpoints" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://yourapp.com/webhooks/health",
    "description": "Production health data handler"
  }'
```

**Response:**

```json theme={null}
{
  "id": "ep_2t8Q4Xv9mNkRpLzYoB3cW7",
  "url": "https://yourapp.com/webhooks/health",
  "description": "Production health data handler",
  "filter_types": null,
  "user_id": null
}
```

Save the `id` — you'll need it to fetch the signing secret and inspect delivery attempts.

**2. Get the signing secret**

Retrieve the HMAC signing key for your endpoint to verify incoming payloads.

```bash theme={null}
curl "http://localhost:8000/api/v1/webhooks/endpoints/ep_2t8Q4Xv9mNkRpLzYoB3cW7/secret" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

**Response:**

```json theme={null}
{
  "key": "whsec_C2FVsBQIhrscChlQIMV+b5ND9vAIBZaM7ZqtLnNYGDA="
}
```

Store this secret securely on your server — you'll use it to verify every incoming request.

**3. Handle incoming events**

Open Wearables sends a `POST` to your URL with a JSON body and three signature headers. Verify the signature before processing.

> [tab] Python
>
> ```python theme={null}
> from svix.webhooks import Webhook, WebhookVerificationError
> from fastapi import FastAPI, Request, HTTPException
>
> app = FastAPI()
> WEBHOOK_SECRET = "whsec_C2FVsBQIhrscChlQIMV+b5ND9vAIBZaM7ZqtLnNYGDA="
>
> @app.post("/webhooks/health")
> async def handle_webhook(request: Request):
>     headers = dict(request.headers)
>     payload = await request.body()
>
>     try:
>         wh = Webhook(WEBHOOK_SECRET)
>         event = wh.verify(payload, headers)
>     except WebhookVerificationError:
>         raise HTTPException(status_code=400, detail="Invalid signature")
>
>     event_type = event["type"]
>
>     if event_type == "workout.created":
>         data = event["data"]
>         print(f"New workout for user {data['user_id']}: "
>               f"{data['type']} — {data['duration_seconds']}s")
>
>     elif event_type == "sleep.created":
>         data = event["data"]
>         print(f"New sleep for user {data['user_id']}: "
>               f"efficiency {data.get('efficiency_percent')}%")
>
>     return {"ok": True}
> ```

> [tab] Node.js
>
> ```javascript theme={null}
> import { Webhook } from "svix";
> import express from "express";
>
> const app = express();
> const WEBHOOK_SECRET = "whsec_C2FVsBQIhrscChlQIMV+b5ND9vAIBZaM7ZqtLnNYGDA=";
>
> app.post(
>   "/webhooks/health",
>   express.raw({ type: "application/json" }),
>   (req, res) => {
>     const wh = new Webhook(WEBHOOK_SECRET);
>     let event;
>
>     try {
>       event = wh.verify(req.body, req.headers);
>     } catch (err) {
>       return res.status(400).json({ error: "Invalid signature" });
>     }
>
>     if (event.type === "workout.created") {
>       console.log(`Workout for user ${event.data.user_id}:`,
>         event.data.type, event.data.duration_seconds + "s");
>     }
>
>     res.json({ ok: true });
>   }
> );
> ```

> [tab] cURL (manual verify)
>
> ```bash theme={null}
> # The three signature headers sent with every request:
> # svix-id         — unique message ID (for idempotency)
> # svix-timestamp  — Unix timestamp of delivery attempt
> # svix-signature  — comma-separated list of v1,<base64_hmac> signatures
> #
> # To verify manually:
> # 1. Build the signed content: "{svix-id}.{svix-timestamp}.{raw_body}"
> # 2. HMAC-SHA256 the content with the base64-decoded key (strip "whsec_" prefix)
> # 3. Base64-encode the result
> # 4. Compare with the signature in the svix-signature header
> ```

> [!TIP]
>
> Install the Svix library: `pip install svix` / `npm install svix`. The `Webhook.verify()` call handles timestamp tolerance (rejects messages older than 5 minutes) and all signature edge cases automatically.

**4. Send a test event**

Trigger a realistic example payload to your endpoint to confirm end-to-end delivery before you go live.

```bash theme={null}
curl -X POST "http://localhost:8000/api/v1/webhooks/endpoints/ep_2t8Q4Xv9mNkRpLzYoB3cW7/test" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "event_type": "workout.created" }'
```

Check delivery status at any time:

```bash theme={null}
curl "http://localhost:8000/api/v1/webhooks/endpoints/ep_2t8Q4Xv9mNkRpLzYoB3cW7/attempts" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

***

## Event Types

All events follow the `resource.action` naming convention. Use `GET /api/v1/webhooks/event-types` to retrieve this list programmatically.

### Session Events

Fired once when a complete session is saved or merged.

| Event | Description |
| - | - |
| `connection.created` | A user successfully connected a wearable provider. For OAuth providers this fires when authorization completes; SDK providers have no OAuth callback, so it fires when the first data upload arrives, and again when a previously revoked SDK connection resumes uploading. |
| `connection.revoked` | A connection became invalid or was disconnected (refresh token expired/revoked, the user deregistered on the provider side, or the user manually disconnected). OAuth connections require re-authorization to resume syncing; SDK connections resume on the next upload. See the `reason` field. |
| `workout.created` | A new workout session was saved. |
| `sleep.created` | A new (or merged) sleep session was saved. |
| `meal.created` | A new meal or nutrition-log entry was saved. |
| `menstrual_cycle.created` | A new menstrual cycle record was saved. |
| `activity.created` | A new generic activity session was saved. |

### Timeseries Events

Fired per ingestion batch — one event per distinct `(user, provider, series_type)` combination in a sync run. Each event carries the full `samples` array, so consumers can store data directly from the webhook without issuing follow-up API calls.

| Event | Series types included |
| - | - |
| `heart_rate.created` | `heart_rate`, `resting_heart_rate`, `heart_rate_recovery_one_minute`, `walking_heart_rate`, `atrial_fibrillation_burden` |
| `heart_rate_variability.created` | `heart_rate_variability_sdnn`, `heart_rate_variability_rmssd` |
| `steps.created` | `steps` |
| `calories.created` | `active_energy`, `basal_energy`, `total_energy` |
| `spo2.created` | `oxygen_saturation`, `peripheral_perfusion_index` |
| `respiratory_rate.created` | `respiratory_rate`, `sleeping_breathing_disturbances` |
| `body_temperature.created` | `body_temperature`, `skin_temperature`, `skin_temperature_deviation` |
| `stress.created` | `garmin_stress_level`, `electrodermal_activity` |
| `blood_glucose.created` | `blood_glucose`, `blood_alcohol_content`, `insulin_delivery` |
| `blood_pressure.created` | `blood_pressure_systolic`, `blood_pressure_diastolic` |
| `body_composition.created` | `weight`, `body_fat_percentage`, `body_mass_index`, `lean_body_mass`, … |
| `fitness_metrics.created` | `vo2_max`, `cardiovascular_age`, `garmin_fitness_age` |
| `recovery_score.created` | `recovery_score`, `garmin_body_battery` |
| `activity_timeseries.created` | `stand_time`, `exercise_time`, `flights_climbed`, distance types, … |
| `workout_metrics.created` | `cadence`, `power`, `speed`, running/walking/swimming metrics |
| `environmental.created` | `environmental_audio_exposure`, `uv_exposure`, `weather_temperature`, … |
| `timeseries.created` | Catch-all for series types not yet explicitly mapped. |

Each series type also has its own event, `series.<series_type>.created`, carrying only that series' samples.

> [!NOTE]
>
> Two series changed in this release, and their events with them:
>
> | Before | Now |
> | - | - |
> | `series.walking_heart_rate_average.created` | `series.walking_heart_rate.created` |
> | `series.average_met.created` | retired: a workout's average MET is its `physical_effort` average, returned as the workout's `average_met` |
>
> Self-hosting with endpoints that filter on the old names: run `scripts/data_migrations/rename_series_webhook_events.py --phase=add` from the new image before it takes traffic, so those endpoints also subscribe to the new names, and `--phase=remove` once the deploy is done. An endpoint whose filter names only old events is left as it is, as removing them would leave it with no filter and every event: the script lists it, and its filter needs the new names set by hand.

***

## Payload Reference

Every payload envelope has `type` (the event name as a string) and `data`.

### `connection.created`

```json theme={null}
{
  "type": "connection.created",
  "data": {
    "user_id": "550e8400-e29b-41d4-a716-446655440000",
    "provider": "garmin",
    "connection_id": "7f3d9c2a-1b4e-4f8a-9d6c-8e5f2a0b3c7e",
    "connected_at": "2025-12-19T10:30:00+00:00"
  }
}
```

### `connection.revoked`

`reason` is a short cause:

| Reason | Cause |
| - | - |
| `user_disconnected` | The connection was disconnected via the API. |
| `sdk_sign_out` | The user signed out of the mobile app; the SDK reported it with its own token. |
| `refresh_failed` | The OAuth refresh token was rejected by the provider. |
| `deregistration` | The user deregistered on the provider side (Garmin) or deauthorized the app (Strava). A Strava request that hits the dead grant before the deauthorization event is processed revokes the connection with `refresh_failed` instead. |

```json theme={null}
{
  "type": "connection.revoked",
  "data": {
    "user_id": "550e8400-e29b-41d4-a716-446655440000",
    "provider": "garmin",
    "connection_id": "7f3d9c2a-1b4e-4f8a-9d6c-8e5f2a0b3c7e",
    "reason": "refresh_failed",
    "revoked_at": "2025-12-19T10:30:00+00:00"
  }
}
```

### `workout.created`

```json theme={null}
{
  "type": "workout.created",
  "data": {
    "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "user_id": "550e8400-e29b-41d4-a716-446655440000",
    "type": "running",
    "start_time": "2025-12-19T07:30:00+01:00",
    "end_time": "2025-12-19T08:30:00+01:00",
    "zone_offset": "+01:00",
    "duration_seconds": 3600.0,
    "source": {
      "provider": "garmin",
      "device": "Forerunner 255"
    },
    "calories_kcal": 480.0,
    "distance_meters": 10200.0,
    "avg_heart_rate_bpm": 158,
    "max_heart_rate_bpm": 182,
    "avg_pace_sec_per_km": 353,
    "elevation_gain_meters": 95.0
  }
}
```

> [!NOTE]
>
> Fields like `calories_kcal`, `distance_meters`, and heart-rate fields are `null` when the provider did not report them.

### `sleep.created`

`sleep_stage_intervals` below is shown **abbreviated** — three intervals out of a full night — to keep the example short. A real payload's array covers the entire session end-to-end (typically 15-60+ merged intervals, depending on how fragmented the sleep was).

```json theme={null}
{
  "type": "sleep.created",
  "data": {
    "id": "b2c3d4e5-f6a7-8901-bcde-f12345678901",
    "user_id": "550e8400-e29b-41d4-a716-446655440000",
    "start_time": "2025-12-19T22:15:00+01:00",
    "end_time": "2025-12-20T06:45:00+01:00",
    "zone_offset": "+01:00",
    "duration_seconds": 30600.0,
    "sleep_duration_seconds": 29400.0,
    "source": {
      "provider": "oura",
      "source": "oura",
      "device": "Oura Ring Gen3",
      "device_type": "ring",
      "device_name": "Oura Ring Gen3"
    },
    "efficiency_percent": 87.0,
    "stages": {
      "deep_minutes": 95,
      "rem_minutes": 80,
      "light_minutes": 215,
      "awake_minutes": 12
    },
    "sleep_stage_intervals": [
      {
        "stage": "light",
        "start_time": "2025-12-19T22:15:00+01:00",
        "end_time": "2025-12-19T22:45:00+01:00"
      },
      {
        "stage": "deep",
        "start_time": "2025-12-19T22:45:00+01:00",
        "end_time": "2025-12-19T23:30:00+01:00"
      },
      {
        "stage": "rem",
        "start_time": "2025-12-20T06:15:00+01:00",
        "end_time": "2025-12-20T06:45:00+01:00"
      }
    ],
    "is_nap": false
  }
}
```

> [!NOTE]
>
> `sleep_duration_seconds` is the time actually asleep (excludes awake periods within the session); `duration_seconds` is the session's span from `start_time` to `end_time`, awake time included. Both `source.source` (the third-party writer app, e.g. HealthKit/Health Connect) and `sleep_stage_intervals` are `null`/omitted when the provider or ingestion path did not report them. Likewise, a stage's minutes in `stages` are `null` when the source did not measure that stage, and `stages` itself is `null` when no stage is reported. Unlike every other field in this example, `sleep_stage_intervals` above is **not** shown in full — see the note before the code block.

For providers that don't flag naps, `is_nap` is derived by Open Wearables and can change after the webhook (see [Data types](https://openwearables.io/docs/architecture/data-types.md)). A change sends no webhook, so read the session again for the current value. Mobile SDK and Sensor Bio sessions are announced with `is_nap: false`.

### `meal.created`

```json theme={null}
{
  "type": "meal.created",
  "data": {
    "id": "e5f6a7b8-c9d0-1234-efab-234567890123",
    "user_id": "550e8400-e29b-41d4-a716-446655440000",
    "title": "Grilled Chicken Breast",
    "meal_type": "lunch",
    "start_time": "2025-12-19T12:30:00+01:00",
    "end_time": "2025-12-19T12:30:00+01:00",
    "zone_offset": "+01:00",
    "source": {
      "provider": "apple",
      "device": "iPhone"
    },
    "calories_kcal": 550.0,
    "macros": {
      "protein_g": 38.2,
      "carbohydrates_g": 42.0,
      "fat_g": 18.5,
      "fiber_g": 4.0
    },
    "water_ml": null,
    "nutrients": {
      "dietary_energy_consumed": { "value": 550.0, "unit": "kcal" },
      "dietary_protein": { "value": 38.2, "unit": "g" },
      "dietary_carbohydrates": { "value": 42.0, "unit": "g" },
      "dietary_fat_total": { "value": 18.5, "unit": "g" },
      "dietary_fiber": { "value": 4.0, "unit": "g" },
      "dietary_sodium": { "value": 620.0, "unit": "mg" }
    }
  }
}
```

> [!NOTE]
>
> `title` and `meal_type` come from the provider's food-log entry (or HealthKit/Health Connect correlation metadata) and are `null` when not reported. `macros` is `null` when none of its four fields were recorded for the meal; each of `calories_kcal` and `water_ml` is `null` independently when that nutrient wasn't reported. `nutrients` holds every nutrient recorded for the meal, keyed by series type, the same as in `GET /events/meals`.

### `menstrual_cycle.created`

```json theme={null}
{
  "type": "menstrual_cycle.created",
  "data": {
    "id": "d4e5f6a7-b8c9-0123-defa-123456789012",
    "user_id": "550e8400-e29b-41d4-a716-446655440000",
    "start_time": "2025-12-01T00:00:00+00:00",
    "end_time": "2025-12-29T00:00:00+00:00",
    "zone_offset": null,
    "source": {
      "provider": "garmin",
      "device": null
    },
    "current_phase_type": "fertile",
    "day_in_cycle": 12,
    "cycle_length": 28,
    "is_predicted_cycle": false,
    "pregnancy_snapshot": null
  }
}
```

> [!NOTE]
>
> `pregnancy_snapshot` is populated (as a list with one entry) when the user is tracking a pregnancy. Garmin reuses the same summary ID for daily cycle updates — Open Wearables deduplicates by `external_id`, so the event fires only when a new record is first inserted.

### `activity.created`

```json theme={null}
{
  "type": "activity.created",
  "data": {
    "id": "c3d4e5f6-a7b8-9012-cdef-012345678902",
    "user_id": "550e8400-e29b-41d4-a716-446655440000",
    "type": "walking",
    "start_time": "2025-12-19T12:00:00+01:00",
    "end_time": "2025-12-19T12:45:00+01:00",
    "zone_offset": "+01:00",
    "duration_seconds": 2700.0,
    "source": {
      "provider": "garmin",
      "device": null
    }
  }
}
```

### Timeseries events (all share the same shape)

Each timeseries event carries the full sample array so your backend can act on the data immediately — no follow-up API call needed.

```json theme={null}
{
  "type": "heart_rate.created",
  "data": {
    "user_id": "550e8400-e29b-41d4-a716-446655440000",
    "provider": "garmin",
    "series_type": "heart_rate",
    "sample_count": 3,
    "start_time": "2025-12-19T07:30:00+01:00",
    "end_time": "2025-12-19T07:40:00+01:00",
    "samples": [
      {
        "timestamp": "2025-12-19T07:30:00+01:00",
        "zone_offset": "+01:00",
        "type": "heart_rate",
        "value": 62,
        "unit": "bpm",
        "source": { "provider": "garmin", "device": "Forerunner 255" },
        "is_daily_total": null,
        "window_seconds": null
      },
      {
        "timestamp": "2025-12-19T07:35:00+01:00",
        "zone_offset": "+01:00",
        "type": "heart_rate",
        "value": 65,
        "unit": "bpm",
        "source": { "provider": "garmin", "device": "Forerunner 255" },
        "is_daily_total": null,
        "window_seconds": null
      },
      {
        "timestamp": "2025-12-19T07:40:00+01:00",
        "zone_offset": "+01:00",
        "type": "heart_rate",
        "value": 70,
        "unit": "bpm",
        "source": { "provider": "garmin", "device": "Forerunner 255" },
        "is_daily_total": null,
        "window_seconds": null
      }
    ]
  }
}
```

Each entry in `samples` matches the schema returned by `GET /api/v1/users/{user_id}/timeseries`, so consumers work with a single schema regardless of whether data comes from a webhook or the pull API.

> [!NOTE]
>
> Series events carry readings only. A provider's **day value** (Garmin's daily step total, Oura's nightly SpO2, a readiness temperature) is not a sample any more and is not sent as one: read it from `GET /api/v1/users/{user_id}/timeseries?resolution=1day`, where every source's days are, the provider's own value where it sent one. Day values stored before this release are copied there by a backfill that runs after the upgrade; until it has reached them, they are still in `raw`. `is_daily_total` is therefore `false` or `null` on every sample a webhook carries; sum the samples of an additive series (steps, energy, distance, flights) as they come.

> [!NOTE]
>
> **`window_seconds`** is the width of a sample reported over a window rather than at an instant: a Garmin 15-minute epoch is `900`, a HealthKit record from 08:00 to 08:05 is `300`. `null` means an instant reading.

> [!NOTE]
>
> **Large batches** (exceeding 2 500 samples) are automatically split into consecutive chunk events to stay within Svix's 1 MB payload limit.  Each chunk event includes `chunk_index` (0-based) and `total_chunks` so you can detect and reassemble split deliveries.  The `sample_count` field always reflects the total number of samples across all chunks.

The pull API (`GET /api/v1/users/{user_id}/timeseries`) remains available for backfill, reconciliation, or recovery after missed deliveries.

***

## Filtering Events

### Filter by event type

Pass `filter_types` when creating or updating an endpoint to receive only the events you care about.

```bash theme={null}
curl -X POST "http://localhost:8000/api/v1/webhooks/endpoints" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://yourapp.com/webhooks/workouts-only",
    "description": "Workout and sleep events only",
    "filter_types": ["workout.created", "sleep.created"]
  }'
```

Omit the field entirely to receive all event types.

To later remove the event type filter from an existing endpoint (receive all event types again), send a `PATCH` with `"filter_types": []`:

```bash theme={null}
curl -X PATCH "http://localhost:8000/api/v1/webhooks/endpoints/ep_2t8Q4Xv9mNkRpLzYoB3cW7" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "filter_types": [] }'
```

> [!NOTE]
>
> The empty list is what clears the filter. Sending `"filter_types": null` — or leaving the field
> out — keeps the current filter, so a client that serialises unset fields as `null` will not wipe
> an endpoint's event types by accident. Note that `user_id` works the other way round: there
> `null` is what removes the filter.

### Filter by user

Pass `user_id` to scope an endpoint to events for a single user. All other users' events are silently dropped before delivery.

```bash theme={null}
curl -X POST "http://localhost:8000/api/v1/webhooks/endpoints" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://yourapp.com/webhooks/alice",
    "description": "Only Alice'\''s data",
    "user_id": "550e8400-e29b-41d4-a716-446655440000"
  }'
```

To later remove the user filter (receive all users again), send a `PATCH` with `"user_id": null`:

```bash theme={null}
curl -X PATCH "http://localhost:8000/api/v1/webhooks/endpoints/ep_2t8Q4Xv9mNkRpLzYoB3cW7" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "user_id": null }'
```

> [!TIP]
>
> Combine both filters to receive e.g. only `workout.created` events for a specific user — pass both `filter_types` and `user_id` in the same request.

***

## Signature Verification

Every delivery includes three headers that let you confirm the payload was sent by Open Wearables and hasn't been tampered with:

| Header | Description |
| - | - |
| `svix-id` | Unique message ID. Use this for idempotency — the same ID is retried on failure. |
| `svix-timestamp` | Unix seconds timestamp of the original send. Requests older than 5 minutes are auto-rejected by the Svix SDK. |
| `svix-signature` | Comma-separated list of `v1,<base64_hmac>` values. |

### Using the Svix SDK (recommended)

> [tab] Python
>
> ```python theme={null}
> from svix.webhooks import Webhook, WebhookVerificationError
>
> wh = Webhook("whsec_YOUR_SIGNING_SECRET")
>
> try:
>     # headers must include svix-id, svix-timestamp, svix-signature
>     payload = wh.verify(raw_body_bytes, headers_dict)
> except WebhookVerificationError:
>     # reject — signature invalid or timestamp too old
>     return 400
> ```
>
> Install: `pip install svix`

> [tab] Node.js
>
> ```javascript theme={null}
> import { Webhook } from "svix";
>
> const wh = new Webhook("whsec_YOUR_SIGNING_SECRET");
>
> try {
>   const payload = wh.verify(rawBodyBuffer, headersObject);
> } catch (err) {
>   // reject — signature invalid or timestamp too old
>   return res.status(400).end();
> }
> ```
>
> Install: `npm install svix`

> [tab] Manual (any language)
>
> ```
> # 1. Decode the key: base64_decode(key.removePrefix("whsec_"))
> # 2. Build the signed string: "{svix-id}.{svix-timestamp}.{raw_body}"
> # 3. Compute: HMAC-SHA256(key_bytes, signed_string)
> # 4. Encode: base64(hmac_bytes)
> # 5. Compare with each "v1,<value>" in the svix-signature header
> ```

> [!WARNING]
>
> Always verify signatures **before** processing the payload. This prevents replay attacks and ensures events cannot be forged by third parties.

### Idempotency

The `svix-id` header is stable across retries — the same logical event always carries the same ID. Store received IDs and skip duplicates to make your handler idempotent.

***

## Managing Endpoints

### List all endpoints

```bash theme={null}
curl "http://localhost:8000/api/v1/webhooks/endpoints" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

### Update an endpoint

All fields are optional — send only what you want to change.

```bash theme={null}
curl -X PATCH "http://localhost:8000/api/v1/webhooks/endpoints/ep_2t8Q4Xv9mNkRpLzYoB3cW7" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://yourapp.com/webhooks/health-v2",
    "filter_types": ["workout.created", "sleep.created", "heart_rate.created"]
  }'
```

### Delete an endpoint

```bash theme={null}
curl -X DELETE "http://localhost:8000/api/v1/webhooks/endpoints/ep_2t8Q4Xv9mNkRpLzYoB3cW7" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

Returns `204 No Content` on success.

***

## Delivery and Retries

Open Wearables (via Svix) retries failed deliveries automatically with exponential back-off. A delivery is considered failed when your endpoint returns a non-2xx status code or does not respond within the timeout.

> [accordion] Retry schedule
>
> Svix retries each failed message at increasing intervals. If all retries are exhausted the message is marked as failed in delivery history — you can inspect it and manually trigger a resend from the Svix dashboard, as long as its payload is still retained (see below).

> [accordion] Payload retention
>
> Svix stores each message payload for **7 days** by default, then deletes it. The message itself stays in delivery history, without the payload. Self-hosters can change this with `OUTGOING_WEBHOOK_PAYLOAD_RETENTION_DAYS` in the backend `.env` (5-90 days). The setting applies to messages sent after the change.
>
> Keep the retention above the automatic retry window, which is about 28 hours and can stretch to roughly 3 days when your endpoint returns `Retry-After`. Once a payload is gone, Svix drops any pending retry without recording an attempt, and the message can no longer be resent.

> [accordion] Expected endpoint behaviour
>
> * Respond with a `2xx` status code as quickly as possible (before doing any heavy processing).
> * Offload slow work to a background queue — process the event asynchronously.
> * Return `2xx` even for events you choose to ignore (otherwise they'll be retried).

> [accordion] Webhook availability
>
> Data ingestion is **never** blocked by webhook failures — if delivery infrastructure is temporarily unavailable, data continues to be stored and events are queued for retry.

> [accordion] User deletion
>
> When you delete a user (`DELETE /api/v1/users/{user_id}`), Open Wearables deletes the payloads of all their webhook messages from Svix in a background task, about a minute after the user is removed. The messages stay in delivery history without the payload, and their event IDs can still contain the user ID.
>
> The cleanup is best-effort. The one-minute delay lets webhooks already queued for that user reach Svix first, so they are cleaned up too, but a webhook queued for longer than that (for example when the worker is backlogged) is not covered. If the cleanup task cannot be queued at all, the user is still deleted and a warning is logged. In both cases the remaining payloads are removed when their payload retention period ends.

***

## Debugging

### View delivery history for an endpoint

```bash theme={null}
curl "http://localhost:8000/api/v1/webhooks/endpoints/ep_2t8Q4Xv9mNkRpLzYoB3cW7/attempts" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

Each attempt includes the HTTP status code returned by your server and the timestamp of the attempt.

### View all sent messages

```bash theme={null}
curl "http://localhost:8000/api/v1/webhooks/messages" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

### Send a test event

Send a realistic example payload for any event type to an endpoint without waiting for real data:

```bash theme={null}
curl -X POST "http://localhost:8000/api/v1/webhooks/endpoints/ep_2t8Q4Xv9mNkRpLzYoB3cW7/test" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "event_type": "sleep.created" }'
```

Omit the body to default to `workout.created`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.