Integration

Subscriptions and Outbound Delivery

Subscribe to record changes, configure webhook or broker delivery, and retrieve approved records and query results.

How notifications work

AMCDR can notify authorized partners when clinical records, workflows, registry entries, integrations or reports change. Configure a webhook or broker subscription to choose which events a partner receives.

When a notification arrives, the receiving system verifies it, acknowledges receipt promptly and requests the data it is allowed to access. It can use FHIR, shared health record, openEHR composition or saved-query APIs to retrieve that data.

This pattern keeps patient access policy, protected-record checks, consent and release controls, audit logging, and payload shaping inside AMCDR while still allowing partner systems to react quickly to clinical events.

Delivery Model

AMCDR sends outbound notifications to configured partners. Inbound clinical writes use governed ingest, FHIR, form, composition, or workflow APIs, not the outbound webhook endpoint.

Access Boundary

Subscription administration and delivery processing are authenticated backend operations. Local deployments use http://127.0.0.1:8009/triggers/.... Reverse-proxy deployments may expose the same routes under /backend/triggers/....

Receiver security

Production receivers must use HTTPS, signature verification, scoped pull credentials, idempotent processing, and minimum-necessary payloads. Patient data should be pulled through governed APIs unless a formal integration contract allows payload delivery.

Delivery options

AMCDR uses one subscription model with two delivery modes: webhook for HTTP callbacks and broker for queue or stream delivery. The same event contract can be delivered through either mode depending on the subscription configuration and partner operating model.

SurfaceWhat It SendsHow To SubscribeTypical Use
Lifecycle subscriptionsCore clinical, workflow, artifact, composition, template, mapping, saved-query, patient, encounter, medication, diagnostic, referral, consent, and policy events persisted as lifecycle events.event_source=lifecyclePartner notification after canonical AMCDR changes.
Integration subscriptionsMPI, FHIR-facing MPI, terminology, connector probe/action, patient portal identity, SHR policy, and saved-query notification events emitted by integration services.event_source=integrationIntegration monitoring, partner connector audit, external identity/terminology workflows.
Patient portal subscriptionsPortal reminders, submitted documents, and portal-specific patient communication events.event_source=patient_portalNotify portal processors or external patient communication systems.
Cohort stream subscriptionsPatient enters, exits, or re-enters a cohort after cohort evaluation.event_source=cohortRegistry alerts, dashboards, public health monitoring, programme follow-up.
Vital event reporting subscriptionsBirth and death reporting payloads when vital-event transport is enabled.Default event_source=vital_reporting, unless reporting config changes it.Civil registration, public health, and humanitarian reporting signals.
Grouped delete batch subscriptionsScheduled grouped deletion notifications such as composition.deleted.batch and lifecycle.deleted.batch.definition.batch_delivery.enabled=trueDownstream cache cleanup, registry sync, delayed delete processing.
Lifecycle activity report subscriptionsScheduled totals, standard breakdowns and paginated item details for created, changed, merged, restored or deleted resources.definition.activity_batch.enabled=trueOperational reconciliation, audit reporting and downstream change windows.
Saved-query snapshot subscriptionsNotifications after an approved AQL schedule persists a ready or changed result snapshot.event_source=integration, target_record_type=saved_query, exact target_record_idGoverned clinical analytics and scheduled partner extracts.

Event Families

Subscriptions can match one exact event_type, one event_family prefix, one target_record_type, one exact target_record_id, or controlled identifier/type lists in the definition. Tenant, organisation, environment and facility scope are enforced during immediate delivery and replay. Use GET /triggers/events to review individual events and GET /triggers/events/activity for totals and grouped results for a time range.

