Integration

API and Lifecycle Operations

Use clinical APIs and manage record versions, deletion, restoration, lifecycle events, and administration operations.

Audience

Use this guide to choose an API, handle responses and follow a record through creation, correction and deletion. It also explains partner authentication, event delivery and the responsibilities of integration teams.

API groups

Clinical record APIsCreate, retrieve, update, version, amend, and govern structured clinical records.
Patient and encounter APIsResolve patient identity, active visits, encounters, transfers, discharge state, and care context.
Template and form APIsExpose published templates, generated forms, field metadata, coded bindings, and validation requirements.
Terminology APIsLookup, validate, expand, and translate coded values used in forms, mappings, reports, and exchange.
Query and reporting APIsRun governed queries, saved queries, indicator outputs, patient-context reports, and scheduled extracts.
Lifecycle and subscription APIsExpose auditable lifecycle events and deliver governed webhook or broker notifications to approved consumers.
Standards-facing API reference: use the openEHR API Reference for Definition, EHR, Composition, Folder, Contribution, and Query API examples with request and response payloads.

Authenticated Swagger and Postman

Live Swagger is part of the protected AMCDR frontend, not a public route. Open /api-docs/swagger after signing in; /doc is the supported short alias. The Swagger request interceptor attaches the current AMCDR bearer token and includes cookies for reverse-proxy sessions. The raw schema is available through /api-docs/openapi.json in the same frontend session, or through /openapi.json for API clients that send Authorization: Bearer or X-API-Key.

Medication lifecycle and MediServe handoff examples are available in postman/AMCDR_Medication_Lifecycle.postman_collection.json with postman/AMCDR_Sandbox.postman_environment.json. The collection uses the same AMCDR authentication model: update access_token from a logged-in session or run local password login where enabled.

Inbound Partner Registration And Credentials

Before a partner sends data, register it as an integration or service account and issue a scoped bearer token or API key. Approve its routes, purpose of use, tenant, organisation, environment, facility and data-sharing contract. Network access alone does not authorize an import.

ControlProduction expectation
Partner identityCreate a named integration/service account for the sending organisation or system. Do not reuse human administrator accounts.
CredentialUse Authorization: Bearer <token> or X-API-Key: <api-key>. API keys are created through the AMCDR API key management endpoints or protected operations tooling.
ScopesUse the narrowest ingest scope possible: integration:ingest:fhir, integration:ingest:records, integration:ingest:compositions, or integration:ingest:* for controlled multi-format partner feeds.
Network controlIP allow-listing, VPN, mTLS, or private connectivity may be added, but they are additional controls. They do not replace application authentication and authorization.
AuditAMCDR records authenticated actor, purpose of use, source metadata, patient/EHR resolution, validation result, created composition/version identifiers, and warnings or errors.
POST /auth/api-keys
Authorization: Bearer <admin-or-integration-admin-token>
Content-Type: application/json

{
  "service_account_id": "11111111-1111-1111-1111-111111111111",
  "scopes": [
    "integration:ingest:fhir",
    "clinical-record"
  ],
  "expires_at_text": "2026-12-31"
}

Partner credentials should be stored in a vault or secret manager, rotated on a defined schedule, and revoked immediately when the integration contract ends or the sending system is compromised.

Laboratory API lifecycle

Laboratory APIs are module-scoped and preserve lifecycle history. A lab journey uses lab_workflow_id to link the clinical order, specimen, transport, transfer, processing, result, correction, cancellation, alert, and acknowledgement records. The API writes operational events for lab workflow state and commits clinical orders/results to the openEHR record where clinically meaningful.

