The guideline another system follows to integrate with the PocketHealth EMR and HealthGrid. It covers only what is finished, and says for each part where it runs and who can call it.
Last updated 9 November 2026
Everything on this page runs in the integration build and is not in production yet. Hosts, ids, keys and tokens in the examples are synthetic.
01
Overview
Integration build
Not in production
The platform has two APIs. The PocketHealth EMR holds the records. HealthGrid is the interoperability layer: it reads from the EMR on a participant’s behalf, through the EMR’s own API, as a registered integration client.
EMR integration routesIntegration clients
Twelve EMR routes, each behind one capability, for a registered integration client acting for an organization that granted it access. See Authentication and EMR integration routes.
HealthGrid routesHealthGrid operators only
The operator session, participant bindings, an organization’s users as JSON and as FHIR, staff registration requests, patient registration and a patient’s record. Today they answer HealthGrid’s operators only: participant systems cannot sign in to HealthGrid yet. See HealthGrid routes, FHIR, Staff registration, Patients and Records.
Where it runsIntegration build
The integration build. Nothing on this page is in production yet, so no real host is published here.
Getting a clientSelf-service planned
There is no self-service sign-up yet. The platform team registers a client’s public key and records each organization’s grant. A developer platform, console and SDK are planned: see Status and roadmap.
Conventions
Requests and answers are JSON over HTTPS, except the token request, which is form-encoded, and HealthGrid’s FHIR answers, which are application/fhir+json.
Ids are UUIDs, and a malformed path id is refused with 400. HealthGrid’s Practitioner and Patient reads and $everything answer not-found instead.
JSON bodies are checked against the fields each route declares: an undeclared top-level field is refused with 400. The form-encoded token request reads only the parameters it names.
Identifiers and names travel in request bodies, never in URLs: that is why $match, $lookup-by-identifier and the cross-reference are POSTs. Keep them out of Idempotency-Key values and logs too.
Send FHIR operation names as written: $match, not %24match. A percent-encoded $ names another path, which answers 404.
Typed contracts
The request and answer shapes on this page are the EMR’s typed contracts (@medichain/contracts, HG-047). That package is internal to the PocketHealth repository today; a published SDK is planned (HG-051).
Ready-made requests
The repository’s Bruno collection, docs/api/bruno/healthgrid-platform/, has a documented, tested request for the token endpoint, the workforce reads and every HealthGrid route on this page, with their refusals. yarn api:collections runs it on a disposable stack with synthetic data.
02
Authentication
Integration build
Integration clients
The EMR follows the Backend Services profile of SMART App Launch 2.2. Your system signs a short JWT with its own private key (private_key_jwt) and exchanges it for a short-lived access token. There is no shared secret and no refresh token.
1. Keys and registration
Generate a key pair: EC P-384 to sign with ES384, or RSA of at least 2048 bits to sign with RS384. The private key never leaves your system.
Your public key is registered by value, as a JWK with a kid. Registering a JWK Set URL instead is planned with the developer platform.
If the JWK carries use, key_ops or alg, they must allow verifying with your algorithm.
Each organization you act for is a grant: the capabilities you may use there and the purposes of use (TREAT, HOPERAT) it allows. A client holds one active grant per organization.
2. Discovery
GET /.well-known/smart-configuration on the EMR names the issuer and the token endpoint. It answers 404 while integration clients are switched off.
Required: one of your registered keys. Keys come only from the registry, so a jku, x5u or x5c header is refused, and so is crit.
iss, sub
Both your client_id.
aud
The token URL or the issuer, as one string. An array is refused, even one holding the right value.
iat, exp, nbf
Whole seconds. exp after iat and at most 300 seconds later; nbf is optional and must precede exp. The EMR allows 60 seconds of clock skew.
jti
Unique for each assertion, up to 255 printable characters. An assertion the EMR has already seen is refused.
extensions.hl7-b2b
Whom and why you ask, shaped like UDAP’s B2B extension: version"1"; organization_id is urn:uuid: and the EMR organization id; purpose_of_use holds exactly one code, urn:oid:2.16.840.1.113883.5.8#TREAT or #HOPERAT; participant_id is 1 to 255 printable characters naming the participant you act for.
Use TREAT for patient flows and HOPERAT for workforce and organization reads, as HealthGrid does. The EMR checks that the organization’s grant allows the purpose you sign.
Signing with jose (Node)js
import { randomUUID } from 'node:crypto';
import { importPKCS8, SignJWT } from 'jose';
const tokenUrl = 'https://emr.example.invalid/integration/oauth2/token';
const key = await importPKCS8(process.env.CLIENT_PRIVATE_KEY_PEM, 'ES384');
const now = Math.floor(Date.now() / 1000);
const assertion = await new SignJWT({
extensions: {
'hl7-b2b': {
version: '1',
organization_id: 'urn:uuid:00000000-0000-4000-8000-00000000e101',
purpose_of_use: ['urn:oid:2.16.840.1.113883.5.8#HOPERAT'],
participant_id: '00000000-0000-4000-8000-00000000e201',
},
},
})
.setProtectedHeader({ alg: 'ES384', typ: 'JWT', kid: 'example-key-1' })
.setIssuer('example-integration-client')
.setSubject('example-integration-client')
.setAudience(tokenUrl) // one string, never an array
.setIssuedAt(now)
.setExpirationTime(now + 240) // at most 300 seconds after iat
.setJti(randomUUID())
.sign(key);
The capabilities you ask for, separated by spaces. You receive the ones the organization’s grant holds; if it holds none of them, the answer is invalid_scope.
client_id
Optional. If you send it, it must name the client that signed the assertion.
Send each parameter once, form-encoded. A client_secret or an Authorization header beside the assertion is invalid_request.
The token lives 300 seconds and is bound to one organization, one participant, one purpose and the granted scope. Treat it as opaque. There is no refresh token: sign a new assertion when the token nears expiry.
invalid_client · 401
Every authentication failure: a bad signature, an unknown key, an expired or replayed assertion, a suspended client, a client_id naming another client, or integration clients switched off.
invalid_request · 400
A missing grant_type or scope, a repeated parameter, a body that is not form-encoded, a missing or malformed hl7-b2b extension, or a second credential.
unsupported_grant_type · 400
A grant type other than client_credentials.
invalid_grant · 400
No active grant for the organization, or a purpose the grant does not allow.
invalid_scope · 400
Nothing you asked for is granted, or the scope is malformed.
temporarily_unavailable · 429
More than 60 token requests in a minute. Wait for Retry-After.
A refusal’s body is only { "error": "<code>" }. The precise reason stays in the EMR’s log.
Only the routes opened to integration clients accept the token. Every other route answers 401.
X-Organization-Id is optional. If you send it, it must name your token’s organization; any other value is refused with 403.
Each call re-reads your client and its grant, so a suspended client or a revoked grant stops a live token at its next call.
Switching integration clients off on the EMR refuses every client.
401
“Integration client authentication failed.” A missing, expired or invalid token, a route not open to clients, or a client that is not active.
403
“The integration client may not perform this action.” The scope lacks the route’s capability, a header names another organization, the grant does not allow the token’s purpose, or the organization is not active.
Client behaviour we recommend
Reuse a token until shortly before it expires. HealthGrid’s own client replaces its tokens 30 seconds early.
Ask for one token at a time per organization, participant and purpose.
After a 401 from a route, get a new token and retry once.
Retry a write only with an Idempotency-Key (see Idempotency).
Never log a token, an assertion or a key.
03
EMR integration routes
Integration build
Integration clients
Twelve EMR routes are open to integration clients, opened one by one, each behind one capability. The capability must be in your token’s scope and in the organization’s grant. Paths are relative to the EMR’s base URL, which is its issuer.
The routes are built and tested in the integration build; the HG-039 tracker row that opens them is still in progress.
workforce.read
The organization display, the members list and the workforce list.
workforce.manage
Asking an organization to register one person as staff, which its admin approves, and reading that request’s progress.
patients.read
$match, the FHIR patient read, the identifier cross-reference and an artifact’s content.
patients.create
Patient intake, and registering a patient with your organization.
exchange.export
Producing an exchange artifact. It needs patients.read as well.
Every route acts only in your token’s organization. A path, header or body naming another organization is refused: with 403, or with 404 where the route never confirms that an organization exists.
Workforce and organization
GET/organizations/{organizationId}/display
Capability
workforce.read
The organization’s display fields: its EMR id, name, type and status, and nothing else.
Your token’s organization only. Another organization’s id and an unknown id get the same 404. type is one of hospital, clinic, government, laboratory, pharmacy, insurance, private_practice or other.
The organization’s members: each membership with the person who holds it, most recently joined first.
Query: role, isActive, status (pending, active, suspended, terminated), limit (1 to 100, default 20) and offset. meta.total counts the rows on this page.
Each member comes with their name, roles and status, and with no email address, phone number or membership history: the EMR answers an integration client only what HealthGrid reads. Keep names out of logs.
GET/organizations/{organizationId}/workforce
Capability
workforce.read
Practitioner affiliations, oldest first, as a bare array. They name no person: join them to members by userId.
Query: status (active, suspended, ended), role, locationId, healthcareServiceId and userId.
licence is { system, value, status: "verified" } while the practitioner’s PRC licence is verified and current, and null otherwise. Its system is https://fhir.medichain.ph/Identifier/prc-license-number.
Asks your organization to register one person as staff. An owner or admin of the organization decides; nothing is issued or sent.
One person, never a code
The request files a pending record for the organization’s admin. No code exists until an admin approves, and the code is shown to that admin once: the answer to this route, its status read and every other route of yours never carry it. HealthGrid calls this route for a participant (see Staff registration).
organizationId is your token’s organization; another is refused with 403. email is the person’s address, in the body only. roles holds 1 to 10 role names among those the organization’s grant lets your client request (allowed_roles); never owner, admin, manager or the patient role. Any other field, expiresInDays included, is refused with 400.
outcome is requested with the request’s id, statuspending and its decision deadline, 14 days after the request; request_pending (the address is already waiting; its requestId only when the open request is your own client’s for this participant), invitation_pending (it holds an open invitation) or already_a_member. The last three write nothing. An address that already has a MediChain account is answered as a new one.
Refusals: 403 role_not_grantable or role_outside_grant; 422 unknown_role or invalid_email; 429 pending_limit or daily_limit, with Retry-After (the minute limit answers 429 too). error.code names the reason, and the sentence repeats no address or role.
Limits: 10 requests a minute for each client and organization, at most 50 waiting at once and 100 in any 24 hours.
GET/v1/staff-registration-requests/{id}
Capability
workforce.manage
The progress of a request your client made for its participant, by the id its answer gave, and nothing else.
status is pending, approved, joined, declined, expired or lapsed (see Staff registration). expiresAt is the decision deadline while pending and the code’s expiry while approved, and absent otherwise. Another client’s or participant’s request, and an id nobody holds, get the same 404.
Patients
POST/patients/$match
Capability
patients.read
Finds candidates for a partly known person before anyone registers them. It looks across organizations and answers demographics only.
Body fields: firstName, middleName, lastName, names, birthDate, gender, identifiers, telecoms, onlyCertainMatches and limit (1 to 25). The EMR answers at most 25 candidates. names holds every name the caller has (use, family, given, suffix); an integration client sends it, and onlyCertainMatches: true asks for the one certain match alone.
For a staff caller, a query too thin to run is refused with 400: add a family name of at least 3 characters, a family name of at least 2 characters with a birth date, a PhilHealth or PhilSys number, or a phone number of at least 7 digits.
A candidate never echoes an identifier or a contact detail. For a staff caller grade is certain, probable or possible (an integration client sees certain or probable only, below); inActiveOrganization says whether your organization already holds the patient.
Its own budget: 30 requests a minute and 300 an hour.
An integration client is answered by the registration rule instead, and its answer adds decision. Its $match needs a first name, a surname and a full birth date (YYYY-MM-DD), or it is refused with 400. The same first name, surname and birth date is the same person; a PhilHealth or PhilSys number supports the match and carries a changed surname. A candidate is graded certain (score 1) or probable (score 0.8) only. The decision is link with the patientId of one certain match, create when nobody fits, review with a reason (namesakes or held-number) when a person decides, or not-found for a number held outside your organization by a patient the request does not agree with (one that agrees is a link).
names is required, with at least one name. The other fields are optional and FHIR-shaped: identifiers, telecoms, gender, birthDate, addresses and more.
Leave organizationId out and the patient is filed under your token’s organization. Any other organization is refused.
system is philhealth, philsys or the pinned assigning-system URI; value is 4 to 64 characters; purpose is treatment, record_exchange or identity_verification.
An unknown number and a number held outside your organization both answer { "data": null }.
Every attempt is recorded in the governance audit, without the number.
The exact bytes of an available artifact, re-verified against their checksum before they are sent.
200 OKhttp
HTTP/1.1 200 OK
Content-Type: application/fhir+json
Content-Length: 18342
X-Artifact-Checksum: sha256:<hex digest>
Cache-Control: no-store
<the stored bytes: a FHIR Bundle>
Verify the bytes against X-Artifact-Checksum and relay them unchanged.
404 for an unknown artifact, one that is not available, or a patient outside your organization; 403 when your organization has no basis to disclose it.
Each read is recorded as a disclosure.
04
HealthGrid routes
Integration build
HealthGrid operators only
HealthGrid’s routes live under /api/v1. Today they answer HealthGrid’s operators: people whose MediChain account holds the system.healthgrid.operate capability. Participant systems cannot sign in to HealthGrid yet; that waits for participant certificates (HG-010) and HealthGrid’s FHIR API with SMART Backend Services (HG-014).
An organizationId or participantId here is HealthGrid’s participant id. The EMR organization stays behind the participant’s binding: HealthGrid stores the binding, but none of the EMR organization’s fields and no person’s name or email.
POST/api/v1/auth/operator-session
Who
No session needed
Starts or renews an operator session with a MediChain sign-in.
Requesthttp
POST https://healthgrid.example.invalid/api/v1/auth/operator-session
Content-Type: application/json
{
"idToken": "<Firebase ID token of a MediChain sign-in>"
}
One active binding per participant and per EMR organization. Binding again after an end adds a version, and each change writes an audit row with no personal data.
Refusals: 404 participant_not_found, 409 participant_already_bound or emr_organization_already_bound.
GET/api/v1/participants/{participantId}/binding
Who
Operators
The participant’s active binding, with the EMR organization’s display fields read live from the EMR.
organization comes from the EMR’s organization display route, read for HOPERAT. HealthGrid stores none of it, so a renamed organization shows its new name at the next read.
Refusals: 404 participant_not_found; 403 participant_not_bound; and when the EMR refuses or fails, 403 emr_refused, 503 emr_unavailable or 502 emr_failed.
No email, phone or birth date is in the answer. licence is { system, value } only once the practitioner’s PRC licence is verified.
practitionerRole is the affiliation in force, or null for a member with none.
An unbound participant and an unknown one both answer 403 participant_not_bound, before the EMR is asked. EMR refusals map as on the binding read.
05
FHIR
Integration build
HealthGrid operators only
HealthGrid answers an organization’s practitioners as FHIR R4 on PH Core 0.2.0, the pinned draft build of the Philippine Core profiles, and its patients and their records the same way (see Patients and Records). Answers are application/fhir+json, and every refusal is an OperationOutcome.
GET/api/v1/fhir/PractitionerRole
Who
Operators
The participant’s organization’s roles as a searchset Bundle, with the Practitioners when you ask.
Requesthttp
GET https://healthgrid.example.invalid/api/v1/fhir/PractitionerRole
?organization=Organization/00000000-0000-4000-8000-00000000e201
&active=true
&_include=PractitionerRole:practitioner
Authorization: Bearer <HealthGrid access token>
organization is required: Organization/<participant id>, or the bare id. active is true or false. _include serves PractitionerRole:practitioner only.
Any other parameter is refused with 400, as an OperationOutcome.
total counts the matching roles, not the included Practitioners. fullUrls are built from the host you called.
GET/api/v1/fhir/Practitioner/{id}
Who
Operators
One member of the participant’s organization as a Practitioner. {id} is the EMR user id.
An operator names the participant with ?organization=Organization/<participant id>; without it the answer is 400 with issue code required.
An id nobody holds and one held outside the organization get the same 404:
404 Not Foundjson
{
"resourceType": "OperationOutcome",
"issue": [
{
"severity": "error",
"code": "not-found",
"diagnostics": "The practitioner was not found."
}
]
}
What the resources carry
Practitioner
The PH Core Practitioner profile; the EMR user id under https://fhir.medichain.ph/Identifier/practitioner; the name on file as text; active. A verified PRC licence adds an official identifier under https://fhir.medichain.ph/Identifier/prc-license-number and a qualification issued by the Professional Regulation Commission. Never a telecom, an address, a birth date or a gender.
PractitionerRole
The PH Core PractitionerRole profile; references to the Practitioner and the participant’s Organization; the role as code text; the specialty as text, when there is one; the affiliation’s period; active while the affiliation is active.
Validation
HG-041’s run validated the Practitioner, PractitionerRole and Bundle against the pinned PH Core 0.2.0 profiles with the HL7 validator, with no error.
With RBAC-011, PractitionerRole.code also carries HL7’s practitioner-role coding for doctors, nurses and pharmacists. See Role codes.
OperationOutcome issue codes
401
login
403
forbidden
404
not-found
405
not-supported: a HEAD request
409
multiple-matches when a person must choose a patient, conflict while the same Idempotency-Key is still being processed
413
too-long: a body past 100 kB
429
throttled
503, 504
transient
Other 5xx
exception, with a fixed sentence
Other 4xx
invalid, or required for a missing participant
06
Staff registration
Integration build
HealthGrid operators only
A participant asks its organization, through HealthGrid, to register staff (HG-042). The organization’s own admin approves or declines the request in the EMR. HealthGrid creates no account, delivers no code and holds none.
Today these routes answer HealthGrid’s operators acting for a bound participant: participant systems cannot sign in to HealthGrid yet, and the same routes will take a participant’s own key once that sign-in opens (HG-049).
You request one person with their address and the roles you ask for. The EMR files the request for the organization’s owners and admins. Nothing is sent to the person.
An owner or admin of the organization approves or declines it in the EMR, within 14 days. Approval issues one code bound to the person’s address and roles, and shows it to that admin once.
That admin gives the code to the person. The code the person receives is the one your organization’s admin gives them: HealthGrid and your system never see it, and no system emails it.
The person completes MediChain’s sign-up with the code (or, with an account already, joins with it). A clinical role still goes through licence verification (KYC-001): an approved request vouches for no licence.
email is the person’s address, in the body only. roles holds 1 to 10 role names. Any other field is refused with 400: expiresInDays is gone, because the invitation’s lifetime is the approving admin’s choice.
Only the roles the organization’s grant to HealthGrid lists (allowed_roles) can be requested, and none an organization admin could not grant: never owner, admin, manager or the patient role.
202 requested means a request was filed, and registrationId is its id. expiresAt is the decision deadline, 14 days after the request, not an invitation’s expiry.
A 200 answers a request that wrote nothing: request_pending (this address is already waiting; registrationId is the open request’s id when your participant made it), invitation_pending (the address already holds an open invitation) or already_a_member.
With an Idempotency-Key, a retry answers the first result, requested again. Without one, the same address sent again is request_pending.
An id the participant’s organization does not hold answers 404 registration_not_found, whether or not it exists elsewhere.
The six states
pending
Waiting for an owner or admin. expiresAt is the decision deadline.
approved
Approved: the organization holds the person’s code and it is not yet used. expiresAt is the code’s expiry.
joined
The person used the code and is a member.
declined
An owner or admin declined it. Who decided, and why, are not sent.
expired
Nobody decided within 14 days.
lapsed
Approved, but the code was revoked or ran out unused.
declined, expired, joined and lapsed carry no expiresAt. After approved, you learn only joined or lapsed: never the code, the address, the roles, or whether the person already had an account.
Deadlines
The request’s decision deadline is 14 days, and expired follows if nobody decides.
The code’s own lifetime is 1, 7 or 30 days, which the approving admin picks (7 by default). A participant cannot ask for one: a request with an expiry is refused with 400.
Limits
The EMR limits an organization to 10 requests a minute, 50 waiting at once and 100 in any 24 hours. Past a limit HealthGrid answers 429 request_limit with Retry-After in whole seconds, when the EMR named one, and nothing is requested.
429 Too Many Requestshttp
HTTP/1.1 429 Too Many Requests
Retry-After: 86400
Content-Type: application/json
{
"statusCode": 429,
"reason": "request_limit",
"message": "This organization has too many staff registration requests. Try again later."
}
No account oracle
An address that already has a MediChain account is answered exactly as a new address: the same outcome, the same fields and the same states. No route says whether an account exists, and no route reads a code by its value or its id, so nothing tells the two apart.
Joining with the code
A new address completes MediChain’s sign-up with the code your organization’s admin gives it. Someone who already has an account signs in and joins with it through the EMR’s own route, as themselves: neither HealthGrid nor an integration client can call it.
Requesthttp
POST https://emr.example.invalid/v1/registration-codes/use
Authorization: Bearer <the person’s Firebase ID token>
Content-Type: application/json
{
"code": "<the code your organization’s admin gave you>"
}
The code travels in the body, never the path, and the account is the signed-in caller, never a field. The code is spent and the membership made in one transaction; a refusal spends nothing.
A clinical role the code would confer must match the account’s credential, or the code is refused unspent.
Refusals are sentences written for the person. Every code that cannot be used (unknown, already used, withdrawn, expired, or bound to another address) gets the same one, so no answer confirms that a code exists; an account that already has a membership there is told so.
Ten failed tries in five minutes, and five wrong codes in fifteen minutes lock the account and its address (twenty its network) with a 429 and retryAfter, even for the right code.
Refusals
role_outside_grant · 403
The organization has not let HealthGrid grant that role.
role_not_grantable · 403
A staff registration never grants the patient role.
unknown_role · 422
Not a role the organization has.
invalid_email · 422
The EMR cannot send an invitation to that address.
idempotency_key_reused · 422
The key was already used with a different request.
registration_in_progress · 409
A request with this key is still being processed. Retry later with the same key.
request_limit · 429
The organization has too many staff registration requests. Retry after Retry-After.
request_failed · 503
The EMR could not record the request, and changed nothing. Try again later.
registration_not_found · 404
The organization has no such registration.
participant_not_bound · 403
The participant has no binding: refused before the EMR is asked.
The EMR refused HealthGrid that organization, could not answer, or answered what HealthGrid cannot read.
07
Patients
Integration build
HealthGrid operators only
A participant registers patients into its organization through HealthGrid, as FHIR R4 on PH Core 0.2.0, match first (HG-043). The EMR’s matching decides, never HealthGrid, so the same person is not registered twice.
The same first name, surname and birth date
One patient is the same person: they are registered with your organization and returned: 200.
Nobody
The EMR creates the patient in your organization: 201.
A person decides
Nothing is written. The candidates come back for a person to choose, with the reason: 409 multiple-matches. The reason is that a number disagrees with the patient who holds it, or that two or more patients fit.
A number held outside your organization
404 not-found, when the registration does not agree with that patient (another first name or birth date). Nothing is created and the holder is not named: a person resolves it. A registration that agrees (the same first name and birth date) is registered with your organization: 200.
A first name, a surname or a birth date missing
400 required, naming what to add. Both a match and a registration need all three, and a number cannot stand in for them.
The rule: the same first name, surname and birth date
Send a first name, a surname and a full birth date (YYYY-MM-DD). A PhilHealth or PhilSys number supports the match and never decides alone. It carries a changed surname: the same number, first name and birth date under a married surname is the same patient, and the patient keeps the surname already on file. When the number is held under another first name or another birth date, or two numbers point at two patients, a person decides: 409, with the held-number sentence. The same name and birth date under another number is a namesake: a person decides too, with the namesakes sentence.
What counts as the same name
Case, spaces, accents and ñ, and punctuation do not make another person, nor does Ma. for Maria in a first name, Sto. for Santo and Sta. for Santa, nor a space inside a particle (de la Cruz and dela Cruz). A nickname, a spelling variant, or a dropped particle or given name is another name. Two different suffixes (Jr, Sr, II) send a registration to a person. So do two middle names that differ, but only when the registration carries no number the patient holds: a holder with the same first name, birth date and number is linked whatever the middle names.
POST/api/v1/fhir/Patient/$match
Who
Operators
Who the EMR’s matching finds for a person, as a searchset with each candidate’s score and grade.
A Parameters with resource, the Patient to match (required), onlyCertainMatches (default false) and count. The EMR answers 25 candidates at most. The Patient needs a first name, a surname and a full birth date.
A candidate is demographics only, id, name, gender and birthDate, with search.score and the match-grade extension: certain (the same first name, surname and birth date; one patient, to link) or probable (a person decides, with a score of 0.8). A candidate graded below certain never shows a score of 0.9 or more.
Nobody found: total: 0 and no entry.
A Patient without a first name, a surname or a full birth date is 400 required, naming what to add. A number alone is not enough.
Each candidate the EMR answers is recorded in that patient’s access history: ask for no more than you need.
Idempotency-Key is required: 8 to 128 letters, digits, _, -, . or :, fresh for each patient, never a name or a number. A retry with the same key gets the same patient, answered 200 once the first attempt has registered them.
HealthGrid reads identifier, name, telecom, gender and birthDate (a full date), and nothing else: the organization is your binding’s, never a managingOrganization. A modifier it cannot register (implicitRules, modifierExtension, a death, active: false, link) is refused rather than dropped. A first name, a surname and a full birth date are required: without one the answer is 400 required, before the EMR is asked.
A PhilHealth or PhilSys number is filed under its PII-011 system, http://philhealth.gov.ph/fhir/Identifier/philhealth-id or http://philsys.gov.ph/fhir/Identifier/philsys-id, whatever system it came under, https://www.philhealth.gov.ph included.
The NHDR guide’s http://nhdr.gov.ph/fhir/Identifier/philhealth-id, with the number written with its dashes (NN-NNNNNNNNN-N), is the same PhilHealth number.
201 and 200 answer the EMR’s own PH Core Patient, with its Location. A 200 for a married surname answers the patient as the EMR holds them: the registration never rewrites the surname.
409 Conflict: namesakesjson
{
"resourceType": "OperationOutcome",
"issue": [
{
"severity": "error",
"code": "multiple-matches",
"diagnostics": "Existing patients have this first name, surname and birth date, and nothing here tells which one this is or whether this is someone new. Nothing was created: a person at this organization decides in the EMR, then the registration is sent again."
},
{
"severity": "information",
"code": "multiple-matches",
"details": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/match-grade",
"code": "probable"
}
],
"text": "Patient/00000000-0000-4000-8000-00000000e302"
},
"diagnostics": "Patient/00000000-0000-4000-8000-00000000e302 matched with score 0.8 (probable)."
}
]
}
The first issue says nothing was created and why a person decides. Then one information issue for each candidate: its reference in details.text, its grade coded in details.coding, its score in diagnostics. Every candidate here is probable, scored 0.8. Ids, grades and scores only: decide in the EMR. This answer, for the same first name, surname and birth date under another number or with another middle name, begins with the namesakes sentence.
409 Conflict: a number heldjson
{
"resourceType": "OperationOutcome",
"issue": [
{
"severity": "error",
"code": "multiple-matches",
"diagnostics": "A patient of this organization holds a PhilHealth or PhilSys number this registration carries, and the rest of the registration does not agree with that patient. Nothing was created: a person at this organization checks the number and the patient in the EMR, then the registration is sent again."
},
{
"severity": "information",
"code": "multiple-matches",
"details": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/match-grade",
"code": "probable"
}
],
"text": "Patient/00000000-0000-4000-8000-00000000e302"
},
"diagnostics": "Patient/00000000-0000-4000-8000-00000000e302 matched with score 0.8 (probable)."
}
]
}
This one is for a number your organization’s patient holds while the rest of the request does not agree with that patient: another first name or another birth date. It begins with the held-number sentence and lists the holder.
400 Bad Requestjson
{
"resourceType": "OperationOutcome",
"issue": [
{
"severity": "error",
"code": "required",
"diagnostics": "A patient is registered by first name, surname and full birth date: add a full birth date (Patient.birthDate, as YYYY-MM-DD)."
}
]
}
A first name, a surname or a full birth date missing. The sentence names only what to add (here the birth date alone), and repeats nothing you sent.
404 Not Foundjson
{
"resourceType": "OperationOutcome",
"issue": [
{
"severity": "error",
"code": "not-found",
"diagnostics": "No patient this organization may see holds that PhilHealth or PhilSys number, so the patient cannot be registered here. Nothing was created: a person at this organization checks the number with the patient and resolves it in the EMR."
}
]
}
A PhilHealth or PhilSys number held by a patient your organization may not see, where the registration does not agree with that patient. Nothing is created, and neither the number nor its holder is named. A registration that agrees with the holder (the same first name and birth date) is registered with your organization instead: 200.
GET/api/v1/fhir/Patient/{id}
Who
Operators
One of your organization’s patients, as the EMR’s own PH Core Patient. {id} is the EMR’s patient id.
An id nobody holds, another organization’s patient and an id that is no EMR id get the same 404:
404 Not Foundjson
{
"resourceType": "OperationOutcome",
"issue": [
{
"severity": "error",
"code": "not-found",
"diagnostics": "The patient was not found."
}
]
}
Refusals
400 invalid
No Idempotency-Key, a body that is not JSON, or a Patient HealthGrid cannot read. diagnostics names the element and the shape it wants, never the value.
400 required
A match or a registration without a first name, a surname or a full birth date (diagnostics names what to add), or an operator that named no participant.
404 not-found
A PhilHealth or PhilSys number held by a patient your organization may not see, on a registration that does not agree with that patient; an id nobody holds, or another organization’s patient, on a read.
403 forbidden
An unbound participant, or one whose organization has not granted HealthGrid its patient capabilities.
409 multiple-matches, conflict
A person must choose; or the same key is still being processed.
413 too-long
A body past 100 kB.
422 invalid
The same key, already used with another body.
503 transient, 502 exception
The EMR could not answer, or answered what HealthGrid cannot read.
08
Records
Integration build
HealthGrid operators only
A participant fetches a patient’s record through HealthGrid (HG-044): it finds the patient by a PhilHealth or PhilSys number, then receives the EMR’s custody-tracked export or transition-of-care summary as a FHIR Bundle, byte for byte. The EMR decides and records each disclosure.
POST/api/v1/fhir/Patient/$lookup-by-identifier
Who
Operators
The patient of your organization who holds a PhilHealth or PhilSys number, as a reference.
system is a valueUri or a valueString: PhilHealth or PhilSys, by its PII-011 system, its short key (philhealth, philsys) or an address naming the authority. Any other system is 400: no other number finds a patient across organizations.
value is a valueString of 4 to 64 characters. The number never reaches a URL, and HealthGrid keeps it nowhere.
A number nobody holds and a patient outside your organization get the same 404 not-found.
The answer is a reference only. Read the patient with Patient/{id}, and their record with $everything.
HTTP/1.1 200 OK
Content-Type: application/fhir+json
Content-Length: 4922
Content-Digest: sha-256=:<base64 SHA-256 of the body>:
Cache-Control: no-store, no-transform
<the EMR’s bytes: a FHIR Bundle>
kind is export (the default) or summary. FHIR’s own $everything parameters (start, end, _since, _type, _count) are refused with 400: the EMR produces the record whole.
Idempotency-Key is optional. A retry with the same key reuses the artifact, and one key serves both kinds. Without one, every request is a production and a disclosure of its own.
An id nobody holds, another organization’s patient and an id that is no EMR id get the same 404 not-found.
What a record holds
kind=export
The EMR’s record export, a collection Bundle: the Patient, each encounter with its note as a Composition and its vital signs as Observations, and the patient’s problems, allergies and immunizations.
kind=summary
The transition-of-care summary, a document Bundle: a Composition of LOINC 18761-7 first, then the Patient, the composing organization as author and custodian, the encounters, active problems, allergies, immunizations and the latest vital sign of each kind.
The release rule
Only what the EMR’s release rule (PAT-012) allows: active records, final or amended, of normal confidentiality.
Through HealthGrid
Only the clinical entries recorded in the participant’s own organization, until disclosure policy (HG-016) widens it. Another organization’s patient is not found at all.
Its ids
The EMR’s own. The record is relayed unchanged, so its references name the EMR’s patient, encounters and organization, not the participant.
Verify the bytes
HealthGrid compares the bytes with the EMR’s own checksum before the first one goes out, then relays them unchanged with Content-Digest (RFC 9530) and Cache-Control: no-store, no-transform, so nothing between may re-encode them. Check the digest before you parse:
Verifying Content-Digest (Node)js
import { createHash } from 'node:crypto';
const response = await fetch(url, { headers });
const body = Buffer.from(await response.arrayBuffer());
const digest = `sha-256=:${createHash('sha256').update(body).digest('base64')}:`;
if (response.headers.get('content-digest') !== digest) {
throw new Error('The record did not arrive as HealthGrid sent it.');
}
const bundle = JSON.parse(body.toString('utf8'));
A checksum that is missing, malformed or wrong, a record past 16 MiB, or one not sent whole within 30 seconds is 502 exception, and nothing is relayed.
The EMR records the production and every read in the patient’s access history, naming HealthGrid’s client. HealthGrid’s message log keeps the artifact, its SHA-256, its length and the outcome, never a byte of the record.
HEAD is refused
A HEAD answer has no body, but on these routes the request would still reach the EMR, which records the read. So HealthGrid refuses HEAD on every route that would call the EMR, before anything is asked: 405, with Allow naming the methods the route does answer (GET for these reads). Use GET.
Refusals
400 invalid
Another system, a malformed Parameters, an unknown parameter or kind, or a malformed key. Never the value sent.
403 forbidden
An unbound participant, or the EMR refused HealthGrid.
404 not-found
A number nobody holds, an id nobody holds, an id that is no EMR id and another organization’s patient, alike.
405 not-supported
HEAD.
409 conflict, 422 invalid
The key is still being processed; the key was already used with another request.
502 exception
The EMR’s artifact was not available, its bytes could not be verified, or the record was too large or too slow. Nothing was relayed.
503 transient
The EMR could not answer. Retry with backoff.
09
Errors
Integration build
Each surface has its own refusal shape. HealthGrid’s own sentences, and the EMR’s refusals of integration clients, are fixed and never repeat a value you sent.
EMR routes
{ "statusCode", "message", "error" }. A validation failure lists its messages as an array in message.
EMR token endpoint
{ "error": "<code>" }, as OAuth 2.0 defines it.
HealthGrid refusals
Its own refusals, for participant bindings, interop reads, staff registration and the operator sign-in, answer { "statusCode", "reason", "message" }: switch on reason. Other errors, such as a validation failure, use NestJS’s standard body with statusCode and message.
{
"statusCode": 403,
"reason": "participant_not_bound",
"message": "This participant is not bound to an EMR organization."
}
HealthGrid’s reasons
participant_not_found · 404
The participant does not exist.
participant_not_bound · 403
The participant has no active binding to an EMR organization.
participant_already_bound · 409
End the participant’s binding first.
emr_organization_already_bound · 409
That EMR organization is bound to another participant.
emr_refused · 403
The EMR did not release the organization’s data to HealthGrid.
emr_unavailable · 503
The EMR could not answer. Try again shortly.
emr_failed · 502
HealthGrid could not read the EMR’s answer.
sign_in_not_verified · 401
The EMR did not verify the MediChain sign-in.
account_cannot_act · 403
The account cannot sign in to HealthGrid now.
not_an_operator · 403
The account may not operate HealthGrid.
role_outside_grant · 403
The organization has not let HealthGrid grant that role.
role_not_grantable · 403
A staff registration cannot grant that role.
unknown_role · 422
That is not a role the organization has.
invalid_email · 422
The EMR cannot send an invitation to that address.
request_limit · 429
This organization has too many staff registration requests. Try again later.
request_failed · 503
The EMR could not record the staff registration request. Try again later.
registration_not_found · 404
The organization has no such registration.
registration_in_progress · 409
A request with this Idempotency-Key is still being processed.
idempotency_key_reused · 422
This Idempotency-Key was already used with a different request.
No existence leak
Where an answer could reveal that something exists outside your reach, an unknown id and an out-of-scope one answer the same (HG-046 for the EMR’s patient reads):
The FHIR patient read and both artifact routes: 404 “Patient not found”.
The identifier cross-reference: { "data": null }.
The organization display and the workforce list: 404 “Organization not found”.
A staff registration request’s progress, in the EMR and through HealthGrid: the same 404 for another participant’s or organization’s request as for an id nobody holds.
HealthGrid’s Practitioner read: the same not-found OperationOutcome.
HealthGrid’s Patient read, $lookup-by-identifier and $everything: one not-found OperationOutcome, “The patient was not found.”, for an unknown id or number and for another organization’s patient.
Staff registration: an address that already has a MediChain account is answered as a new one.
When to retry
429: after Retry-After.
503: after a pause, with backoff.
409 from an idempotent write: the first request is still running; retry later with the same key.
409 multiple-matches is not a retry: a person chooses among the candidates.
401 from an EMR route: once, with a new token.
Do not retry 400, 403, 404 or 422 unchanged.
10
Rate limits
Integration build
Every surface has a budget, and every refusal says when to come back.
EMR token endpoint
60 token requests a minute per client. Over it: 429 temporarily_unavailable with Retry-After.
EMR routes
60 requests a minute per client, organization and route, unless the route declares its own. Over it: 429 with Retry-After and retryAfter in the body.
POST /patients/$match
Its own budget: 30 a minute and 300 an hour.
POST /v1/staff-registration-requests
10 a minute for each client and organization, at most 50 requests waiting and 100 in any 24 hours. Over it: 429 with Retry-After.
HealthGrid
100 requests a minute per route and client address by default, and 10 a minute for the operator sign-in. Over it: 429 with Retry-After; on FHIR routes, an OperationOutcome with throttled.
Through HealthGrid
HealthGrid’s staff, patient and record routes call the EMR routes above, inside the EMR’s budgets for HealthGrid’s client. When the EMR is over one, the answer is 503 emr_unavailable, or transient on a FHIR route: retry with backoff.
EMR route · 429http
HTTP/1.1 429 Too Many Requests
Retry-After: 42
{
"statusCode": 429,
"error": "Too Many Requests",
"message": "Too many requests from this integration client. Try again shortly.",
"retryAfter": 42
}
11
Idempotency
Integration build
Integration clients
Send an Idempotency-Key with a write, and a retry returns the first result instead of creating a second record (HG-048).
Writes
POST /patients, POST /patients/{id}/organization-registrations, POST /patients/{patientId}/exchange-artifacts and POST /v1/staff-registration-requests.
The key
8 to 128 letters, digits, _, -, . or :. Anything else is 400. A UUID per logical write works well.
Same key, same request
Within 24 hours, the first result, with the route’s own status and Idempotent-Replayed: true. It is read again under your current access, not served from a stored copy.
Same key, another request
422. The EMR compares a hash of the method, the route, its path ids and the body.
While the first runs
409. Retry later with the same key.
Scope
A key belongs to your client and the organization it acts for.
Without a key
Nothing changes, and a retry can create a second record.
A replayhttp
HTTP/1.1 201 Created
Idempotent-Replayed: true
<the first request’s resource, read again under your current access>
Keep keys opaque
The EMR stores a key as sent. Never build one from a PhilHealth number, a name or any other identifier.
HealthGrid’s writes
HealthGrid’s staff registration request (optional), Patient registration (required) and $everything (optional) take an Idempotency-Key under the same rule, and answer 400 for a malformed one.
HealthGrid sends the EMR hg: and a SHA-256 of the participant and your key, never your key: two participants never share one, and nothing you typed reaches the EMR.
A retry answers the first result: the same request, the same patient, the same record artifact. One key serves $everything for both kinds of record.
The EMR’s 409 and 422 come back as registration_in_progress and idempotency_key_reused, or as conflict and invalid on a FHIR route.
12
Role codes
Landing with RBAC-011
Every role has one code, in lowercase snake_case, stored, sent and compared the same way everywhere. People see a display label, never a code: the doctor role’s label is “Doctor (physician)”.
The code
Lowercase letters, digits and underscores, starting with a letter: doctor, lab_technician, super_admin. The same spelling in REST, GraphQL, CSV and tokens.
Sign-in credentials
patient, doctor, nurse, admin, super_admin, receptionist and lab_technician. lab_technician is the one credential the technician, lab_tech and rad_tech organization roles sign in under.
Organization roles
The same convention for templates, memberships, invitations, affiliations and registration codes. physician is accepted as input and stored as doctor, HL7’s code.
At the FHIR boundary
PractitionerRole.code carries HL7’s practitioner-role coding for doctor, nurse and pharmacist, and the code as text for every role.
RBAC-011 is built and verified, and production takes it with its next deploy, which the release notes will name. Until then production still sends the sign-in credential in capitals (DOCTOR), keeps physician beside doctor among organization roles, and gives PractitionerRole.code as text only, so compare role codes without regard to case.
13
Status and roadmap
Integration build
Not in production
What exists today and what is still to come, by tracker row. A section joins this page when its API reaches done.
Built
EMR integration-client access (HG-039)Tracker: in progress
The token endpoint and the twelve routes, built and tested in the integration build.
No existence leak (HG-046), typed contracts (HG-047)Tracker: in progress
Built in the integration build; the rows are still in progress.
Idempotent writes (HG-048)Tracker: done
A retried write returns the first result instead of a second record.
Staff registration through HealthGrid (HG-042)Tracker: done
A request the organization’s admin approves in the EMR; HealthGrid never sees a code, and an existing account is answered as a new address.
Patients through HealthGrid (HG-043)Tracker: done
Match first, as FHIR on PH Core 0.2.0; a number counts only with its holder’s birth date.
Records through HealthGrid (HG-044)Tracker: done
The EMR’s export or transition-of-care summary, byte for byte, verified and sent with Content-Digest.
Bruno collectionIn the repository
Documented, tested requests for the token endpoint, the workforce reads and every HealthGrid route, at docs/api/bruno/healthgrid-platform/.
Operator session and participant bindings (HG-008)Tracker: done
Operators sign in with MediChain; HealthGrid stores no people.
Users as JSON and FHIR (HG-041)Tracker: done
Read live from the EMR on PH Core 0.2.0; no email or phone leaves HealthGrid.
HealthGrid’s EMR client (HG-040)Tracker: done
One client on the shared packages, with the integration credential.
Being built now
One role code (RBAC-011)Landing with RBAC-011
Lowercase snake_case role codes and HL7 codings at the FHIR boundary.
Not yet
ProductionNot in production
Nothing here is deployed. Production use also waits for the HealthGrid trust and security contract (HG-002, then ORG-036).
Participant systems signing in to HealthGridPlanned
Participant certificates and a signed trust list (HG-010); HealthGrid’s FHIR R4 API with SMART Backend Services and a CapabilityStatement (HG-014).
Self-service developer platform (HG-049)Planned
Projects with production and non-production environments, clients with key pairs by value or by JWK Set URL, a scope catalog mapped to EMR capabilities, the organization admin’s approval, and tokens bound to their environment.
Developer console (HG-050)Planned
API keys per environment, a scope picker, approvals, access requests, grants and revocation, in the PocketHealth app.
Platform SDK (HG-051)Planned
A TypeScript SDK for Node that signs assertions, caches tokens, retries as the error contract allows, and publishes the OpenAPI document.
Disclosure between organizations (HG-016)Planned
A record released beyond the participant’s own organization, under disclosure policy. Until then a record through HealthGrid holds that organization’s entries only.
Sandbox and onboarding (HG-032, HG-033)Planned
A synthetic-data sandbox, then onboarding from application to production activation.