# Webhooks

> Receive real-time notifications from Jump EHR via webhooks. Configure endpoints and handle events.

Source: https://docs.usejump.co.uk/webhooks

Webhooks allow you to receive real-time notifications when events occur in Jump EHR. Instead of polling the API for changes, webhooks push data to your server as events happen.

## Overview

When you configure a webhook endpoint, Jump EHR will send HTTP POST requests to your URL whenever subscribed events occur. This enables real-time integrations without consuming your API rate limit.

## Minimal payloads and fetch on notify

A webhook tells you **that** something changed, not **what** it now says. Each delivery carries the event and the id of the record it is about, and nothing personal or clinical: no names, dates of birth, NHS numbers, contact details, appointment details or answers. When you receive one, fetch the record through the API with your API key. That way a patient's details only ever travel over an authenticated request that your key is allowed to make, and a leaked or misrouted webhook exposes nothing.

Every endpoint created from now on sends minimal payloads:

```json
{
  "id": "6f1c2a4e-0b8d-4c35-9a77-2f5d1e8b3c90",
  "type": "appointment.rescheduled",
  "created_at": "2026-11-09T10:30:00.000Z",
  "organization_id": "00000000-0000-4000-8000-000000000001",
  "livemode": true,
  "data": {
    "object": {
      "id": "00000000-0000-4000-8000-000000000002",
      "object": "appointment",
      "status": "confirmed",
      "updated_at": "2026-11-09T10:29:58.000Z"
    }
  }
}
```