StageTypical APILifecycle rule
OrderPOST /lab/ordersCreates clinical intent and the first workflow event. Do not duplicate orders on transfer.
CancelPOST /lab/orders/{lab_order_id}/cancelCreates a cancellation event; original order/specimen history remains visible.
TransferPOST /lab/orders/{lab_order_id}/transferMoves operational responsibility while preserving lab_workflow_id.
SpecimenPOST /lab/orders/{lab_order_id}/specimensRecords collection/accession context and barcode/specimen state.
TransportPOST /lab/specimens/{specimen_id}/transport/startTracks courier, handover, delay, cold-chain breach, loss, or damage as operational events.
ResultsPOST /lab/resultsCreates atomic result observations and alert candidates.
CorrectionPOST /lab/results/{observation_result_id}/correctCreates a corrected result event; prior final result is not destructively overwritten.
AcknowledgementPOST /lab/alerts/{alert_id}/acknowledgeRecords who acknowledged a critical result, when, and what action was taken.

Shared Health Record And IPS Retrieval

Use records summary APIs when an integration needs a governed clinical read model rather than raw compositions. Single-patient routes return patient-specific summaries and timelines. The population route returns SHR or IPS availability across cohorts, facilities, locations, date ranges, or patient filters.

OperationRouteNotes
Current patient summaryGET /records/patient/{patient_id}/summary/current?format=json|fhir|xmlPatient-level SHR projection.
Encounter summaryGET /records/patient/{patient_id}/summary/encounters/{encounter_id}?format=json|fhir|xmlEncounter-scoped SHR projection.
Annual summaryGET /records/patient/{patient_id}/summary/annual/{year}?format=json|fhir|xmlYear-scoped clinical summary.
Population SHR or IPSGET /records/patients/summary?profile=shr|ips&include=index|summary&format=json|fhir|xmlDefaults to lightweight include=index. Use include=summary only for authorized embedded patient summaries.
GET /records/patients/summary?profile=ips&include=index&date_from=2026-01-01&date_to=2026-06-30&location=Emergency&page=1&page_size=25&format=fhir

Supported population filters include date_from, date_to, location, facility_id, encounter_type, identifier, name, gender, birthdate, and _lastUpdated. Population retrieval remains governed by RBAC, protected-record policy, consent and release controls, purpose of use, and audit.

Clinical write routes

AMCDR accepts structured clinical payloads, form-derived submissions, template-aligned records, standards-based exchange payloads, and approved interoperability messages. Successful write calls return an acknowledgement containing patient context, record identifiers, version metadata, lifecycle status, and validation warnings where applicable.

Incoming partner writes use one of three governed patterns: FHIR facade ingest for linked FHIR resources, mapped FHIR ingest for profile-validated FHIR-to-openEHR conversion, or template-based composition ingest for TDD XML, FLAT JSON, and STRUCTURED JSON.

Incoming payloadRouteCredential scopeUse when
FHIR Bundle packagePOST /fhir/Bundleintegration:ingest:fhirThe partner sends a document, message, collection, IPS, SHR, referral, transfer, or report package containing linked FHIR resources.
Direct FHIR resource createPOST /fhir/{ResourceType}clinical-record, unless deployment policy narrows this routeThe partner creates a single supported resource. Prefer Bundle or profile ingest when preserving full SHR/IPS context.
FHIR profile mapped to templatesPOST /fhir/ingestintegration:ingest:fhirThe partner payload must validate against a known FHIR StructureDefinition and mapping before AMCDR creates canonical compositions.
TDD XML transformationPOST /records/ingestintegration:ingest:compositionsA governed transformation converts the mapping artefact; it is not a second composition CRUD API.
FLAT or STRUCTURED JSONPOST /openehr/v1/ehr/{ehr_id}/compositionintegration:ingest:compositionsThe standard media type selects the simplified representation.
Generic record ingestPOST /records/ingestintegration:ingest:recordsThe caller submits a governed record ingest envelope containing patient, template, composer, category, name, source, and payload.

TDS And TDD Composition Ingest

The OPT is the source template. The TDS XSD is the template-specific schema imported by mapping tools. The TDD XML is the mapped document instance produced against that schema and submitted to AMCDR. It does not replace canonical openEHR persistence; AMCDR validates the TDD XML and converts it into the canonical composition pipeline.