FamilyExamples Present In The PlatformTarget Examples
compositioncomposition.created, composition.updated, composition.version.superseded, composition.logical_deleted, composition.restored, composition.expired, composition.revoked, composition.hard_deletedcomposition
templatetemplate.archived, template.restored, template.retired, template.deleted, template.hard_deleted, template.version.deleted, template.fhir_binding.deletedtemplate
formform.deleted, form.hard_deleted, form.version.deleted, form.version.restored, form.restoredform
mappingmapping.deleted, mapping.hard_deleted, mapping.restored, mapping.binding.deleted, mapping.binding.restoredmapping
workflowworkflow.instance.created, workflow.task.created, workflow.task.opened, workflow.task.assigned, workflow.task.completed, workflow.task.failed, workflow.task.requeuedworkflow_instance, workflow_task
visit and encountervisit.created, encounter.created, encounter.post_death_override, and status-specific encounter.* events.patient_visit, encounter
emergencyemergency.visit.created, emergency.identity.partial, emergency.registration.completed, emergency.identity.review_requested, emergency.transfer.completed, emergency.discharge.completedpatient_visit
medication and diagnosticmedication.order.created, medication.dispense.*, medication.administration.*, diagnostic.order.*.created, diagnostic.specimen.created, diagnostic.report.*.ingestedmedication_order, diagnostic_order
integrationintegration.mpi.pdq.search, integration.mpi.pix.query, integration.mpi.fhir.patient.create, integration.terminology.expand, integration.connector.probe, integration.connector.action.{action_key}integration_request, service-specific targets
cohortpatient_enters_cohort, patient_exits_cohort, patient_reenteredcohort_definition
vital_reportingcivil_registration.birth.ready, public_health.birth.ready, civil_registration.death.ready, public_health.death.ready, humanitarian.death.readybirth_event, death_event
Recommended outbound integration pattern
Clinical writeComposition, patient, encounter, document
->
Lifecycle eventStored and auditable
->
Subscription matchScope, type, target
->
Delivery queueWebhook or broker
->
Governed partner pullFHIR, SHR, AQL, export

Notification And Retrieval Patterns

PatternUse WhenAMCDR Surface
Webhook notificationA partner needs to be alerted when a composition, patient, encounter, document, or lifecycle event changes./triggers/subscriptions, /triggers/deliveries/process
Broker notificationInternal platforms, HIE pipelines, and high-volume partners must consume a stream or queue instead of direct HTTP callbacks where throughput or reliability requirements exceed webhook capacity.delivery_mode=broker, /triggers/deliveries/process-broker
FHIR pull after eventThe partner needs a standards payload such as Composition, Patient/$everything, or a mapped Bundle./fhir/Composition, /fhir/Patient/{patient_id}/$everything, /fhir/project
Shared health record pullThe partner needs a patient-wide or population-level summary assembled from many templates, encounters, documents, and relationships./records/patient/{patient_id}/summary/current, /records/patients/summary, saved-query projections
Saved-query extractThe partner needs repeatable reporting, CSV, XML, or governed AQL output./integration/outbound/saved-queries/{key}/execute, .csv, .xml

Subscription And Delivery APIs

GET  /triggers/events
GET  /triggers/events/activity
GET  /triggers/events/deleted-compositions
GET  /triggers/definitions
POST /triggers/definitions
GET  /triggers/subscriptions
POST /triggers/subscriptions
GET  /triggers/deliveries
GET  /triggers/broker-deliveries
POST /triggers/deliveries/process
POST /triggers/deliveries/process-broker
POST /triggers/deliveries/process-delete-batches
POST /triggers/deliveries/process-lifecycle-delete-batches
POST /triggers/deliveries/process-activity-batches
POST /triggers/deliveries/{delivery_id}/retry
POST /triggers/broker-deliveries/{delivery_id}/retry

POST /subscriptions
GET  /subscriptions/{subscription_id}
POST /subscriptions/{subscription_id}/replay