| Field                    | Description                                                                                                                                                                                                    |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`                     | The event's id. The same value is in `X-Webhook-Event-ID`; use it to skip duplicates.                                                                                                                          |
| `type`                   | The event type, for example `patient.updated`.                                                                                                                                                                 |
| `created_at`             | When the event happened (UTC).                                                                                                                                                                                 |
| `organization_id`        | The practice the event belongs to.                                                                                                                                                                             |
| `livemode`               | `false` when the event comes from a practice's sandbox.                                                                                                                                                        |
| `data.object.id`         | The id of the record the event is about.                                                                                                                                                                       |
| `data.object.object`     | What kind of record it is: `patient`, `appointment`, `clinician_profile`, `location`, `appointment_template`, `questionnaire_response` or `document`. It is always the part of `type` before the dot.          |
| `data.object.status`     | The record's status when the event was raised. For clinician profiles, locations and appointment templates, which have no status of their own, it is `active` or `inactive`. `null` for a record with neither. |
| `data.object.updated_at` | When the record last changed. Compare it with your own copy to ignore a notification older than what you already hold.                                                                                         |

There is no `data.previous` in a minimal payload. If you need to know what changed, compare the record you fetch with the copy you stored last time.

### Fetching the record

Use the record's resource on the API:

| `data.object.object`     | Fetch with                                                                    | Scope                        |
| ------------------------ | ----------------------------------------------------------------------------- | ---------------------------- |
| `patient`                | [`GET /patients/{id}`](https://docs.usejump.co.uk/api-reference/patients)                               | `read_patients`              |
| `appointment`            | [`GET /appointments/{id}`](https://docs.usejump.co.uk/api-reference/appointments)                       | `read_appointments`          |
| `clinician_profile`      | [`GET /clinician-profiles/{id}`](https://docs.usejump.co.uk/api-reference/clinician-profiles)           | `read_clinician_profiles`    |
| `location`               | [`GET /locations/{id}`](https://docs.usejump.co.uk/api-reference/locations)                             | `read_locations`             |
| `appointment_template`   | [`GET /appointment-templates/{id}`](https://docs.usejump.co.uk/api-reference/appointment-templates)     | `read_appointment_templates` |
| `questionnaire_response` | [`GET /questionnaire-responses/{id}`](https://docs.usejump.co.uk/api-reference/questionnaire-responses) | `read_questionnaires`        |

Document events (`document.created`, `document.updated`, available to endpoints set up in Jump) have no API resource yet, so a minimal document event tells you only that a document changed.

A few things to handle:

* **Acknowledge first, fetch after.** Return a 2xx straight away and fetch in the background, so a slow fetch never makes the delivery time out and retry.
* **A 404 is an answer.** The record may have been removed, or be outside what your key can read. Treat it as "nothing to do", not as a failure to retry for ever.
* **Expect notifications out of order.** Two quick changes can arrive the other way round. The fetch always returns the current record, so use `data.object.updated_at` (or the fetched record's) to keep the newest.
* **The fetch counts against your rate limit**, at one request per event you act on.

```javascript
app.post('/webhooks', express.raw({ type: 'application/json' }), async (req, res) => {
  if (!verifyWebhookSignature(req.body.toString(), req.headers['x-webhook-signature'], process.env.WEBHOOK_SECRET)) {
    return res.status(401).send('Invalid signature');
  }
  res.status(200).send('OK'); // acknowledge before doing any work

  const event = JSON.parse(req.body.toString());
  const PATHS = {
    patient: 'patients', appointment: 'appointments', clinician_profile: 'clinician-profiles',
    location: 'locations', appointment_template: 'appointment-templates',
    questionnaire_response: 'questionnaire-responses',
  };
  const path = PATHS[event.data?.object?.object];
  if (!path) return; // test.ping, or a resource you don't use

  const r = await fetch(`https://api.usejump.co.uk/v1/${path}/${event.data.object.id}`, {
    headers: { Authorization: `Bearer ${process.env.JUMP_API_KEY}` },
  });
  if (r.status === 404) return; // removed, or not readable with this key
  if (!r.ok) throw new Error(`Jump API ${r.status}`); // retry from your own queue
  const { data: record } = await r.json();
  await upsertLocalCopy(event.type, record);
});
```

### Full payloads (deprecated)

<Callout type="warning">
  **`legacy_full` payloads are deprecated. The removal date is to be announced.** Endpoints created before minimal payloads were introduced keep receiving the full record, in the shape described under [Payload Structure](#payload-structure), until they are switched. Move your integration to fetch on notify, then switch the endpoint.
</Callout>

An endpoint's `payload_version` is `minimal` or `legacy_full`, and is shown on [`GET /webhooks/{id}`](https://docs.usejump.co.uk/api-reference/webhooks) and in **Settings** > **Developer** > **Webhooks**. To switch, send `PATCH /webhooks/{id}` with `{"payload_version": "minimal"}`, or use **Switch to minimal payloads** on the webhook in Settings. The switch takes effect from the next event and is **one way**: an endpoint cannot be switched back to `legacy_full`, and a new endpoint cannot be created with it. Deliveries already queued keep the shape they were queued with.

## Event Types

### Patient Events

| Event              | Description                           |
| ------------------ | ------------------------------------- |
| `patient.created`  | A new patient record has been created |
| `patient.updated`  | Patient demographics have changed     |
| `patient.archived` | A patient has been archived           |

<Callout type="info">
  A minimal payload carries the patient's id and status only. Use `GET /patients/{id}` to fetch the record after receiving the notification. A deprecated `legacy_full` endpoint also receives core demographics.
</Callout>

### Appointment Events

| Event                     | Description                             |
| ------------------------- | --------------------------------------- |
| `appointment.created`     | A new appointment has been booked       |
| `appointment.updated`     | Appointment details have changed        |
| `appointment.cancelled`   | An appointment has been cancelled       |
| `appointment.rescheduled` | Appointment time or date changed        |
| `appointment.completed`   | Appointment status changed to completed |

### Questionnaire Response Events

| Event                            | Description                                 |
| -------------------------------- | ------------------------------------------- |
| `questionnaire_response.created` | A questionnaire response has been submitted |
| `questionnaire_response.updated` | A questionnaire response has been updated   |

<Callout type="info">
  Questionnaire response webhook payloads do not include the `responses` field (clinical data protection). Use `GET /questionnaire-responses/{id}` to fetch the full response after receiving the notification.
</Callout>

### Test Event

| Event       | Description                                                                                                        |
| ----------- | ------------------------------------------------------------------------------------------------------------------ |
| `test.ping` | Sent when you test an endpoint from Jump. It references no real record. See [Testing Webhooks](#testing-webhooks). |

## Payload Structure

<Callout type="warning">
  This section describes the deprecated &#x2A;*`legacy_full`** shape, still sent to endpoints created before minimal payloads were introduced. New endpoints receive the [minimal payload](#minimal-payloads-and-fetch-on-notify) instead: the same envelope, with `data.object` reduced to `id`, `object`, `status` and `updated_at`, and no `data.previous`.
</Callout>

A `legacy_full` payload has this structure:

```json
{
  "id": "evt_abc123",
  "type": "appointment.created",
  "created_at": "2025-01-15T10:30:00Z",
  "organization_id": "org_xyz789",
  "data": {
    "object": {
      "id": "apt_def456",
      "patient_id": "pat_ghi789",
      "clinician_profile_id": "cli_jkl012",
      "appointment_type_id": "type_mno345",
      "title": "Follow-up Consultation",
      "start_time": "2025-01-20T14:00:00+00:00",
      "end_time": "2025-01-20T14:30:00+00:00",
      "timezone": "Europe/London",
      "status": "confirmed",
      "location_id": "loc_pqr678",
      "is_remote": false,
      "attendee_name": "Sarah Johnson",
      "attendee_email": "sarah@example.com",
      "created_at": "2025-01-15T10:30:00Z",
      "updated_at": "2025-01-15T10:30:00Z",
      "is_untimed": false,
      "list_position": null,
      "patient_time_display": null,
      "arrival_time": null
    },
    "previous": null
  }
}
```

### Times

An appointment's `start_time` and `end_time` (in `data.object` and `data.previous`) are written in the practice's local time with its UTC offset, and `data.object.timezone` names the practice's time zone. In January that is `+00:00`; during British Summer Time the same 14:00 appointment is `2025-07-20T14:00:00+01:00`. Parse them as instants. Event and audit timestamps (`created_at`, `updated_at`) stay in UTC.

### Untimed bookings

Some practices run **untimed lists**, such as a call-back list or a theatre list. A booking on one holds a place on the list rather than a time. For these bookings `start_time` and `end_time` are the **list's window** (for example 10:00 to 14:00), not an appointment time. The patient is told the window or an arrival time, never a precise start, so your system should not show `start_time` as the time of the appointment.

Every appointment payload carries these four fields:

| Field                  | Type                            | Description                                                                                                                                                                                       |
| ---------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `is_untimed`           | boolean                         | `true` for a place on an untimed list. `false` for every timed appointment.                                                                                                                       |
| `list_position`        | integer or null                 | The booking's 1-based place on the list. It changes when the practice reorders the list, or a booking ahead of it leaves. `null` for a timed appointment, and for a cancelled untimed booking.    |
| `patient_time_display` | `"window"`, `"arrival"` or null | How the patient was told the time: `window` means the whole `start_time` to `end_time` range, `arrival` means `arrival_time`. `null` for a timed appointment.                                     |
| `arrival_time`         | string or null                  | The arrival time the patient was given, as `HH:MM` in the practice's local time on the day of the window. It can be earlier than `start_time`. Set only when `patient_time_display` is `arrival`. |

On a timed appointment the last three are always present as `null` rather than left out, so every appointment payload has the same shape. The `start_time` and `end_time` of a timed appointment are unchanged.

An untimed booking on an arrival list looks like this:

```json
{
  "id": "evt_abc124",
  "type": "appointment.created",
  "created_at": "2025-01-15T10:30:00Z",
  "organization_id": "org_xyz789",
  "data": {
    "object": {
      "id": "apt_def457",
      "title": "Theatre list",
      "start_time": "2025-01-20T10:00:00+00:00",
      "end_time": "2025-01-20T14:00:00+00:00",
      "timezone": "Europe/London",
      "status": "confirmed",
      "is_untimed": true,
      "list_position": 3,
      "patient_time_display": "arrival",
      "arrival_time": "09:45"
    },
    "previous": null
  }
}
```

(Other fields are left out of this example for brevity; the payload carries them all.) The same four fields are returned by the appointments API.

### Questionnaire Response Payload Example

```json
{
  "id": "evt_xyz789",
  "type": "questionnaire_response.created",
  "created_at": "2025-01-15T11:00:00Z",
  "organization_id": "org_xyz789",
  "data": {
    "object": {
      "id": "qr_abc123",
      "questionnaire_id": "qt_def456",
      "questionnaire_title": "New Patient Intake Form",
      "patient_id": "pat_ghi789",
      "appointment_id": null,
      "episode_id": "ep_jkl012",
      "submitted_at": "2025-01-15T11:00:00Z",
      "submitted_by_patient": true,
      "is_pre_booking": false,
      "created_at": "2025-01-15T11:00:00Z",
      "updated_at": "2025-01-15T11:00:00Z"
    },
    "previous": null
  }
}
```

<Callout type="info">
  The `responses` field (containing actual form answers) is intentionally excluded from webhook payloads for clinical data protection. Fetch the full response via the API after receiving the notification.
</Callout>

### Payload Fields

| Field             | Type   | Description                                                                                       |
| ----------------- | ------ | ------------------------------------------------------------------------------------------------- |
| `id`              | string | Unique identifier for this event                                                                  |
| `type`            | string | The event type (e.g., `appointment.created`)                                                      |
| `created_at`      | string | ISO 8601 timestamp when event occurred                                                            |
| `organization_id` | string | Your organization ID                                                                              |
| `data.object`     | object | Minimal: `id`, `object`, `status`, `updated_at`. `legacy_full`: the current state of the resource |
| `data.previous`   | object | `legacy_full` only: previous state (for update events only)                                       |

## Setting Up Webhooks

### 1. Create a Webhook Endpoint

1. Go to **Settings** > **Webhooks** in your Jump EHR dashboard
2. Click **Add Endpoint**
3. Enter your endpoint URL (must be HTTPS)
4. Select the events you want to receive
5. Click **Create**

<Callout type="warning">
  Your webhook secret is displayed only once when creating the endpoint. Copy and store it securely.
</Callout>

### 2. Configure Your Server

Your server must:

* Accept POST requests
* Respond with a 2xx status code within 30 seconds
* Verify the webhook signature (recommended)

### URL Requirements

* Must use HTTPS (HTTP not allowed in production)
* Cannot point to internal/private IP addresses (127.x, 10.x, 172.16-31.x, 192.168.x)
* Must be publicly accessible

## Security

### Signature Verification

Every webhook request includes a signature header for verification:

```
X-Webhook-Signature: t=1705312200,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd
```

The signature format is `t=<timestamp>,v1=<signature>` where:

* `t` is the Unix timestamp when the webhook was sent
* `v1` is the HMAC-SHA256 signature

### Verifying Signatures

To verify a webhook signature:

1. Extract the timestamp and signature from the header
2. Reject the request if the timestamp is more than 5 minutes from your clock. This stops a captured request being replayed later.
3. Construct the signed payload: `{timestamp}.{request_body}`, using the **raw** request body, before any JSON parsing
4. Compute HMAC-SHA256 using your webhook secret
5. Compare with the provided signature in constant time

Every delivery, including each retry, is signed with the time it was sent, so a 5-minute window never rejects a genuine retry.

#### Node.js Example

```javascript
const crypto = require('crypto');