OperationRouteRequired format
Download TDS XSDGET /templates/{template_key}/exports/tdsGenerates on demand when needed, then returns the schema for Talend, Mirth, ALUR, or XML validators.
Generate sample by active templateGET /templates/{template_key}/examples/tddtdd
Generate sample by exact template versionGET /template-versions/{template_version_id}/examples/tddtdd
Transform mapped TDD XMLPOST /records/ingestUses the governed transformation envelope.
Read created compositionGET /openehr/v1/ehr/{ehr_id}/composition/{uid_based_id}Use Accept to select canonical, FLAT, or STRUCTURED representation.

The TDD importer parses XML strings or {"xml": "..."} wrappers. XML elements are matched to template aliases, XML-safe labels, node ids, canonical field names, canonical OPT paths, and AQL paths. DV_QUANTITY values are normalised with magnitude and units; DV_PROPORTION values are normalised with numerator, denominator, type, and precision; coded values are normalised to {"code": "...", "value": "...", "terminology_id": "..."}.

TDD source artefact supplied in the POST /records/ingest transformation envelope:

<?xml version="1.0" encoding="UTF-8"?>
<KDS_Laborbericht xmlns="http://schemas.oceanehr.com/templates"
                 xmlns:oe="http://schemas.openehr.org/v1"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 template_id="kds-laborbericht">
  <context>...</context>
  <data>...</data>
</KDS_Laborbericht>

Flat JSON And Structured JSON Composition Ingest

The clinical write API accepts FLAT JSON and STRUCTURED JSON directly. Use FLAT JSON when an external form, ETL job, or partner application can send compact template field keys. Use STRUCTURED JSON when the sender can preserve a richer openEHR-shaped composition envelope, context, content sections, events, items, datatypes, and values.

OperationRouteRequired format
Download flat JSON exampleGET /templates/{template_key}/examples/flatTemplate-aware JSON sample with ctx/... context keys.
Download structured JSON exampleGET /templates/{template_key}/examples/structuredTemplate-aware structured JSON sample.
Create composition from FLAT JSONPOST /openehr/v1/ehr/{ehr_id}/compositionContent-Type: application/openehr.wt.flat+json.
Create composition from STRUCTURED JSONPOST /openehr/v1/ehr/{ehr_id}/compositionContent-Type: application/openehr.wt.structured+json.
Read a simplified representationGET /openehr/v1/ehr/{ehr_id}/composition/{uid_based_id}Use the corresponding openEHR Accept media type.

Every persisted composition can be exported as TDD XML, flat JSON, or structured JSON regardless of the format used to create it. AMCDR uses the persisted canonical composition and template definition to generate the requested projection when the original source payload used another format.

Flat JSON example

GET /templates/kds-laborbericht/examples/flat

POST /openehr/v1/ehr/00000000-0000-0000-0000-000000000000/composition
Content-Type: application/openehr.wt.flat+json
openehr-template-id: kds-laborbericht

{
  "ctx/language": "de",
  "ctx/territory": "DE",
  "ctx/composer_name": "AMCDR Integration",
  "ctx/time": "2026-06-11T09:30:00Z",
  "laboratory_test_name": "Haemoglobin",
  "laboratory_result_magnitude": 13.4,
  "laboratory_result_units": "g/dL",
  "laboratory_result_status": "final"
}

Structured JSON example

GET /templates/kds-laborbericht/examples/structured

POST /openehr/v1/ehr/00000000-0000-0000-0000-000000000000/composition
Content-Type: application/openehr.wt.structured+json
openehr-template-id: kds-laborbericht

{
  "_type": "COMPOSITION",
  "template_id": "kds-laborbericht",
  "name": {"value": "Laboratory report"},
  "language": {"code_string": "de"},
  "territory": {"code_string": "DE"},
  "composer": {"name": "AMCDR Integration"},
  "context": {
    "start_time": {"value": "2026-06-11T09:30:00Z"}
  },
  "content": [
    {
      "_type": "OBSERVATION",
      "name": {"value": "Laboratory result"},
      "data": {
        "events": [
          {
            "_type": "POINT_EVENT",
            "time": {"value": "2026-06-11T09:30:00Z"},
            "data": {
              "items": [
                {
                  "_type": "ELEMENT",
                  "name": {"value": "Haemoglobin"},
                  "value": {
                    "_type": "DV_QUANTITY",
                    "magnitude": 13.4,
                    "units": "g/dL"
                  }
                }
              ]
            }
          }
        ]
      }
    }
  ]
}

