OCTA Health Gate — API v1
Base URL: https://health.medcoreapp.tech (deployment setting PUBLIC_DOMAIN). All bodies are JSON (UTF-8). All responses are {"success": true, "data": …} or {"success": false, "error": "…"}. Error messages are in Arabic and safe to show to end users. File downloads (CDA, package) are the only non-JSON responses.
Overview
The gateway connects hospital and clinic systems (MedCore first) to Saudi health platforms: Seha sick leaves, SeHE (national health information exchange), Wasfaty, Nafath, and — once published — Mawid and Seha Virtual Hospital. Each establishment (facility) is a tenant; every record belongs to one facility, and every facility belongs to the calling app.
Honesty rule. None of these agencies publishes a system-to-system interface we can build on. The gateway never invents an endpoint, field, code or specification. Anything unpublished is PENDING in the agency profile (GET /v1/agencies) and the api channel refuses to run (409, code: "channel_not_ready") until the agency's document is received. Wording is compatible with the published specification, never "certified", until an official certification result exists.
| Mode | What it does | Agencies |
|---|---|---|
manual | The action is done on the agency portal by the facility; the gateway records the agency reference once plus evidence, tracks status and reminds | seha_sickleave, wasfaty |
file | SeHE package for download and testing on public IHE tools: CDA R2 + ebRIM metadata + ITI-41 MTOM message. Sends nothing | sehe |
sandbox | Non-production simulation: references start with SANDBOX-, every result carries "simulated": true. Nafath simulation never verifies anyone | all except mawid, seha_virtual |
api | Direct integration — 409 channel_not_ready until the agency document arrives | all |
SeHE implementation profile: ihe-xdsb-cda-2015 (IS0102 / IS0005, published 2015) — unconfirmed for the current national platform.
Authentication
| Header | Use |
|---|---|
X-API-Key: ohg_… | Server-to-server (MedCore and subscribed systems) |
Authorization: Bearer <token> | Dashboard sessions (/portal/login) |
Internal OCTA apps get a key from POST /admin/apps (or manage.py create-app) and have no subscription limits. Every resource is scoped to the calling app: an id belonging to another app returns 404, never 403.
Rate limit: RATE_LIMIT_PER_MINUTE per app (default 600) → 429.
Conventions
- Idempotency:
external_refis unique per facility and record type. Repeating a create with the sameexternal_refreturns the existing record (200instead of201). Use MedCore's own ids (e.g.enc-55:sl). - Actors:
created_by,approved_by,actorare user ids in the calling system. The gateway enforces "the reviewer is not the creator", so pass the real user. With a dashboard session the identity is the signed-in member and the body field is ignored. - No PHI in JSON: national ID / iqama numbers are encrypted at rest and only
patient_nid_last4is returned. Diagnoses, prescription items and CDA content are encrypted and never returned in JSON. Webhooks and the audit trail follow the same rule. - Agency references are recorded once: a Seha leave number or Wasfaty prescription number can be attached to one record only, once, even under concurrency (
409otherwise). - Coding licences: the gateway ships no code tables. ICD codes are checked for shape only, and their system must be one the facility has declared as licensed (
settings.coding.licensed_systems). Licensing (ICD-10-AM etc.) is the facility's responsibility. - Dates are Gregorian
YYYY-MM-DD.
| Status | Meaning |
|---|---|
| 400 | Invalid input |
| 401 | Bad or revoked key / expired session |
| 402 | Subscription inactive, quota reached, or agency not in the plan (sandbox is always free) |
| 403 | Not allowed (e.g. the creator approving their own sick leave) |
| 404 | Not found or belongs to another app |
| 409 | State conflict, duplicate agency reference, or code: "channel_not_ready" |
| 429 | Rate limited |
| 502 | Agency channel error |
Facilities
- POST /v1/tenants —
{"external_ref": "hospital-12", "name": "…", "cr_number": "…"}(create or update). - GET /v1/tenants · GET /v1/tenants/{tid}
- PUT /v1/tenants/{tid}/settings
{"coding": {"licensed_systems": ["ICD-10-AM"]}, // the facility attests it holds these licences
"sickleave": {"reminder_hours": 24}, // webhook reminder if not registered in Seha
"actor": "user:1"}
Channels
POST /v1/tenants/{tid}/channels — one channel per agency per facility (re-posting changes mode/config; changing mode drops stored secrets).
{"agency": "seha_sickleave" | "sehe" | "wasfaty" | "nafath" | "mawid" | "seha_virtual",
"mode": "manual" | "file" | "sandbox" | "api", "config": {…}}
SeHE in file/api mode needs the facility's own OIDs — there are no defaults: config.document_oid_root and config.source_oid. The sandbox uses a simulated 2.25.… arc.
- GET /v1/tenants/{tid}/channels · GET /v1/channels/{cid} — each includes
readiness: {ready, problems[]}; MedCore's readiness board reads this. - PUT /v1/channels/{cid}/secrets —
{"secrets": {…}}(credentials or mTLS material issued to the facility). Encrypted; only key names are echoed. - POST /v1/channels/{cid}/sync — pull new statuses (
sandbox;apionce available).
Sick leaves (Seha)
Lifecycle (internal tracking model matching the published manual workflow: entry → review → approval):
draft --approve--> approved --submit--> pending_seha --seha-reference--> registered
'--reject--> rejected --submit--> pending_seha
draft | approved | rejected --cancel--> cancelled
POST /v1/tenants/{tid}/sick-leaves
{"external_ref": "enc-55:sl", "created_by": "user:12",
"patient": {"national_id": "1xxxxxxxxx", "ref": "MRN-9"},
"practitioner": {"ref": "user:12", "license": "…"},
"start_date": "2026-11-20", "end_date": "2026-11-22",
"diagnosis": {"text": "…", "code": "J45.9", "system": "ICD-10-AM"}, // optional, encrypted
"encounter_ref": "enc-55", "companion": false, "notes": "…"}
- GET /v1/tenants/{tid}/sick-leaves?status=&patient_ref= · GET /v1/sick-leaves/{id} (with
history[]) - POST /v1/sick-leaves/{id}/approve —
{"approved_by": "user:57"}; must differ fromcreated_by(403). - POST /v1/sick-leaves/{id}/submit —
{"actor": "…"}→manual:pending_seha+channel_result.instructions_ar;sandbox: simulated;api:409. - POST /v1/sick-leaves/{id}/seha-reference — manual channel only:
{"seha_reference": "…", "evidence_ref": "attachment:991", "evidence_sha256": "…", "actor": "…"}. Evidence is required; the reference is accepted once. - POST /v1/sick-leaves/{id}/reject — manual:
{"reason": "…", "actor": "…"}. - POST /v1/sick-leaves/{id}/cancel —
{"actor": "…", "reason": "…"}.
Prescriptions (Wasfaty)
ready --submit--> sent (manual) --wasfaty-reference--> acknowledged --status--> dispensed | partially_dispensed | expired
'--submit--> acknowledged (sandbox)
ready | sent | acknowledged --cancel--> cancelled
POST /v1/tenants/{tid}/prescriptions — ICD diagnosis is mandatory.
{"external_ref": "rx-901", "created_by": "user:12",
"patient": {"national_id": "2xxxxxxxxx", "ref": "MRN-9"}, "prescriber": {"ref": "user:12"},
"diagnoses": [{"code": "J45.9", "system": "ICD-10-AM", "text": "…"}],
"items": [{"medication_text": "…", "medication_code": "…", "medication_code_system": "…",
"dose": "…", "route": "…", "frequency": "…", "duration_days": 7, "quantity": 1, "instructions": "…"}]}
- GET /v1/tenants/{tid}/prescriptions · GET /v1/prescriptions/{id}
- POST /v1/prescriptions/{id}/submit —
{"actor": "…"} - POST /v1/prescriptions/{id}/wasfaty-reference — manual:
{"wasfaty_reference": "…", "actor": "…", "evidence_ref": "…"} - POST /v1/prescriptions/{id}/status — manual:
{"status": "dispensed" | "partially_dispensed" | "expired", "actor": "…"} - POST /v1/prescriptions/{id}/cancel —
{"actor": "…"}
Nafath
The only detailed public description is a third-party source: user enters the ID, a number is shown, the user approves in the Nafath app within 60 seconds, result accepted / rejected / expired. Server API, token format, JWKS URL and claim names are PENDING.
- POST /v1/tenants/{tid}/nafath/transactions —
{"external_ref": "…", "purpose": "staff_login" | "patient_login" | "kyc" | "consent", "national_id": "…", "actor": "…", "subject_ref": "…"}. With anapichannel:409and no record is created. - GET /v1/nafath/transactions/{id} — polls:
waiting→simulated_approved/simulated_rejected(sandbox) orexpiredafter the window.summary.verifiedis alwaysfalsein the sandbox and no identity data is ever returned. - GET /v1/tenants/{tid}/nafath/transactions
Signed-token verification (asymmetric algorithms only, exp required, ID and transaction must match) is built in octa_health/nafath.py and is wired to the api adapter only after the contract defines the token.
SeHE documents
generated --submit--> exported (file) | registered (sandbox) | 409 (api) generated | exported | registered --deprecate--> deprecated (local; Metadata Update not built)
POST /v1/tenants/{tid}/hie/documents — builds an HL7 CDA R2 document (narrative level) plus ebRIM 3.0 SubmitObjectsRequest from a FHIR R4 Bundle.
{"external_ref": "enc-55:summary", "created_by": "user:12", "kind": "summary" | "lab" | "imaging",
"patient": {"national_id": "…", "ref": "MRN-9"}, "language": "ar-SA",
"fhir_bundle": {"resourceType": "Bundle", "entry": [Patient, Practitioner, Condition | Observation | DiagnosticReport …]},
"metadata_values": {"classCode": {"code": "…", "scheme": "…"}} // optional, for IHE-tool testing only
}
summary.pending[] lists every Saudi-platform value that is not published (IS0106 template ids, document type codes, metadata value sets, assigning authority…). Those elements carry nullFlavor or are omitted — never guessed.
- GET /v1/tenants/{tid}/hie/documents · GET /v1/hie/documents/{id}
- GET /v1/hie/documents/{id}/cda — the CDA XML (contains PHI by nature; audit-logged).
- GET /v1/hie/documents/{id}/package — zip:
cda.xml,submit-objects.xml,iti41-request.mtom,iti41-content-type.txt,README.txt. - POST /v1/hie/documents/{id}/submit — ITI-41 over the channel.
- POST /v1/hie/documents/{id}/deprecate —
{"actor": "…", "reason": "…"} - POST /v1/tenants/{tid}/hie/query — ITI-18 FindDocuments:
{"patient_ref": "…"}(sandbox: the facility's simulated registry). - POST /v1/tenants/{tid}/hie/retrieve — ITI-43:
{"document_unique_id": "…"}→ CDA file.
Built from the IHE ITI Technical Framework and HL7 CDA R2: ITI-41 (SOAP 1.2 + MTOM/XOP), ITI-18, ITI-43, standard metadata UUIDs. Not built: ITI-42, ITI-62, DSUB, PDQ (IS0001), XDS-I.b.
Mawid and Seha Virtual Hospital
Profiles only: api mode, every field PENDING, 409 channel_not_ready on sync. No joining method is published.
Audit
- GET /v1/tenants/{tid}/audit · GET /v1/tenants/{tid}/audit/verify →
{ok, entries, head}— hash-chained per facility; any later edit or deletion breaks the chain. - GET /v1/records/{id}/audit
Webhooks
POST /v1/webhook — {"url": "https://…"} → returns the signing secret once (whsec_…).
| Event | When |
|---|---|
sickleave.updated | Any sick-leave status change, and reminder: "registration_overdue" once |
wasfaty.status | Any prescription status change |
nafath.result | Transaction started, finished or expired |
hie.document.generated · hie.document.submitted · hie.document.deprecated | SeHE document lifecycle |
Headers: X-Octa-Event, X-Octa-Delivery, X-Octa-Timestamp (ms), X-Octa-Signature = hex HMAC-SHA256 of {timestamp}.{raw body} with the secret. Retries with back-off (1m, 5m, 15m, 1h, 6h) then failed. The body is {"event", "tenant_id", "tenant_ref", "record": {…same shape as GET, no PHI…}}.
Agencies
GET /v1/agencies — every profile with published[] facts and their sources, pending_fields[], field_sources, api_ready. Sources are the numbered references S1..S19 and S35 of research document 48.
Subscriptions
- An app with no portal account is internal (MedCore): no limits.
- External customers sign up at
/app; packages of 3, 6 or 12 months only (no monthly plan), activated by/provision(HMAC-signed, same contract as the ZATCA and Bank gateways) or/billing/webhook. - Unit: a facility with at least one non-sandbox channel. Sandbox is always free.
- Plans and every number live in
pricing.jsononly (GET /portal/plans). Each plan lists the agencies allowed on real channels.
Python client
clients/octa_health_client.py — OctaHealthClient(base_url, api_key) with one method per endpoint, HealthGatewayError (.status, .code, .retryable), and verify_webhook(secret, headers, body).