Skip to main content

Webhooks

Webhooks let MedBackend notify your own service about FHIR operations, so you can trigger external workflows, mirror data, or keep an audit trail outside the platform.

Webhooks fire at two points in the request lifecycle:

  • Pre-request hook: dispatched after RBAC validation passes, before the request reaches the FHIR server.
  • Post-response hook: dispatched after the FHIR server responds and the operation has been recorded in the audit trail.
Webhooks are notifications, not gates

Delivery is fire-and-forget. MedBackend queues each webhook on a background thread pool and continues processing the request immediately; it never waits for your endpoint, and it does not act on your response body — only the HTTP status code changes anything, and only by deciding whether to retry.

A pre-request hook therefore cannot block, delay or alter a request, and a post-response hook cannot modify what the client receives. Access decisions belong in validation rules; webhooks tell you what happened. Because dispatch is asynchronous, your endpoint may also be called after the FHIR write has already landed, despite the hook being named "pre-request".

A request refused by the RBAC gate produces no webhook at all — the denial is raised before either hook is reached. Check the audit trail for those.

A request can still be refused after the pre-request hook has been dispatched, though: row-level checks run inside the resolver and can refuse there. So a pre-request webhook means the request was authorized to proceed, not that it succeeded. Only the post-response hook tells you the resolver returned without error — and even that does not guarantee a resource came back, as the post-response payload explains.

Webhook Configuration​

Webhooks are configured per resource and operation within your validation rules. Add pre_request_hook or post_response_hook to any validation rule:

{
"client_role": "Patient",
"entity_name": "Observation",
"operation": "create",
"validator": "patient_compartment",
"pre_request_hook": {
"url": "https://your-service.com/webhooks/observation-submitted",
"enabled": true
}
}

You can configure both hooks on the same rule:

{
"client_role": "Practitioner",
"entity_name": "Observation",
"operation": "create",
"validator": "legitimate_interest",
"pre_request_hook": {
"url": "https://your-service.com/webhooks/observation-submitted",
"enabled": true
},
"post_response_hook": {
"url": "https://your-service.com/webhooks/observation-created",
"enabled": true
}
}

Only the first matching validation rule supplies the hooks for a request. If several rules match the same client_role / entity_name / operation triple, all of them still run for the access decision, but hooks are read from the first match only.

MedBackend's own platform rules are merged ahead of your project's, so a hook placed on a triple a platform rule already covers is never read. That affects Me reads and UploadFile reads and creates for every role, plus Communication for Device. Attach hooks to your own resource rules rather than to those.

A hook is only as reachable as the rule it sits on

A hook attached to a rule that denies every request never fires, and nothing reports this — the request simply fails and no delivery is logged. Patient + Patient + create under patient_compartment is the standard example of such a rule: a Patient resource carries none of the subject, patient or performer elements the compartment write check requires, so the rule parses, publishes, looks correct in the editor, and denies. Confirm the rule grants before you debug the webhook. See What a compartment validator asks of a write.

Full Configuration Example​

Here's a complete RBAC configuration with webhooks:

{
"rbac": {
"default_access": "Forbidden",
"validators": {
"patient_compartment": { "enabled": true },
"legitimate_interest": { "enabled": true }
},
"validation_rules": [
{
"client_role": "Patient",
"entity_name": "Observation",
"operation": "read",
"validator": "patient_compartment"
},
{
"client_role": "Patient",
"entity_name": "Observation",
"operation": "create",
"validator": "patient_compartment",
"pre_request_hook": {
"url": "https://your-service.com/webhooks/observation-submitted",
"enabled": true
}
},
{
"client_role": "Practitioner",
"entity_name": "Observation",
"operation": "create",
"validator": "legitimate_interest",
"post_response_hook": {
"url": "https://your-service.com/webhooks/observation-created",
"enabled": true
}
}
],
"webhook_settings": {
"enabled": true,
"timeout_ms": 5000,
"retry_attempts": 3,
"retry_backoff_ms": 1000,
"hmac_secret": "env:WEBHOOK_HMAC_SECRET",
"allowed_url_schemes": ["https"],
"user_agent": "MedBackend-Webhook/1.0"
}
}
}

Delivery​

Each webhook is delivered as an HTTP POST with a JSON body and these headers:

HeaderValue
Content-Typeapplication/json
X-Webhook-Request-IdCorrelation id, identical to request_id in the body and shared by the pre-request and post-response hooks of the same operation
X-Webhook-TimestampISO 8601 UTC timestamp generated when the delivery is queued. Headers are built once per dispatch, so every retry repeats that same value rather than carrying a fresh one, and it is not covered by X-Webhook-Signature, which signs the payload only. A receiver that enforces a replay window on this header will reject legitimate retries.
X-Webhook-Hook-Typepre_request or post_response
User-AgentValue of the user_agent setting, MedBackend-Webhook/1.0 by default
X-Webhook-SignatureHMAC-SHA256 signature — present only when an HMAC secret is configured

Your endpoint should acknowledge with any 2xx status. Nothing you put in the body changes what MedBackend does — only the status code does.

  • 2xx — delivery succeeded, no retry.
  • 4xx — treated as a permanent rejection, no retry. The first 500 characters of your response body are written to MedBackend's server log, so do not return anything sensitive in an error response.
  • Anything else — timeouts, connection errors, 5xx, and any other status that is neither 2xx nor 4xx — retried up to retry_attempts times with exponential backoff.

Returning an error status does not stop, reverse or flag the FHIR operation. It only affects whether MedBackend retries the delivery.

Webhook Payload​

Pre-Request Hook Payload​

{
"hook_type": "pre_request",
"timestamp": "2026-03-15T10:30:00.482913+00:00",
"request_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"client_request": {
"operation": "create",
"entity_name": "Observation",
"entity_id": null,
"parameters": {
"resource": {
"status": "final",
"code": { "coding": [{ "system": "http://loinc.org", "code": "29463-7" }] },
"subject": { "reference": "Patient/patient-123" },
"valueQuantity": { "value": 72.5, "unit": "kg" }
}
},
"resource_data": {
"status": "final",
"code": { "coding": [{ "system": "http://loinc.org", "code": "29463-7" }] },
"subject": { "reference": "Patient/patient-123" },
"valueQuantity": { "value": 72.5, "unit": "kg" }
}
},
"validated_request": {
"operation": "create",
"entity_name": "Observation",
"entity_id": null,
"compartment_name": "Patient",
"compartment_id": "patient-123",
"parameters": {
"resource": {
"status": "final",
"code": { "coding": [{ "system": "http://loinc.org", "code": "29463-7" }] },
"subject": { "reference": "Patient/patient-123" },
"valueQuantity": { "value": 72.5, "unit": "kg" }
}
}
},
"client_role": "Patient",
"client_entity_id": "patient-123",
"rule_matched": {
"client_role": "Patient",
"entity_name": "Observation",
"operation": "create",
"validator": "patient_compartment"
}
}
FieldDescription
hook_typepre_request or post_response. There is no separate event-name field — combine client_request.entity_name and client_request.operation if you need one.
timestampISO 8601 UTC timestamp, generated when the payload is built
request_idUUID correlating the two hooks of one operation
client_request.operationread, search, create, update or delete
client_request.entity_nameFHIR resource type
client_request.entity_idTarget resource id, null on create
client_request.parametersThe GraphQL arguments for the operation, verbatim. For a write this includes resource; for a read or search it holds the query arguments.
client_request.resource_dataThe submitted resource body, with null fields stripped. Empty ({}) for operations that carry no body.
validated_requestThe same operation as MedBackend resolved it, plus compartment_name / compartment_id — the caller's role and entity id, that is, the compartment the request was scoped to
client_roleCaller's role, e.g. Patient, Practitioner, Device
client_entity_idCaller's FHIR entity id
rule_matchedThe matched validation rule, reduced to client_role, entity_name, operation and validator. Hook URLs and any other rule keys are stripped before sending.

There is no project_id and no context wrapper on this payload — client_role and client_entity_id are top-level fields. The project is implied by the endpoint you registered the webhook against.

That applies to the pre-request and post-response hooks only. The test webhook is a different payload and does carry a project_id — see below.

Post-Response Hook Payload​

The post-response payload is the pre-request payload with hook_type set to post_response, a later timestamp, and one additional top-level key:

{
"backend_response": {
"status": "success",
"resource": {
"id": "obs-789",
"resourceType": "Observation",
"status": "final",
"subject": { "reference": "Patient/patient-123" }
}
}
}

backend_response.status is a string, not an HTTP status code, and the resource lives under resource — not body.

Two things about resource will bite a receiver that trusts the example above.

It can be null. A call that raises aborts the request before this hook is dispatched, so a post-response webhook means the resolver returned without error — it does not guarantee a resource. Row-level filters refuse quietly rather than raising, and that case arrives as {"status": "success", "resource": null}. Check for null before dereferencing.

It is the full GraphQL type, not the fields you sent. The example above is truncated. What ships is every field the resource type declares — 58 keys for Observation — with null for each one not set, alongside _-prefixed primitive-extension keys (_status, _effectiveDateTime, _valueString, and so on). Read the fields you need by name; never iterate the object or size a buffer against the example.