Composition export examples

GET /openehr/v1/ehr/{ehr_id}/composition/{uid_based_id}
Accept: application/openehr.wt.flat+json

200 OK
{
  "format": "flat_json",
  "composition_id": "{composition_id}",
  "template_id": "kds-laborbericht",
  "payload": {
    "ctx/language": "de",
    "ctx/territory": "DE",
    "ctx/composer_name": "AMCDR Integration",
    "laboratory_test_name": "Haemoglobin",
    "laboratory_result_magnitude": 13.4,
    "laboratory_result_units": "g/dL"
  }
}

FHIR Composition handling

FHIR Composition is handled as an exchange document organizer. AMCDR preserves the source FHIR resource and maps it into canonical clinical persistence only when an approved template mapping exists.

Composition aloneUse when the payload has subject, type, status, date, author, and section context.
Bundle with CompositionPreferred when sections reference Observations, Conditions, MedicationRequest, MedicationStatement, MedicationAdministration, Medication, DiagnosticReports, DocumentReferences, or Encounters.
Unmapped CompositionStore as governed source material and provenance; do not treat it as normalized clinical truth until mapped and validated.

Section entries must remain linked to their referenced resources. Status values such as preliminary, final, amended, and entered-in-error map to AMCDR lifecycle state and audit behavior rather than overwriting prior clinical history.

Validation failures must include field-level detail. FHIR-facing responses use OperationOutcome paths such as Composition.subject, Composition.section[0].entry[2], or the mapped canonical field path.

Status codes and error bodies

Swagger provides the route and schema reference. Operational behavior also depends on authentication mode, module configuration, policy rules, schema revision, protected-record rules, request size limits, and external service state. Use this table together with the endpoint description.

StatusMeaning in AMCDRTypical action
200 OKThe read, update, execution, export, replay, or lifecycle action completed.Use the returned object, acknowledgement, or result set.
201 CreatedA new resource, composition version, template, subscription, form, or configuration object was created.Store the returned identifier and version metadata.
400 Bad RequestThe request is understood but invalid for the operation. Common causes include invalid AQL, invalid business state, unsupported mapping input, or template validation failure.Fix the request content, parameters, or query before retrying.
401 UnauthorizedNo usable authentication was supplied, the token is invalid or expired, or the configured authentication method is disabled.Log in again, refresh the token, or use the configured bearer/API-key path.
403 ForbiddenThe user is authenticated but cannot perform the action. Causes include missing role, module disabled, policy denial, scope mismatch, or protected-record rules.Check role assignments, module mode, purpose of use, protected-record clearance, and policy configuration.
404 Not FoundThe referenced patient, EHR, composition, template, task, subscription, delivery, or configuration object was not found or is hidden by policy.Verify the identifier and tenant/organisation/environment context.
405 Method Not AllowedThe route exists but the attempted method or FHIR resource operation is not enabled.Use an enabled method or enable the resource operation in configuration.
406 Not AcceptableThe standards-facing route cannot satisfy the requested Accept header.Request a supported media type such as JSON or FHIR JSON.
409 ConflictThe requested state change conflicts with the current resource state, version, lock, archive status, or workflow state.Reload the object, resolve the state/version conflict, then retry.
413 Payload Too LargeThe request body or uploaded file exceeds the configured platform limit.Reduce the payload, split the upload, or raise the configured body-size limit deliberately.
422 Unprocessable ContentThe JSON shape reached the endpoint but failed request-model validation or semantic validation.Inspect the field-level errors and correct the body.
429 Too Many RequestsRate limiting has blocked the request, most commonly around authentication attempts.Back off before retrying and check whether clients are looping.
500 Internal Server ErrorAn unexpected server failure occurred.Treat as an incident, check backend logs, and use request timing/correlation data where available.
501 Not ImplementedThe requested adapter capability or external CDR operation is recognised but not implemented for that connector.Choose a supported adapter operation or complete the connector implementation.
503 Service UnavailableThe platform is not ready for the request, often because of schema revision mismatch or unavailable dependency state.Run migrations, check readiness, and verify dependent services.