The /subscriptions route is a compact subscription endpoint. The /triggers/* routes expose the broader operational console for definitions, events, subscriptions, deliveries, retries, replay, and worker processing.

If nginx exposes the backend under /backend, call the same routes with that prefix, for example /backend/triggers/subscriptions. If calling the backend container or development port directly, use the route without the nginx prefix.

Example environment

export AMCDR_BASE_URL="https://amcdr.example.org/backend"
export ACCESS_TOKEN="<platform-admin-or-integration-operator-token>"

When calling the backend directly, use its configured origin, for example http://127.0.0.1:8009. Every administration, processing, retry, replay and result-retrieval request requires an authenticated credential with the appropriate scope. A webhook receiver uses a separately issued, least-privilege credential when it pulls governed clinical data.

Webhook Quick Start

This example creates a signed, immediate webhook for new and updated compositions. Replace the sample endpoint and identifiers, and keep signing secrets in deployment secret management.

1. Confirm the event contract

curl "${AMCDR_BASE_URL}/triggers/events?target_record_type=composition&limit=10" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Accept: application/json"

2. Create the subscription

curl --request POST "${AMCDR_BASE_URL}/triggers/subscriptions" \
  --header "Authorization: Bearer ${ACCESS_TOKEN}" \
  --header "Content-Type: application/json" \
  --data '{
    "key": "partner-composition-changes",
    "name": "Partner composition changes",
    "event_source": "lifecycle",
    "target_record_type": "composition",
    "delivery_mode": "webhook",
    "endpoint_url": "https://partner.example.org/hooks/amcdr",
    "signing_secret": "replace-with-secret-from-vault",
    "retry_max_attempts": 5,
    "retry_backoff_seconds": 120,
    "active": true,
    "definition": {
      "event_types": ["composition.created", "composition.updated"],
      "headers": {"X-Integration-Name": "partner-composition-feed"}
    }
  }'

A successful request returns HTTP 201:

{
  "id": "0eddfeb8-df3c-4400-808b-3610dd921b7f",
  "key": "partner-composition-changes",
  "name": "Partner composition changes"
}

3. Receive and acknowledge the delivery

POST /hooks/amcdr HTTP/1.1
Content-Type: application/json
X-AmCDR-Signature: 8b5030e15f16f379...
X-Integration-Name: partner-composition-feed

{
  "schema_version": "1.0",
  "event_id": "66f69ad8-a43e-4a6c-ac05-4448d9145f68",
  "event_source": "lifecycle",
  "event_action": "created",
  "event_type": "composition.created",
  "occurred_at": "2026-07-21T09:30:00+00:00",
  "target_record_type": "composition",
  "target_record_id": "505ba72c-cad7-4b51-a4d3-e6a035483553",
  "subscription_key": "partner-composition-changes",
  "payload": {
    "template_key": "vital-signs",
    "version_number": 1,
    "patient_id": "95bfa2d2-98cb-45e9-a119-31f5e6ed9440",
    "ehr_id": "85ad2cbe-2604-4c50-94a7-b366c4a5ef05"
  }
}

Verify the signature, persist event_id as the idempotency key, place downstream work on the receiver's queue, and return 200, 202, or another 2xx status promptly. A non-2xx response is retried according to the subscription policy.

4. Verify the HMAC-SHA256 signature

AMCDR signs the compact, key-sorted JSON envelope. Parse the body and reproduce that canonical representation before comparison.

import hashlib
import hmac
import json

def verify_amcdr_webhook(raw_body: bytes, received_signature: str, secret: str) -> dict:
    payload = json.loads(raw_body)
    canonical = json.dumps(
        payload,
        sort_keys=True,
        separators=(",", ":"),
    ).encode("utf-8")
    expected = hmac.new(
        secret.encode("utf-8"),
        canonical,
        hashlib.sha256,
    ).hexdigest()
    if not hmac.compare_digest(expected, received_signature or ""):
        raise PermissionError("Invalid AMCDR webhook signature")
    return payload

5. Inspect processing status

curl "${AMCDR_BASE_URL}/triggers/deliveries?limit=50" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}"

curl --request POST "${AMCDR_BASE_URL}/triggers/deliveries/process" \
  --header "Authorization: Bearer ${ACCESS_TOKEN}" \
  --header "Content-Type: application/json" \
  --data '{"limit":20}'

Composition Lifecycle Notification

This subscription alerts a partner when AMCDR records a composition lifecycle event. The receiver treats the delivery as notification context, verifies the signature, acknowledges receipt, and retrieves the authorized payload through FHIR, SHR, openEHR-facing, or saved-query APIs.

POST /triggers/subscriptions
Authorization: Bearer <admin-or-integration-token>
Content-Type: application/json

{
  "key": "partner-fhir-compositions",
  "name": "Partner FHIR Composition Feed",
  "event_source": "lifecycle",
  "event_family": "composition",
  "event_type": "composition.created",
  "target_record_type": "composition",
  "delivery_mode": "webhook",
  "endpoint_url": "https://partner.example.org/amcdr/events",
  "signing_secret": "<secret-provisioned-outside-git>",
  "retry_max_attempts": 5,
  "retry_backoff_seconds": 120,
  "scope_type": "organisation",
  "definition": {
    "content_mode": "notification",
    "recommended_pull": [
      "GET /fhir/Composition",
      "GET /fhir/Patient/{patient_id}/$everything",
      "POST /fhir/project"
    ]
  }
}

Deleted Composition Webhook

Subscribe to both logical and hard deletion when a downstream index, cache, registry, or document store must suppress removed clinical records.

curl --request POST "${AMCDR_BASE_URL}/triggers/subscriptions" \
  --header "Authorization: Bearer ${ACCESS_TOKEN}" \
  --header "Content-Type: application/json" \
  --data '{
    "key": "partner-composition-deletions",
    "name": "Partner composition deletions",
    "event_source": "lifecycle",
    "target_record_type": "composition",
    "delivery_mode": "webhook",
    "endpoint_url": "https://partner.example.org/hooks/amcdr-deletions",
    "signing_secret": "replace-with-secret-from-vault",
    "definition": {
      "event_types": [
        "composition.logical_deleted",
        "composition.hard_deleted"
      ]
    }
  }'

Example logical-deletion delivery:

{
  "schema_version": "1.0",
  "event_id": "3c7a3df5-e360-408c-ae8a-0d32fb1d52ca",
  "event_source": "lifecycle",
  "event_action": "deleted",
  "event_type": "composition.logical_deleted",
  "occurred_at": "2026-07-21T11:45:00+00:00",
  "target_record_type": "composition",
  "target_record_id": "505ba72c-cad7-4b51-a4d3-e6a035483553",
  "subscription_key": "partner-composition-deletions",
  "payload": {
    "deletion_mode": "logical",
    "patient_id": "95bfa2d2-98cb-45e9-a119-31f5e6ed9440",
    "ehr_id": "85ad2cbe-2604-4c50-94a7-b366c4a5ef05",
    "reason_code": "entered-in-error"
  }
}

The webhook is an immediate notification. For reconciliation with tombstones and time bounds, use GET /triggers/events/deleted-compositions or the generic activity report.

Notification Envelope

Webhook bodies use a compact event envelope. The envelope carries routing identifiers and a minimal context snapshot. It should not be treated as the full clinical payload unless the subscription contract explicitly states that patient payload delivery is allowed.

{
  "schema_version": "1.0",
  "event_id": "66f69ad8-a43e-4a6c-ac05-4448d9145f68",
  "event_source": "lifecycle",
  "event_action": "created",
  "event_type": "composition.created",
  "occurred_at": "2026-07-21T09:30:00+00:00",
  "target_record_type": "composition",
  "target_record_id": "505ba72c-cad7-4b51-a4d3-e6a035483553",
  "subscription_key": "partner-fhir-compositions",
  "payload": {
    "template_key": "vital-signs",
    "version_number": 1,
    "patient_id": "95bfa2d2-98cb-45e9-a119-31f5e6ed9440"
  }
}
FieldMeaning
schema_versionVersion of the webhook envelope contract. Consumers should reject unsupported major versions deliberately.
event_idStable lifecycle-event UUID. Use this as the primary idempotency key.
event_sourceSource family used for matching, such as lifecycle, integration, cohort, patient_portal, or vital_reporting.
event_actionNormalized verb such as created, updated, deleted, merged, or restored.
event_typeExact event name, such as composition.created or civil_registration.birth.ready.
occurred_atISO 8601 time at which AMCDR persisted the event.
target_record_typeObject class affected by the event.
target_record_idUUID of the affected record when available.
subscription_keyStable key of the subscription that produced the delivery.
payloadEvent-specific context snapshot. Consumers must treat this as notification context and pull governed payloads separately.

Receiver Requirements

  1. Expose an HTTPS endpoint that accepts POST with JSON.
  2. Verify the HMAC signature when signing_secret is configured.
  3. Use event_id as the primary idempotency key. Batch deliveries use their cursor and item event identifiers.
  4. Return a 2xx response promptly. Long downstream work must run in the receiver's own queue.
  5. Use scoped AMCDR credentials to pull the FHIR, SHR, openEHR-facing, or saved-query payload that the receiver is authorized to see.

HIE Broker Stream

Use broker delivery when a national HIE, reporting layer, or integration engine requires queue or stream semantics. The endpoint_url, stream_name, or destination identifies the broker destination according to the configured backend.

POST /triggers/subscriptions
Authorization: Bearer <admin-or-integration-token>
Content-Type: application/json

{
  "key": "hie-composition-stream",
  "name": "HIE Composition Stream",
  "event_source": "lifecycle",
  "event_family": "composition",
  "target_record_type": "composition",
  "delivery_mode": "broker",
  "endpoint_url": "amcdr.fhir.compositions",
  "definition": {
    "broker_backend": "redis_stream",
    "stream_name": "amcdr.fhir.compositions",
    "content_mode": "notification"
  }
}

Partner Retrieval After Notification

  1. AMCDR creates or updates a patient, encounter, composition, document, or mapped resource.
  2. AMCDR stores a lifecycle event with the target record type and identifiers.
  3. The subscription creates a webhook or broker delivery.
  4. The partner receives the delivery and verifies X-AmCDR-Signature when a signing secret is configured.
  5. The partner calls the appropriate AMCDR API using scoped credentials issued for that integration contract.
# Read mapped FHIR Composition resources
GET /fhir/Composition
Authorization: Bearer <partner-token>
Accept: application/fhir+json

# Read a patient-wide FHIR bundle
GET /fhir/Patient/{patient_id}/$everything
Authorization: Bearer <partner-token>
Accept: application/fhir+json

# Project canonical AMCDR records into a configured FHIR output
POST /fhir/project
Authorization: Bearer <partner-token>
Content-Type: application/json

# Read a governed patient-level shared health record
GET /records/patient/{patient_id}/summary/current?format=fhir
Authorization: Bearer <partner-token>

# Read a governed population SHR or IPS index
GET /records/patients/summary?profile=ips&include=index&date_from=2026-01-01&date_to=2026-06-30&format=fhir
Authorization: Bearer <partner-token>

Lifecycle Activity Report And Batch Webhook

Use the activity report when the question is “what changed and how many records changed between these times?” The report counts recorded changes; use AQL to query clinical content.

curl "${AMCDR_BASE_URL}/triggers/events/activity?since=2026-07-20T00:00:00Z&until=2026-07-21T00:00:00Z&action=created&action=deleted&target_record_type=composition&target_record_type=ehr&group_by=event_action&group_by=target_record_type&limit=100&offset=0" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Accept: application/json"

Abridged response: the complete response also returns the applied filters, requested group_by fields, counts by event type and source, and the full event and tombstone fields documented in the API schema.

{
  "time_range": {
    "since": "2026-07-20T00:00:00Z",
    "until": "2026-07-21T00:00:00Z"
  },
  "total": 27,
  "counts": {
    "by_action": [
      {"value": "created", "count": 24},
      {"value": "deleted", "count": 3}
    ],
    "by_resource_type": [
      {"value": "composition", "count": 26},
      {"value": "ehr", "count": 1}
    ]
  },
  "groups": [
    {
      "values": {
        "event_action": "deleted",
        "target_record_type": "composition"
      },
      "count": 2
    }
  ],
  "pagination": {
    "limit": 100,
    "offset": 0,
    "returned": 27,
    "next_offset": null
  },
  "items": [
    {
      "id": "3c7a3df5-e360-408c-ae8a-0d32fb1d52ca",
      "event_source": "lifecycle",
      "event_action": "deleted",
      "event_type": "composition.logical_deleted",
      "target_record_type": "composition",
      "target_record_id": "505ba72c-cad7-4b51-a4d3-e6a035483553",
      "patient_id": "95bfa2d2-98cb-45e9-a119-31f5e6ed9440",
      "ehr_id": "85ad2cbe-2604-4c50-94a7-b366c4a5ef05",
      "created_at": "2026-07-20T14:25:00+00:00",
      "tombstone": {
        "artifact_type": "composition",
        "deletion_mode": "logical"
      }
    }
  ]
}

For count-only reporting set include_items=false. Filters include event source, action, exact event type, resource type/UUID, patient, EHR, actor, reason and time range.

Schedule the report as a signed webhook

curl --request POST "${AMCDR_BASE_URL}/triggers/subscriptions" \
  --header "Authorization: Bearer ${ACCESS_TOKEN}" \
  --header "Content-Type: application/json" \
  --data '{
    "key": "daily-lifecycle-report",
    "name": "Daily lifecycle report",
    "event_source": "lifecycle",
    "delivery_mode": "webhook",
    "endpoint_url": "https://partner.example.org/hooks/amcdr-activity",
    "signing_secret": "replace-with-secret-from-vault",
    "definition": {
      "activity_batch": {
        "enabled": true,
        "interval_minutes": 1440,
        "max_events_per_batch": 500,
        "actions": ["created", "updated", "deleted", "merged"],
        "target_record_types": ["composition", "template", "ehr", "patient"],
        "include_tombstones": true
      }
    }
  }'

The delivered event type is lifecycle.activity.batch. Its payload includes batch_kind, generated_at, schedule and filter metadata, total, breakdowns, cursor_start, cursor_end, cursor_event_id, and complete item rows. The cursor advances only after successful delivery.

curl --request POST "${AMCDR_BASE_URL}/triggers/deliveries/process-activity-batches" \
  --header "Authorization: Bearer ${ACCESS_TOKEN}" \
  --header "Content-Type: application/json" \
  --data '{"limit":20}'

Saved Query And Extract Delivery

For recurring reports, national indicators, hospital extracts, and partner datasets, define a saved query and expose the approved result. Saved queries are preferred over ad hoc partner AQL because AMCDR versions, audits, caches, schedules, and tunes them centrally.

GET  /integration/outbound/saved-queries
GET  /integration/outbound/saved-queries/{saved_query_key}
POST /integration/outbound/saved-queries/{saved_query_key}/execute
POST /integration/outbound/saved-queries/{saved_query_key}/execute.csv
POST /integration/outbound/saved-queries/{saved_query_key}/execute.xml
GET  /integration/outbound/saved-queries/{saved_query_key}/snapshots/latest
POST /integration/outbound/admin/saved-queries/process-schedules

1. Create the AQL schedule

curl --request POST "${AMCDR_BASE_URL}/integration/outbound/saved-queries/high-risk-anc/schedules" \
  --header "Authorization: Bearer ${ACCESS_TOKEN}" \
  --header "Content-Type: application/json" \
  --data '{
    "name": "High-risk ANC every hour",
    "schedule_kind": "interval",
    "schedule_expression": "1h",
    "parameters": {"facility_id": "4f382b43-5812-4fab-91cf-3b92da2102f9"},
    "schedule_status": "active",
    "notification_mode": "notify_on_change",
    "notify_only_on_change": true,
    "persist_result_payload": true
  }'

For cron schedules use schedule_kind=cron and a five-field expression such as 0 6 * * *. Interval expressions accept positive values with s, m, h, or d suffixes.

2. Subscribe to the exact saved query

curl --request POST "${AMCDR_BASE_URL}/triggers/subscriptions" \
  --header "Authorization: Bearer ${ACCESS_TOKEN}" \
  --header "Content-Type: application/json" \
  --data '{
    "key": "changed-high-risk-anc-results",
    "name": "Changed high-risk ANC snapshots",
    "event_source": "integration",
    "event_type": "saved_query.snapshot_changed",
    "target_record_type": "saved_query",
    "target_record_id": "8b720657-02d0-4072-89d0-0ef139ba58e0",
    "delivery_mode": "webhook",
    "endpoint_url": "https://partner.example.org/hooks/amcdr-reports",
    "signing_secret": "replace-with-secret-from-vault"
  }'

Use saved_query.snapshot_ready when every completed snapshot should notify. Use saved_query.snapshot_changed when only changed result hashes should notify.

3. Receive the snapshot notification

{
  "schema_version": "1.0",
  "event_id": "cb465f6d-9eaf-47cf-86bb-921cb978927b",
  "event_source": "integration",
  "event_action": "snapshot_changed",
  "event_type": "saved_query.snapshot_changed",
  "occurred_at": "2026-07-21T12:00:00+00:00",
  "target_record_type": "saved_query",
  "target_record_id": "8b720657-02d0-4072-89d0-0ef139ba58e0",
  "subscription_key": "changed-high-risk-anc-results",
  "payload": {
    "saved_query_id": "8b720657-02d0-4072-89d0-0ef139ba58e0",
    "saved_query_key": "high-risk-anc",
    "snapshot_id": "73e2b95c-43d4-49c0-b3b0-1ec3bf58ff68",
    "row_count": 14,
    "result_hash": "5b684efc...",
    "changed": true,
    "fetch_url": "/workbench/queries/8b720657-02d0-4072-89d0-0ef139ba58e0/snapshots/73e2b95c-43d4-49c0-b3b0-1ec3bf58ff68",
    "latest_fetch_url": "/workbench/queries/8b720657-02d0-4072-89d0-0ef139ba58e0/snapshots/latest"
  }
}

The callback signals that the snapshot is available; it does not grant access to the result. Retrieve the snapshot through the supplied URL using the receiver's separately issued scoped credential.

Delivery Operations

Deliveries run asynchronously so a temporary partner outage does not prevent a clinical record from being saved. Operators or scheduled workers process pending deliveries, retry failed deliveries, and replay subscriptions when approved.

GET  /triggers/deliveries
GET  /triggers/broker-deliveries
POST /triggers/deliveries/process
POST /triggers/deliveries/process-broker
POST /triggers/deliveries/{delivery_id}/retry
POST /triggers/broker-deliveries/{delivery_id}/retry
POST /subscriptions/{subscription_id}/replay

Retry one failed delivery

curl --request POST "${AMCDR_BASE_URL}/triggers/deliveries/5ce8e025-f4a8-4349-a7db-a4cb42aa1ceb/retry" \
  --header "Authorization: Bearer ${ACCESS_TOKEN}"

# Response
{
  "id": "5ce8e025-f4a8-4349-a7db-a4cb42aa1ceb",
  "delivery_status": "delivered",
  "attempt_count": 2,
  "success": true
}

Replay recent matching events

curl --request POST "${AMCDR_BASE_URL}/subscriptions/0eddfeb8-df3c-4400-808b-3610dd921b7f/replay" \
  --header "Authorization: Bearer ${ACCESS_TOKEN}" \
  --header "Content-Type: application/json" \
  --data '{"limit":50}'

# Response
{
  "subscription_id": "0eddfeb8-df3c-4400-808b-3610dd921b7f",
  "event_source": "lifecycle",
  "matched_event_count": 12,
  "queued_delivery_count": 12,
  "status": "queued"
}

Replay reapplies event type, event family, target type, exact target UUID and governance scope. Receivers must therefore remain idempotent: replay and automatic retry can legitimately deliver the same event_id again.

Operational ItemWhat To Check
Delivery backlogUse delivery listings to see pending, retry-pending, delivered, and failed items.
Partner outageLet retries run within configured limits; replay only after the receiver is healthy.
SecurityUse signed webhooks, scoped tokens, HTTPS endpoints, and minimum necessary payloads.
AuditKeep event id, delivery id, partner endpoint, response status, and replay operator in the audit trail.

HTTP and delivery outcomes

OutcomeMeaning
Receiver returns 2xxThe callback is accepted and the delivery is recorded as delivered.
Receiver returns non-2xxThe attempt is unsuccessful. AMCDR schedules retry_pending or records failed after the configured maximum attempts.
Network error or timeoutThe attempt follows the same retry policy as a non-2xx response.
API returns 401 or 403The caller is unauthenticated or lacks the required administration or integration permission.
API returns 404The requested subscription or delivery identifier does not exist.
API returns 422Request validation failed, for example because of an invalid time window, grouping field, UUID, or batch limit.

Runtime Configuration

Webhook and outbound behaviour is controlled by backend settings and deployment environment variables. Exact variable naming follows the standard AMCDR_ settings convention.

SettingDefaultPurpose
event_webhook_timeout_seconds15HTTP timeout for one webhook delivery attempt.
event_webhook_signature_headerX-AmCDR-SignatureDefault header used for the HMAC-SHA256 signature. Can be overridden per subscription with definition.signature_header.
event_webhook_retry_backoff_seconds60Fallback retry delay when the subscription does not define retry_backoff_seconds.
event_webhook_allow_httpfalseAllows HTTP endpoints only for explicitly allowlisted hosts. Keep disabled in production.
event_webhook_allowed_hostsempty listHosts allowed for development HTTP exceptions or private test callbacks.
outbound_integration_enabledtrueMaster switch for outbound integration health, overview, and saved-query surfaces.
outbound_webhook_enabledtrueFeature flag for webhook delivery capability.
outbound_broker_enabledtrueFeature flag for broker delivery capability.
outbound_webhook_process_limit20Default worker batch size for pending webhook processing.
outbound_broker_process_limit20Default worker batch size for pending broker processing.
outbound_delete_batch_process_limit20Default worker batch size for grouped delete delivery processing.
outbound_replay_window_minutes1440Recommended operational replay window for outbound event recovery.

Access Control

Subscription administration is protected like the rest of the backend. Operators creating subscriptions, processing deliveries, replaying events, or reading delivery status must use an authenticated session, bearer token, or API credential with the required platform or integration role. Receivers must use their own scoped token when pulling data after a notification.

ActorAccess Needed
Platform adminCreate subscriptions, list delivery status, retry failed delivery, configure endpoint URL, signing secret, and event filters.
Integration operatorProcess pending deliveries, monitor failures, replay approved subscriptions, verify receiver health.
Partner receiverReceive webhook POST, verify signature, then call governed pull APIs with partner-scoped credentials.
Clinical userNo webhook access is required for standard clinical workflows. Clinical writes only emit events after commit.

External openEHR CDR Configuration

External openEHR CDRs used by template source discovery and form runtime composition submission are configured as RemoteCDR records in the AMCDR database. They are not browser configuration, and credentials must not be exposed to the frontend.

Configuration PlacePurpose
remote_cdr tableopenEHR CDR adapters used by template source manager and backend composition submission.
backend/config/module_config.ymlControls whether external_cdr_connectors is enabled and which adapter families are supported.
AMCDR_MODULE_EXTERNAL_CDR_CONNECTORS_ENABLEDEnvironment override to enable or disable external CDR connector routes at runtime.
backend/connectors.yaml or AMCDR_CONNECTORS_CONFIG_PATHExternal MPI, terminology connectivity, and generic outbound connectors. This is separate from RemoteCDR adapter records.
-- Provision through admin tooling or secret-managed deployment automation.
insert into remote_cdr (
  id, name, base_url, vendor, auth_config, created_at, updated_at
) values (
  gen_random_uuid(),
  'EHRbase Production',
  'https://ehrbase.example.org/ehrbase/rest/openehr/v1',
  'EHRBASE',
  '{"bearer_token":"<secret-from-vault-or-provisioning>","timeout_seconds":20}'::jsonb,
  now(),
  now()
);

Supported adapter vendors are EHRBASE, BETTER_CDR, and HIP_CDR. The adapter calls standard openEHR REST-style endpoints for template listing, web-template retrieval, template upload, composition create/update, and AQL execution. See MPI, FHIR, and External CDRs for the full connector boundary.

Security Rules

Troubleshooting

SymptomLikely CauseAction
No delivery createdSubscription scope, event family, event type, or target record type does not match the lifecycle event.Check GET /triggers/events and compare the subscription filters.
Endpoint URL rejectedThe URL is not absolute HTTP(S), uses HTTP without allowlisting, or resolves to private, loopback, link-local, reserved, multicast, or unspecified IP space.Use a public HTTPS receiver in production. For local testing, explicitly configure allowed hosts and do not copy that exception to production.
Webhook delivery failsEndpoint unavailable, TLS problem, authorization issue, or receiver timeout.Inspect /triggers/deliveries, receiver logs, and retry after the endpoint is healthy.
Signature mismatchReceiver signed a different JSON shape, used unsorted JSON, wrong secret, or wrong signature header.Verify compact sorted JSON and the configured X-AmCDR-Signature or custom header.
Partner receives event but cannot read FHIRPartner token lacks route, scope, protected-record, or patient access.Review RBAC, policy, purpose of use, and partner API token claims.
Duplicate webhook receivedDelivery retry or operator replay.Make the receiver idempotent using event identifiers and target identifiers.
External CDR is not listedexternal_cdr_connectors disabled or no active RemoteCDR records.Check module settings and GET /template-sources.
External composition post failsMissing external ehr_id, invalid template id, wrong format, or CDR credential failure.Verify patient context, template id, adapter vendor, and auth_config.