Test Webhook Payload​

The "send test webhook" action in the dashboard delivers to your configured URL, but it does not send either payload documented above. It is a different shape, and a receiver that switches on hook_type will fall through unless it handles test:

{
"hook_type": "test",
"timestamp": "2026-08-29T09:14:00Z",
"request_id": "test-1756458840",
"message": "This is a test webhook from MedBackend",
"project_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
}
FieldDescription
hook_typeAlways test
request_idtest-<unix seconds>, not a UUID — unlike the real hooks
messageFixed human-readable string
project_idYour project_uid, despite the field name. Same value as the X-Project-ID header

Testing a single event subscription rather than the endpoint sends a variant of this with event_type, webhook_name and internal webhook_id / event_id values added.

A test delivery proves your endpoint is reachable and your signature check works. It does not exercise the real payload, so a receiver that passes a test can still fail on the first live hook. Validate against the pre-request example above before going live.

Webhook Settings​

Configure global webhook behavior in the webhook_settings section of settings.json:

SettingDefaultDescription
enabledtrueMaster switch for all webhooks in the project
timeout_ms5000Per-attempt HTTP timeout in milliseconds (100–30000)
retry_attempts3Retries after the first attempt, for any response that is neither 2xx nor 4xx and for timeouts and connection errors (0–10)
retry_backoff_ms1000Base backoff in milliseconds; the wait doubles on each successive retry (100–60000)
hmac_secret""Signing secret for X-Webhook-Signature, set by the platform. Deliveries are unsigned when empty.
allowed_url_schemes["https"]Permitted URL schemes for hook endpoints
user_agent"MedBackend-Webhook/1.0"User-Agent header sent with every delivery

The ranges above are the bounds MedBackend enforces when it publishes a project's settings.

max_payload_size_bytes is accepted by the configuration loader but is not currently enforced; do not rely on it to cap delivery size.

A rejected URL fails silently for the caller

A hook whose URL fails validation is skipped, and no error reaches the client. A URL is rejected when its scheme is not in allowed_url_schemes, when it has no network location at all, or — while https is among the allowed schemes — when it points at localhost, 127.0.0.1, ::1, or a literal private or link-local IP address.

The private-address check inspects the URL, not DNS: a hostname that resolves to a private address is not rejected, because no lookup happens. https://internal.corp/hook passes.

Security​

When an HMAC secret is configured, MedBackend signs every webhook payload. The signature is sent in the X-Webhook-Signature header:

X-Webhook-Signature: sha256=<hex-encoded-signature>

Verifying Signatures​

The signature is computed over the payload re-serialized with sorted keys, not over the bytes on the wire. Verifying against the raw request body will fail — parse the body and re-serialize it the same way:

import hmac
import hashlib
import json

def verify_signature(payload: bytes, signature: str, secret: str) -> bool:
# Re-serialize with sorted keys (as MedBackend does before signing)
payload_dict = json.loads(payload)
canonical = json.dumps(payload_dict, sort_keys=True).encode('utf-8')

expected = hmac.new(secret.encode(), canonical, hashlib.sha256).hexdigest()
actual = signature.replace("sha256=", "")

return hmac.compare_digest(expected, actual)

If no secret is configured the header is absent entirely. Reject unsigned deliveries in production rather than treating a missing header as valid.

Example: Pre-Request Notification​

from flask import Flask, request

app = Flask(__name__)

@app.route('/webhooks/observation-submitted', methods=['POST'])
def observation_submitted():
event = request.json
observation = event['client_request']['resource_data']

metrics.increment('observation.submitted', tags={
'role': event['client_role'],
'code': observation.get('code', {}).get('coding', [{}])[0].get('code'),
})

# Nothing you return is acted on. A 2xx acknowledges; a 5xx has MedBackend
# retry the delivery. Neither affects the FHIR operation, and a 4xx body
# ends up in MedBackend's server log, so keep error responses empty.
return '', 204

Example: Post-Response Audit Logging​

@app.route('/webhooks/observation-created', methods=['POST'])
def log_observation():
event = request.json
resource = event['backend_response'].get('resource')

# A row-level filter can suppress the row without raising, which arrives
# here as a successful status with a null resource.
if resource is None:
return '', 204

audit_log.create({
'event': 'observation_created',
'resource_id': resource['id'],
'actor': event['client_entity_id'],
'actor_role': event['client_role'],
'request_id': event['request_id'],
'timestamp': event['timestamp'],
})

return '', 204