Most AMCDR API errors use one of five response-body patterns:

PatternExampleWhen it appears
Standard detail{"detail":"Authentication required"}Authentication, not-found, and standard HTTP exceptions.
Validation list{"detail":[{"loc":["body","system_url"],"msg":"Field required"}]}FastAPI/Pydantic request validation, typically 422.
Structured detail{"detail":{"code":"REQUEST_BODY_TOO_LARGE","message":"Request body exceeds the configured limit."}}Platform guards, template validation, AQL parsing, and service-specific errors.
Policy denial{"detail":"You do not have permission to perform this action.","required_roles":["super_admin"]}RBAC/ABAC policy, protected-record rules, scope enforcement, and admin-only actions.
FHIR OperationOutcome{"resourceType":"OperationOutcome","issue":[{"severity":"error","code":"invalid","diagnostics":"Missing required parameter"}]}FHIR-facing validation, terminology, profile, and mapping failures.

For integrations, read the HTTP status first, then inspect detail or OperationOutcome.issue. Treat 400, 405, and 422 as request-correction problems; 401 as a token/session problem; 403 as a permission, module, policy, or protected-record problem; 409 as a state/version conflict; 413 as a payload-size problem; 429 as a backoff problem; and 503 as a deployment readiness problem.

Read and query routes

Read APIs support direct record retrieval, patient timeline views, patient summary views, governed search, and parameterised saved queries. Technical clients must use named saved queries for repeatable reporting or partner exchange so the platform governs, versions, audits, and tunes those queries centrally.

AQL support for technical users

AMCDR supports a governed AQL subset for clinical repository queries, saved queries, HMIS indicators, and partner reporting. Implementers must validate queries in the workbench and save approved versions before using them in production integrations.

Core clausesSELECT, FROM, CONTAINS, NOT CONTAINS, WHERE.
AggregationDISTINCT, COUNT(*), GROUP BY, HAVING, selected-column aliases, and ordinal grouping such as GROUP BY 1, 2.
Sorting and pagingORDER BY, ASC, DESC, NULLS FIRST, NULLS LAST, TOP, LIMIT, OFFSET, and SQL-style FETCH FIRST/NEXT ... ROWS ONLY.
FilteringAND, OR, NOT, EXISTS, IN, NOT IN, MATCHES, NOT MATCHES, LIKE, NOT LIKE, BETWEEN, IS NULL, IS NOT NULL, IS TRUE, and IS FALSE.
ExpressionsQuoted aliases, selected-column aliases in filters and grouping, basic functions, CASE expressions, scalar subqueries, and quantified subqueries using ANY, ALL, or SOME.
Compound queriesUNION, UNION DISTINCT, INTERSECT, and EXCEPT for compatible projected result sets.

For production reports, avoid unbounded queries. AMCDR applies an internal default limit of 1000 rows when an AQL query has no explicit row cap. Explicit LIMIT, TOP, or SQL-style FETCH FIRST/NEXT ... ROWS ONLY clauses override that guardrail. Use date ranges, facility or organisation filters, explicit result columns, and pagination. Prefer saved queries for any report or integration that will be reused.

SELECT c
FROM EHR e
CONTAINS COMPOSITION c[kds-laborbericht]
ORDER BY c/context/start_time/value DESC
LIMIT 5 OFFSET 0
SELECT c/name/value AS composition_name,
       c/context/start_time/value AS recorded_at
FROM EHR e
CONTAINS COMPOSITION c[kds-laborbericht]
ORDER BY recorded_at DESC
OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY
SELECT TOP 5 c/name/value AS composition_name,
             c/context/start_time/value AS recorded_at
FROM EHR e
CONTAINS COMPOSITION c[kds-laborbericht]
ORDER BY recorded_at DESC

CQL support for technical users