const TOLERANCE_SECONDS = 5 * 60;

function verifyWebhookSignature(payload, header, secret) {
  if (typeof header !== 'string') return false;

  // Parse "t=…,v1=…" without assuming order or spacing.
  const parts = Object.fromEntries(
    header.split(',').map((part) => {
      const i = part.indexOf('=');
      return [part.slice(0, i).trim(), part.slice(i + 1).trim()];
    })
  );
  const timestamp = Number(parts.t);
  const provided = parts.v1;
  if (!Number.isFinite(timestamp) || !provided) return false;

  // Replay protection.
  if (Math.abs(Date.now() / 1000 - timestamp) > TOLERANCE_SECONDS) return false;

  const expected = crypto
    .createHmac('sha256', secret)
    .update(`${parts.t}.${payload}`)
    .digest('hex');

  // timingSafeEqual throws on buffers of different length, so check first:
  // a malformed header should be a clean 401, not an exception.
  const a = Buffer.from(provided, 'utf8');
  const b = Buffer.from(expected, 'utf8');
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

// Express.js example
app.post('/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
  const signature = req.headers['x-webhook-signature'];
  const payload = req.body.toString();

  if (!verifyWebhookSignature(payload, signature, process.env.WEBHOOK_SECRET)) {
    return res.status(401).send('Invalid signature');
  }

  const event = JSON.parse(payload);
  console.log('Received event:', event.type);

  // Process the event
  switch (event.type) {
    case 'appointment.created':
      handleAppointmentCreated(event.data.object);
      break;
    case 'patient.updated':
      handlePatientUpdated(event.data.object, event.data.previous);
      break;
  }

  res.status(200).send('OK');
});
```

#### Python Example

```python
import hmac
import hashlib
import time