AMCDR uses Clinical Quality Language for reviewed, deterministic rules. CQL is intended for clinical quality logic, workflow guardrails, CDS rules, and repeatable decision support checks. AQL is best for querying the repository; CQL is best for executable clinical logic over patient context and coded data.

Library lifecycleCreate CQL libraries, add versioned source, activate a version, compile when the runtime is available, and track execution records.
Accepted sourcePlain text/cql libraries and FHIR Library resources with attached CQL content.
InterpretationExtracts library name, version, included libraries, code systems, value sets, codes, concepts, parameters, context, definitions, and functions.
CompilationCompiled artifacts are produced through the configured CQL execution boundary or attached as runtime artifacts where available.
EvaluationEvaluates active or pinned library versions against supplied subject/context data, with audit records for each execution.
Workflow useCQL bindings are available for workflows, workflow stages, form bindings, CDS rules, and assistant guardrails.
GuardrailsCQL supports execution before or after AI-assisted workflows so deterministic rules remain the safety boundary.

For production use, keep CQL libraries versioned, activate only reviewed versions, bind rules explicitly to the workflow or CDS use case, and configure failed-rule handling as warning, blocking, or audit-only. CQL does not replace clinical judgement; it makes approved rules executable and traceable.

Versioning and lifecycle

Clinical entries support creation, update, amendment, supersession, logical deletion, restoration, and permanent removal only where policy allows. Each change produces a lifecycle event with actor, timestamp, patient context, affected object, previous state, new state, reason where supplied, and correlation information for external messages.

AQL-selected batch hard deletion

Irreversible super-admin operation: use POST /openehr/v1/admin/composition/hard-delete-batch only after retention, backup and approval requirements are satisfied. The endpoint previews by default and is documented under openEHR Admin in the authenticated Swagger UI at /api-docs/swagger or /doc. It is explicitly marked as an AMCDR product extension.

Select exactly one source: an explicit composition_ids array, or aql_text. AQL must project c/uid/value AS composition_id. It can filter by template ID, composition name, version commit time, lifecycle state, EHR context, or other supported predicates. This supports bulk removal by time range, template, composition name, or a combination of those conditions.

1. Preview the exact AQL selection

POST /openehr/v1/admin/composition/hard-delete-batch
Authorization: Bearer {platform_or_integration_admin_token}
Content-Type: application/json

{
  "aql_text": "SELECT c/uid/value AS composition_id, c/name/value AS composition_name FROM EHR e CONTAINS VERSION v CONTAINS COMPOSITION c WHERE c/archetype_details/template_id/value = 'vital-signs' AND c/name/value LIKE '%Vital%' AND v/commit_audit/time_committed/value >= '2026-07-01T00:00:00Z' AND v/commit_audit/time_committed/value < '2026-07-02T00:00:00Z' LIMIT 100",
  "include_logically_deleted": true,
  "max_compositions": 100,
  "dry_run": true,
  "reason_code": "approved_duplicate_cleanup"
}

Review every returned item and retain the response selection_hash. A preview includes logically deleted versions when requested, so AQL can select records no longer visible to normal clinical queries.

2. Execute only the reviewed selection

POST /openehr/v1/admin/composition/hard-delete-batch
Authorization: Bearer {super_admin_token}
Content-Type: application/json

{
  "aql_text": "SELECT c/uid/value AS composition_id FROM EHR e CONTAINS VERSION v CONTAINS COMPOSITION c WHERE ... LIMIT 100",
  "include_logically_deleted": true,
  "max_compositions": 100,
  "dry_run": false,
  "confirm_hard_delete": true,
  "expected_selection_hash": "SHA256_FROM_PREVIEW",
  "reason_code": "approved_duplicate_cleanup",
  "message": "Approved after preview and backup verification."
}

The request fails if the AQL selection changed after preview. The safety ceiling is 500 compositions and can be lowered with max_compositions. Results report ready, deleted, not_found, or failed per composition; successful deletions are committed and audited individually.

Explicit composition IDs