TOLERANCE_SECONDS = 5 * 60

def verify_webhook_signature(payload: str, header: str | None, secret: str) -> bool:
    if not header:
        return False

    # Parse "t=…,v1=…" without assuming order or spacing.
    parts = {}
    for part in header.split(','):
        key, _, value = part.partition('=')
        parts[key.strip()] = value.strip()

    timestamp, provided = parts.get('t'), parts.get('v1')
    if not timestamp or not provided or not timestamp.isdigit():
        return False

    # Replay protection.
    if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
        return False

    expected = hmac.new(
        secret.encode(),
        f"{timestamp}.{payload}".encode(),
        hashlib.sha256
    ).hexdigest()

    return hmac.compare_digest(provided, expected)

# Flask example
@app.route('/webhooks', methods=['POST'])
def handle_webhook():
    signature = request.headers.get('X-Webhook-Signature')
    payload = request.get_data(as_text=True)

    if not verify_webhook_signature(payload, signature, WEBHOOK_SECRET):
        return 'Invalid signature', 401

    event = request.get_json()
    print(f"Received event: {event['type']}")

    # Process the event
    if event['type'] == 'appointment.created':
        handle_appointment_created(event['data']['object'])

    return 'OK', 200
```

### Additional Headers

Each webhook request includes these headers:

| Header                 | Description                            |
| ---------------------- | -------------------------------------- |
| `X-Webhook-Signature`  | HMAC-SHA256 signature for verification |
| `X-Webhook-Event-ID`   | Unique event ID for deduplication      |
| `X-Webhook-Event-Type` | Event type name                        |
| `User-Agent`           | `JumpEHR-Webhooks/1.0`                 |
| `Content-Type`         | `application/json`                     |

## Delivery & Retries

### Delivery Behavior

* Webhooks are delivered within seconds of the event occurring
* Each delivery attempt has a 30-second timeout
* Your endpoint must respond with a 2xx status code to confirm receipt

### Retry Schedule

If delivery fails, Jump EHR retries with exponential backoff:

| Attempt | Delay                   |
| ------- | ----------------------- |
| 1       | 1 minute                |
| 2       | 4 minutes               |
| 3       | 16 minutes              |
| 4       | 64 minutes (\~1 hour)   |
| 5       | 256 minutes (\~4 hours) |

After 5 failed attempts, the delivery is marked as failed and not retried.

### Success Criteria

A delivery is considered successful when your endpoint:

* Responds with HTTP status 200-299
* Responds within 30 seconds

<Callout type="info">
  Return a 2xx response quickly, then process the webhook asynchronously. This prevents timeouts for long-running operations.
</Callout>

## Best Practices

### 1. Respond Quickly

Acknowledge the webhook immediately and process asynchronously:

```javascript
app.post('/webhooks', (req, res) => {
  // Respond immediately
  res.status(200).send('OK');

  // Process asynchronously
  processWebhookAsync(req.body).catch(console.error);
});
```

### 2. Handle Duplicates

Use the `X-Webhook-Event-ID` header to detect and skip duplicate deliveries:

```javascript
const processedEvents = new Set();

function handleWebhook(event, eventId) {
  if (processedEvents.has(eventId)) {
    console.log('Duplicate event, skipping');
    return;
  }

  processedEvents.add(eventId);
  // Process event...
}
```

### 3. Verify Signatures

Always verify webhook signatures in production to ensure requests are from Jump EHR.

### 4. Log Webhook Events

Keep logs of received webhooks for debugging and auditing:

```javascript
function logWebhook(event, status) {
  console.log({
    timestamp: new Date().toISOString(),
    event_id: event.id,
    event_type: event.type,
    status: status
  });
}
```

## Testing Webhooks

### Test Endpoint

Use the **Test** button in the webhook settings to send a test event:

```json
{
  "id": "evt_test_123",
  "type": "test.ping",
  "created_at": "2025-01-15T10:30:00Z",
  "organization_id": "org_xyz789",
  "data": {
    "object": {
      "message": "This is a test webhook"
    },
    "previous": null
  }
}
```

### Local Development

For local development, use a tunneling service like ngrok to expose your local server:

```bash
ngrok http 3000
```

Then use the ngrok URL as your webhook endpoint during development.

## Viewing Delivery History

View webhook delivery history in **Settings** > **Webhooks** > select your endpoint > **Delivery Log**.

The log shows:

* Event type and ID
* Delivery status (delivered, failed, pending)
* Response status code
* Number of attempts
* Timestamps

## Next Steps

* Learn about [Authentication](https://docs.usejump.co.uk/getting-started/authentication) for API access
* Explore the [API Reference](https://docs.usejump.co.uk/api-reference) for available resources
* View [Patients API](https://docs.usejump.co.uk/api-reference/patients) for patient event details