{
  "composition_ids": [
    "11111111-1111-4111-8111-111111111111",
    "22222222-2222-4222-8222-222222222222"
  ],
  "dry_run": false,
  "confirm_hard_delete": true,
  "reason_code": "approved_duplicate_cleanup"
}

Do not combine composition_ids and aql_text. Logical delete remains the normal clinical lifecycle action; hard delete physically removes recoverable clinical payload and version history.

Expected lifecycle states

createdA new clinical or operational object has been accepted.
updatedAn existing object has changed without replacing its clinical meaning.
amendedA correction has been made while preserving the history of the earlier entry.
supersededA newer entry replaces the older one for standard use, while the old one remains traceable.
deletedThe object is no longer active for standard use but remains auditable.
restoredA previously deleted object has been returned to use.

Composition lifecycle authority

OperationRoute authorityPurpose
Clinical correction/versioningPUT /openehr/v1/ehr/{ehr_id}/composition/{uid_based_id}Normal clinical update with version history and optimistic concurrency.
Logical deleteDELETE /openehr/v1/ehr/{ehr_id}/composition/{uid_based_id}Standard openEHR deleted version; retained for audit and possible governed recovery.
Restore, expire, revoke, supersedePOST /openehr/v1/admin/ehr/{ehr_id}/composition/{uid_based_id}/{action}Privileged records-governance transition performed by an authenticated super-administrator.
Physical deletionDELETE /openehr/v1/admin/ehr/{ehr_id}/composition/{uid_based_id} or the AQL batch endpointIrreversible governed removal.

Lifecycle reporting and scheduled notifications

AMCDR supports immediate lifecycle webhooks for individual changes, lifecycle activity reports for time-bounded totals and item details, and scheduled saved-query notifications for approved clinical AQL snapshots.

GET /triggers/events/activity?since=2026-07-01T00:00:00Z&until=2026-08-01T00: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

The activity response includes the total, standard counts by action, resource type, event type and source, requested groupings, stable pagination metadata, event details and retained deletion tombstones. Scheduled reports are configured through definition.activity_batch and processed by POST /triggers/deliveries/process-activity-batches or the automatic outbound runtime.

A saved-query webhook uses event_source=integration, target_record_type=saved_query, the saved query UUID in target_record_id, and saved_query.snapshot_ready or saved_query.snapshot_changed. This preserves AQL as the clinical-query interface while lifecycle reporting remains the authoritative operational audit interface.

Integration contract expectations

Subscription safety

Swagger exposes these operations under Lifecycle & Webhooks. Subscriptions must be scoped by event type, organisation, facility, data class, and purpose. Deliveries must be signed, retried with limits, logged, and replayable by an operator. Delivery must not block the clinical write acknowledgement; a clinical write remains valid even if a downstream notification is delayed.

POST /triggers/subscriptions
GET  /triggers/events
GET  /triggers/events/activity
GET  /triggers/events/deleted-compositions
GET  /triggers/deliveries
POST /triggers/deliveries/process
POST /triggers/deliveries/process-activity-batches
POST /triggers/deliveries/{delivery_id}/retry
POST /subscriptions/{subscription_id}/replay
POST /triggers/subscriptions
Authorization: Bearer {super_admin_token}
Content-Type: application/json

{
  "key": "deleted-composition-webhook",
  "name": "Deleted composition webhook",
  "event_source": "lifecycle",
  "event_type": "composition.logical_deleted",
  "target_record_type": "composition",
  "delivery_mode": "webhook",
  "endpoint_url": "https://integration.example.org/amcdr/composition-events",
  "signing_secret": "managed-secret-reference",
  "definition": {
    "event_types": [
      "composition.logical_deleted",
      "composition.hard_deleted"
    ]
  }
}

For partner subscriptions, webhooks, broker streams, FHIR pull-after-event, saved-query extracts, delivery operations, and replay, use Subscriptions and Outbound Delivery.

What to expect in a response

Technical responses must be predictable: success responses identify the accepted object and lifecycle state; validation responses explain field-level problems; authorization responses avoid leaking clinical content; retryable errors are clearly distinguishable from permanent rejections.