FHIR APIs

Week 4 · ~10 h (SMART often runs over)

FHIR is the API that apps, insurers (“payers”) and data-sharing rules are built on. EHRs certified in the US must offer FHIR APIs, and Canada's national profiles are FHIR R4 too. When a patient's phone shows last month's lab results, or a clinician's screen shows a warning card from a service the hospital bought, a FHIR request was made somewhere. When those requests are careless, the failures are quiet. An app that reads only the first page of a search shows twenty labs out of two thousand and looks fine. An app that asks for every scope holds far more of someone's record than it needs. A feed that never checks its output against the national profile hands the next system data it can't use.

Week 0 taught read, search and conditional update. This week we ask better questions and check the answers. We load ten synthetic patients into a FHIR server and search them properly: chains, includes, paging and bulk export. We separate what data must be exchangeable from how it is shaped, and validate resources against the US and Canadian profiles, by hand and as a CI gate. Then we look at the two standards that let outside software into the clinical workflow: SMART on FHIR, which lets an app act for a user, and CDS Hooks, which lets a service speak up while a clinician is looking at a chart.

Words you need this week. Profile: a set of extra rules on top of base FHIR (week 0). Implementation guide (IG): a published package of profiles and the documentation around them; US Core is one. Token: what an app sends with each request to prove what it is allowed to do. Scope: one permission inside a token, written as a string, such as “read this patient's Observations”. Certified EHR: an EHR that has passed the US government's health IT certification program.

Done when

This week you build profile validation in CI and a SMART app. You are done when:

A server with patients in it

Searching an empty server teaches nothing, so we generate ten patients with Synthea and load them into HAPI. Synthea writes one transaction Bundle per patient, plus two shared Bundles: the hospitals (hospitalInformation…) and the clinicians (practitionerInformation…). Order matters. Patient Bundles point at their doctors with conditional references such as Practitioner?identifier=…|9999966796, which the server resolves while it processes the transaction. Load a patient first and there is nothing to resolve:

$ java -jar synthea-with-dependencies.jar -p 10 -s 42 Massachusetts | grep -E -- ' -- |^Records'
SLF4J: No SLF4J providers were found.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#noProviders for further details.
9 -- Jody426 Hickle134 (8 y/o M) Newburyport, Massachusetts  (11454)
7 -- Wallace647 Effertz744 (16 y/o M) Revere, Massachusetts  (22632)
2 -- Wilfredo622 Fritsch593 (15 y/o M) Whitman, Massachusetts  (20437)
8 -- Lindsay928 Zieme486 (19 y/o F) Worcester, Massachusetts  (25091)
3 -- Ezekiel373 Walter473 (27 y/o M) Watertown, Massachusetts  (37347)
4 -- Shalanda398 Kelsie51 Jenkins714 (30 y/o F) Lowell, Massachusetts  (42162)
6 -- Tennille443 Denna536 Trantow673 (66 y/o F) Arlington, Massachusetts  (91437)
5 -- Jona712 Bonnie873 Gibson10 (67 y/o F) Peabody, Massachusetts  (99680)
10 -- Cristobal567 Montero62 (79 y/o M) Saugus, Massachusetts  (109553)
1 -- Corie618 Sofia418 Beahan375 (101 y/o F) Franklin, Massachusetts  (153177)
Records: total=10, alive=10, dead=0
$ ls output/fhir | grep Information
hospitalInformation1793485472870.json
practitionerInformation1793485472870.json
$ docker run -d --name hapi -p 8080:8080 \
  -e HAPI_FHIR_BULK_EXPORT_ENABLED=true \
  hapiproject/hapi:latest | cut -c1-12
af61d1130e3e
$ F=localhost:8080/fhir
$ timeout 120 sh -c 'until curl -sfo /dev/null $0/metadata; do
  sleep 2; done' $F || exit 1
$ curl -s $F/metadata | jq -c .software
{"name":"HAPI FHIR Server","version":"8.12.0"}
$ post() { curl -s -H 'Content-Type: application/fhir+json' \
  --data-binary @"$1" $F; }
$ post output/fhir/Jody426_*.json | jq -r '.issue[].diagnostics'
HAPI-1091: Invalid match URL "Practitioner?identifier=http://hl7.org/fhir/sid/us-npi|9999966796" - No resources match this search
$ for f in output/fhir/*Information*.json; do
  post $f | jq -r .type; done
batch-response
batch-response
$ for f in output/fhir/[A-Z]*.json; do
  post $f | jq -r .type; done | uniq -c
     10 transaction-response
$ curl -s "$F/Patient?_summary=count" | jq .total
10

HAPI rejected the whole transaction (HAPI-1091) and wrote nothing: a transaction is all or none. The two shared Bundles are batches, so they came back as batch-response, and after them every patient Bundle loaded.

Tested: we enabled bulk export with HAPI_FHIR_BULK_EXPORT_ENABLED=true. Without it, this image answered $export with a 400 and an OperationOutcome saying it didn't know the operation. Lab servers often ship with optional operations off; check /metadata before you blame your client.

Search

A FHIR search is a GET on a resource type with parameters, and the answer is a Bundle of type searchset. Three parts of that Bundle matter as much as the resources inside it: total, how many matched; entry, the ones on this page; and link, where to go next. _count asks for a page size, and _elements trims each resource so we can read the output:

$ F=localhost:8080/fhir
$ curl -s "$F/Patient?_count=3&_elements=name" | jq '{total,
  link: [.link[] | {relation, url}],
  names: [.entry[].resource.name[0].family]}'
{
  "total": 10,
  "link": [
    {
      "relation": "self",
      "url": "http://localhost:8080/fhir/Patient?_count=3&_elements=name"
    },
    {
      "relation": "next",
      "url": "http://localhost:8080/fhir?_getpages=9643061b-8b3d-45f3-9e0a-95603c92abd6&_getpagesoffset=3&_count=3&_pretty=true&_bundletype=searchset&_elements=name"
    }
  ],
  "names": [
    "Beahan375",
    "Montero62",
    "Walter473"
  ]
}
$ pid=$(curl -s "$F/Patient?name=Beahan375" |
  jq -r '.entry[0].resource.id'); echo $pid
1592
$ q="$F/Observation?patient=$pid&category=laboratory"
$ curl -s "$q" | jq '{total, entries: (.entry | length)}'
{
  "total": null,
  "entries": 20
}
$ curl -s "$q&_total=accurate" | jq .total
2067
$ ./fetch-all.sh "$q" | wc -l
2067
$ ./fetch-all.sh "$q&_count=500" | jq -r .code.text |
  sort | uniq -c | sort -rn | head -5
     65 Hemoglobin A1c/Hemoglobin.total in Blood
     60 Urea nitrogen [Mass/volume] in Serum or Plasma
     60 Specific gravity of Urine by Test strip
     60 Sodium [Moles/volume] in Serum or Plasma
     60 Protein [Presence] in Urine by Test strip

The first query matched ten patients and returned three. The next link is not our query with an offset: HAPI stored the result set and handed us a _getpages id. Treat paging links as opaque; follow them, don't build them.

Then the trap. Corie, the 101-year-old, has 2,067 laboratory Observations. The plain search returned 20 of them, and total was null: HAPI hadn't counted yet and left it out, which the spec allows. Nothing in the response is an error. An app that renders entry and stops has just told a clinician that this patient's lab history is twenty results long. _total=accurate made the server count. The spec is explicit that page size is a request: servers “SHALL NOT return more resources than requested … but may return less”. The only correct client follows next until there is none. Ours is ten lines of shell:

#!/bin/sh
# Print every resource a FHIR search matches, one JSON per line,
# following Bundle.link "next" until the server stops sending one.
url=$1
while [ -n "$url" ]; do
  page=$(curl -s "$url")
  printf '%s\n' "$page" | jq -c '.entry[]?.resource'
  url=$(printf '%s\n' "$page" |
        jq -r '.link[]? | select(.relation == "next") | .url')
done

It returned all 2,067. With _count=500 the same loop needed 5 round trips instead of 104, and once you have every page you can ask questions like which tests dominate the record.

Chained parameters

Often what you know isn't on the resource you want. You want Observations, but you know the patient's name or birth date, which live on Patient. A chained parameter follows a reference inside the search: subject:Patient.name=Beahan375 means “Observations whose subject is a Patient whose name matches Beahan375”. _has goes the other way: Patients pointed at by a Condition with a given code. Each replaces a loop of requests in your code with one the server can plan:

$ curl -sG $F/Observation \
  --data-urlencode 'subject:Patient.name=Beahan375' \
  --data-urlencode 'code=http://loinc.org|4548-4' \
  -d _summary=count | jq .total
65
$ curl -sG $F/Observation \
  --data-urlencode 'patient.birthdate=lt1960-01-01' \
  --data-urlencode 'code=http://loinc.org|4548-4' \
  -d _summary=count | jq .total
76
$ curl -sG $F/Patient -d _elements=name --data-urlencode \
  '_has:Condition:patient:code=http://snomed.info/sct|59621000' \
  | jq -r '.entry[].resource.name[0].family'
Beahan375
Gibson10

One patient's HbA1c results (LOINC 4548-4), the same for everyone born before 1960, and the patients with essential hypertension (SNOMED CT 59621000). curl -G --data-urlencode encodes the | between system and code; hand-built URLs break there. In production, chain on subject:Patient.identifier=system|value, not names: as in week 3, identity is an identifier with a system. And the server decides which chains it supports. Its CapabilityStatement lists the search parameters, and a server may ignore one it doesn't know, so check the self link to see what was applied.

_include and _revinclude

A medication list needs the prescriber's name. Fetching each Practitioner is one request per row; instead, ask the server to include referenced resources in the same Bundle. _include follows references out of the matches, _revinclude pulls in resources that point back at them:

$ modes() { jq -r '.entry[] |
  "\(.search.mode) \(.resource.resourceType)"' | sort | uniq -c; }
$ curl -s "$F/MedicationRequest?patient=$pid&_count=5\
&_include=MedicationRequest:requester" | modes
      1 include Practitioner
      5 match MedicationRequest
$ curl -s "$F/Patient?_id=$pid&_revinclude=Condition:patient" |
  tee rev.json | modes
    141 include Condition
      1 match Patient
$ jq '.total' rev.json
1

search.mode says why each entry is there: match or include. Five orders by one clinician brought one Practitioner: includes are deduplicated. The reverse include returned one Patient and 141 Conditions, and total still says 1, because it counts matches only. Never compute “how many results” by counting entries. And ask only for what the screen shows: a _revinclude on a long-lived patient can be huge.

Bulk export

Analytics, payers and quality reporting need everything, and paging through a population would take hours and overload the server. The Bulk Data Access specification defines $export: kick off a job, poll a status URL, and download newline-delimited JSON (one resource per line) when it's ready:

$ poll=$(curl -s -D - -o /dev/null \
  -H 'Accept: application/fhir+json' -H 'Prefer: respond-async' \
  "$F/\$export?_type=Patient,Condition" |
  tr -d '\r' | awk '/^Content-Location/ {print $2}')
$ echo "$poll"
http://localhost:8080/fhir/$export-poll-status?_jobId=0f43f53e-c229-450f-b62d-36903317b4b6
$ timeout 120 sh -c 'until [ "$(curl -s -o manifest.json \
  -w %{http_code} "$0")" = 200 ]; do sleep 5; done' "$poll" \
  || exit 1
$ jq -c '.requiresAccessToken, .output[]' manifest.json
true
{"type":"Condition","url":"http://localhost:8080/fhir/Binary/IraLynOtJr7d8AWHQGJvRK7PeWTiJgaR"}
{"type":"Patient","url":"http://localhost:8080/fhir/Binary/2c5ZIcoSjGjUnl04aAlYf0Dcu2fP7MLV"}
$ jq -r '.output[] | "\(.type) \(.url)"' manifest.json |
  while read t u; do echo "$t $(curl -s "$u" | wc -l)"; done
Condition 408
Patient 10
$ jq -r '.output[] | select(.type == "Patient") | .url' manifest.json |
  xargs curl -s | head -1 | jq -c '{resourceType, id, gender}'
{"resourceType":"Patient","id":"1592","gender":"female"}

The kick-off returned a Content-Location to poll; we polled until the status was 200 and saved the manifest, which lists one file per resource type. Note requiresAccessToken: true. In production each of these calls carries a token from SMART Backend Services (an app authenticating as itself, with no user), and the files are as sensitive as the EHR. Our lab server has no authentication, which is fine for synthetic data and nothing else.

What must be shared, and how it is shaped

Base FHIR is deliberately loose: almost every element is optional, codes can come from any system, and extensions can carry anything. That's why FHIR fits every country, and why two systems that both “speak FHIR” can still fail to understand each other. Countries fix this in two layers.

The first says what must be exchangeable, in plain terms: demographics, problems, medications, allergies, lab results, vital signs, notes. In the US that is USCDI, the United States Core Data for Interoperability; in Canada, CACDI, the Canadian Core Data for Interoperability, published by CIHI. Neither says anything about JSON.

The second says how those elements look in FHIR: profiles that make elements required, bind them to value sets and define extensions. US Core is “updated annually to support the latest requirements” of USCDI. In Canada, CA Baseline is the national starting point, and CA Core+, the guide aligned with CACDI, is still a draft.

United StatesCanada
What must be exchangeableUSCDI (ONC/ASTP)CACDI (CIHI)
How, in FHIR R4US Core (9.0.0 is current)CA Baseline (1.2.0 here); CA Core+ (draft)
Validator packagehl7.fhir.us.corehl7.fhir.ca.baseline
Patient profileus-core-patientprofile-patient

Canada: CA Baseline is deliberately light; provincial guides add their own rules on top. CA Core+ is published as a draft for early implementers, so pin the version you test against and expect changes. Our validator picked CA Baseline 1.2.0 when we didn't name a version.

Validation

A profile is only useful if something checks it. The reference tool is the HL7 FHIR validator, one Java jar. Give it resources, a FHIR version, one or more implementation guides (-ig, downloaded as packages into ~/.fhir) and a profile. It checks codes against value sets too, asking the terminology server at tx.fhir.org about ones it can't resolve locally, so it needs the network.

Synthea against US Core

Synthea's Patient claims, in meta.profile, to be a US Core Patient. Let's hold it to that:

$ jq '.entry[0].resource' output/fhir/Corie618_*.json \
  > synthea-patient.json
$ jq -c '.meta, [.extension[].url | split("/")[-1]]' synthea-patient.json
{"profile":["http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient"]}
["us-core-race","us-core-ethnicity","patient-mothersMaidenName","us-core-birthsex","patient-birthPlace","disability-adjusted-life-years","quality-adjusted-life-years"]
$ US=http://hl7.org/fhir/us/core/StructureDefinition
$ java -jar validator_cli.jar synthea-patient.json \
  -version 4.0.1 -ig hl7.fhir.us.core#9.0.0 \
  -profile $US/us-core-patient > us.log 2>&1; echo "exit $?"
exit 1
$ head -1 us.log | cut -c1-58
FHIR Validation tool Version 7.0.3 (Git# 28e9fac6d79d). Bu
$ grep -E '^\*FAIL|^Success|(Error|Warning) @' us.log |
  sed 's/, validating against.*//'
*FAILURE*: 2 errors, 2 warnings, 5 notes
  Error @ Patient.extension[5] (line 64, col6): The extension http://synthetichealth.github.io/synthea/disability-adjusted-life-years could not be found so is not allowed here
  Error @ Patient.extension[6] (line 68, col6): The extension http://synthetichealth.github.io/synthea/quality-adjusted-life-years could not be found so is not allowed here
  Warning @ Patient.identifier[2].type (line 93, col8): None of the codings provided are in the value set 'IdentifierType' (http://hl7.org/fhir/ValueSet/identifier-type|4.0.1), and a coding should come from this value set unless it has no suitable code (note that the validator cannot judge what is suitable) (codes = http://terminology.hl7.org/CodeSystem/v2-0203#SS)
  Warning @ Patient.communication[0].language (line 207, col8): None of the codings provided are in the value set 'Languages' (http://terminology.hl7.org/ValueSet/Languages|1.0.0), and a coding should come from this value set unless it has no suitable code (note that the validator cannot judge what is suitable) (codes = urn:ietf:bcp:47#en-US)

Two errors of one kind. Synthea adds two extensions of its own, disability-adjusted and quality-adjusted life years (DALY and QALY). Their URLs point at synthetichealth.github.io, no loaded package defines them, and an extension the validator can't find is an error. US Core isn't what's failing; Synthea's private additions are. Fix it where the data is produced: drop the extensions before sending, or publish definitions for them in a package of your own.

The warnings need explaining too, since “every Synthea error is explained” is this week's bar, and a stricter profile can turn a warning into an error. The Social Security number's identifier type SS isn't in the base IdentifierType value set, and en-US wasn't matched in the Languages value set. Both bindings are weaker than required, so they warn. The notes (not shown) are extensions that match no slice the profile names, which is normal.

Synthea and a minimal patient against CA Baseline

The Canadian profile is profile-patient in package hl7.fhir.ca.baseline. We validate the Synthea patient and a minimal hand-written one, then the minimal one again with a flag:

$ P=http://hl7.org/fhir/ca/baseline/StructureDefinition
$ cat minimal-patient.json
{
  "resourceType": "Patient",
  "identifier": [{
    "system": "https://genhosp.example.org/mrn",
    "value": "100901"
  }],
  "name": [{"family": "Tremblay", "given": ["Marie"]}],
  "gender": "female",
  "birthDate": "1975-06-02"
}
$ java -jar validator_cli.jar synthea-patient.json \
  minimal-patient.json \
  -version 4.0.1 -ig hl7.fhir.ca.baseline \
  -profile $P/profile-patient > ca.log 2>&1; echo "exit $?"
exit 1
$ grep -o 'hl7.fhir.ca.baseline#[0-9.]*' ca.log | sort -u
hl7.fhir.ca.baseline#1.2.0
$ grep -E '^-- |^\*FAIL|^Success|Error @' ca.log |
  sed 's/, validating against.*//'
-- synthea-patient.json ----------------------------------------
*FAILURE*: 2 errors, 2 warnings, 18 notes
  Error @ Patient.extension[5] (line 64, col6): The extension http://synthetichealth.github.io/synthea/disability-adjusted-life-years could not be found so is not allowed here
  Error @ Patient.extension[6] (line 68, col6): The extension http://synthetichealth.github.io/synthea/quality-adjusted-life-years could not be found so is not allowed here
-- minimal-patient.json ----------------------------------------
*FAILURE*: 1 errors, 1 warnings, 1 notes
  Error @ Patient.identifier[0].system (line 4, col48): Example URLs are not allowed in this context (https://genhosp.example.org/mrn)
$ java -jar validator_cli.jar minimal-patient.json \
  -version 4.0.1 -ig hl7.fhir.ca.baseline \
  -profile $P/profile-patient -allow-example-urls true \
  > ca2.log 2>&1; echo "exit $?"
exit 0
$ grep -E '^\*FAIL|^Success|(Error|Warning) @' ca2.log |
  sed 's/, validating against.*//'
Success: 0 errors, 1 warnings, 1 notes
  Warning @ Patient (line 1, col2): Constraint failed: dom-6: 'A resource should have narrative for robust management' (defined in http://hl7.org/fhir/StructureDefinition/DomainResource) (Best Practice Recommendation)

Synthea fails on the same two extensions. The validator also checked it against US Core, because the resource still claims that profile: you're validated against what you claim, not only what you ask for.

The minimal patient failed for a different reason. Its identifier system is https://genhosp.example.org/mrn, and the validator refuses example URLs unless you pass -allow-example-urls true. With the flag it passes, with one best-practice warning (dom-6: no narrative). That refusal is a feature: a production record whose identifier system is an example domain is a bug, and a Canadian health card number should carry its province's registered system URI. Every sample in this course uses example.org on purpose, so our test runs need the flag; production runs must not.

Tested: Synthea's own output fails both US Core and CA Baseline on its custom extensions; a minimal CA Baseline patient passes. Re-run on 31 Oct 2026 (validator 7.0.3, US Core 9.0.0, CA Baseline 1.2.0): 2 errors (DALY/QALY) against both, and the minimal patient passed only with -allow-example-urls true, because its MRN system is an example.org URL.

The week 3 bridge's output

Week 3's bridge maps ADT messages to Patients in to_patient, which doesn't need the network. We call it on every week 3 sample message and validate what it would have written:

$ python3 make-patients.py adt*.hl7
adt-a01-late.hl7: wrote out/adt-a01-late.json
adt-a08-first.hl7: wrote out/adt-a08-first.json
adt-amp.hl7: wrote out/adt-amp.json
adt-baddob.hl7: rejected AE 102^Data type error^HL70357
adt-dupe.hl7: wrote out/adt-dupe.json
adt.hl7: wrote out/adt.json
adt-newctl.hl7: wrote out/adt-newctl.json
adt-nomrn.hl7: rejected AE 101^Required field missing^HL70357
adt-on.hl7: wrote out/adt-on.json
adt-prod.hl7: rejected AR 202^Unsupported processing id^HL70357
adt-zseg.hl7: wrote out/adt-zseg.json
$ cat out/adt.json
{
  "resourceType": "Patient",
  "identifier": [
    {
      "system": "https://genhosp.example.org/mrn",
      "value": "100234"
    }
  ],
  "active": true,
  "name": [
    {
      "family": "DOE",
      "given": [
        "JANE"
      ]
    }
  ],
  "gender": "female",
  "birthDate": "1980-02-14"
}
$ java -jar validator_cli.jar out/*.json \
  -version 4.0.1 -ig hl7.fhir.us.core#9.0.0 \
  -profile $US/us-core-patient -allow-example-urls true \
  > bridge-us.log 2>&1; echo "exit $?"
exit 0
$ grep -cE '^Success: 0 errors' bridge-us.log
8

Three messages were rejected, as the bridge rejects them on the wire (bad birth date, missing MRN, production message on a test listener). The other eight Patients pass US Core with zero errors, because the bridge already writes the identifier, name and gender US Core requires. One gap validation can't see: the Ontario sample's health card number (the JHN repetition) never reaches the Patient. A profile can't tell you that dropped data mattered; your mapping tests have to.

Validation in CI

Validation you run by hand stops the week you get busy, so put it in CI. The validator does the hard part: it exits non-zero when any file has an error, and CI fails a step on a non-zero exit. Our gate is a short script:

#!/bin/sh
# CI gate: validate FHIR Patients against CA Baseline.
# The validator exits non-zero if any file has an error, and
# set -e passes that on, so the CI job fails.
set -e
P=http://hl7.org/fhir/ca/baseline/StructureDefinition
java -jar validator_cli.jar "$@" -version 4.0.1 \
  -ig hl7.fhir.ca.baseline#1.2.0 -profile $P/profile-patient \
  -allow-example-urls true > validation.log 2>&1 || {
  grep -E '^-- |^\*FAILURE|Error @' validation.log
  exit 1
}
grep -E '^-- |^Success' validation.log

Here it passes, and then fails after we simulate a mapping regression: someone drops the gender table and writes the HL7 v2 code F straight into FHIR.

$ ./ci-validate.sh out/*.json; echo "exit $?"
-- out/adt-a01-late.json ----------------------------------------
Success: 0 errors, 1 warnings, 1 notes
-- out/adt-a08-first.json ----------------------------------------
Success: 0 errors, 1 warnings, 1 notes
-- out/adt-amp.json ----------------------------------------
Success: 0 errors, 1 warnings, 1 notes
-- out/adt-dupe.json ----------------------------------------
Success: 0 errors, 1 warnings, 1 notes
-- out/adt.json ----------------------------------------
Success: 0 errors, 1 warnings, 1 notes
-- out/adt-newctl.json ----------------------------------------
Success: 0 errors, 1 warnings, 1 notes
-- out/adt-on.json ----------------------------------------
Success: 0 errors, 1 warnings, 1 notes
-- out/adt-zseg.json ----------------------------------------
Success: 0 errors, 1 warnings, 1 notes
exit 0
$ jq '.gender = "F"' out/adt.json > out/regression.json
$ ./ci-validate.sh out/*.json; echo "exit $?"
-- out/adt-a01-late.json ----------------------------------------
-- out/adt-a08-first.json ----------------------------------------
-- out/adt-amp.json ----------------------------------------
-- out/adt-dupe.json ----------------------------------------
-- out/adt.json ----------------------------------------
-- out/adt-newctl.json ----------------------------------------
-- out/adt-on.json ----------------------------------------
-- out/adt-zseg.json ----------------------------------------
-- out/regression.json ----------------------------------------
*FAILURE*: 2 errors, 1 warnings, 1 notes
  Error @ Patient.gender (line 18, col16): The System URI could not be determined for the code 'F' in the ValueSet 'http://hl7.org/fhir/ValueSet/administrative-gender|4.0.1', validating against Canadian Baseline v1.2.0
  Error @ Patient.gender (line 18, col16): The value provided ('F') was not found in the value set 'AdministrativeGender' (http://hl7.org/fhir/ValueSet/administrative-gender|4.0.1), and a code is required from this value set  (error message = The System URI could not be determined for the code 'F' in the ValueSet 'http://hl7.org/fhir/ValueSet/administrative-gender|4.0.1'; The provided code '#F' was not found in the value set 'http://hl7.org/fhir/ValueSet/administrative-gender|4.0.1'), validating against Canadian Baseline v1.2.0
exit 1

Exit status 1, and the log names the element and the value set. Here is a GitHub Actions workflow around the same script. We did not run it on GitHub; its commands are the ones you just saw. Pin the validator and IG versions, or the build can break because a new release came out rather than because your code changed.

# .github/workflows/validate.yml (not run on GitHub for this page)
name: validate
on: [push, pull_request]
jobs:
  fhir:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with: {distribution: temurin, java-version: "21"}
      - uses: actions/setup-python@v5
        with: {python-version: "3.12"}
      - run: pip install hl7
      - name: Bridge output for every sample message
        run: python3 make-patients.py adt*.hl7
      - name: Get the validator (pinned)
        run: >
          curl -sSLo validator_cli.jar https://github.com/hapifhir/org.hl7.fhir.core/releases/download/7.0.3/validator_cli.jar
      - name: Validate (fails the job on any error)
        run: ./ci-validate.sh out/*.json

$validate on the server

Servers offer the same check as an operation, POST [base]/Patient/$validate, and it answers differently:

$ curl -s -o v.json -w '%{http_code}\n' \
  -H 'Content-Type: application/fhir+json' \
  --data-binary @synthea-patient.json "$F/Patient/\$validate"
200
$ jq -r '.issue[] | "\(.severity): \(.diagnostics)"' v.json | cut -c1-110
information: Unknown extension http://hl7.org/fhir/us/core/StructureDefinition/us-core-race
information: Unknown extension http://hl7.org/fhir/us/core/StructureDefinition/us-core-ethnicity
information: Unknown extension http://hl7.org/fhir/us/core/StructureDefinition/us-core-birthsex
information: Unknown extension http://synthetichealth.github.io/synthea/disability-adjusted-life-years
information: Unknown extension http://synthetichealth.github.io/synthea/quality-adjusted-life-years
warning: None of the codings provided are in the value set 'IdentifierType' (http://hl7.org/fhir/ValueSet/iden
error: Profile reference 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient' has not been checke
error: Invalid profile. Failed to retrieve profile with url=http://hl7.org/fhir/us/core/StructureDefinition/us

HTTP 200, with errors inside: the status says the operation ran, not that the resource is valid, so read every issue's severity, as week 0 warned. And the verdict changed. Our HAPI has no US Core package loaded, so it couldn't check the claimed profile, reported that as an error, and treated the extensions as merely unknown. A server validates only against what it has loaded. Use the CLI with pinned packages in CI.

AI this week: ask it to explain validator messages, then confirm each against the profile's own page.

SMART on FHIR

Real EHR FHIR APIs require a token, and SMART App Launch is how an app gets one: OAuth 2.0 plus conventions for discovery, scopes and launch context. In an EHR launch the clinician is already in the chart and opens the app from inside it. Step by step:

  1. The EHR calls the app's launch URL with iss (the FHIR base URL) and an opaque launch value.
  2. The app reads .well-known/smart-configuration under iss to find the authorize and token endpoints.
  3. The app sends the browser to the authorize endpoint with the scopes it wants, the launch value and a PKCE challenge.
  4. The EHR sends the browser back to the app with a short-lived code.
  5. The app trades the code and the PKCE verifier for a token tied to that patient and user.

In a standalone launch the app starts on its own, like a patient's phone app, and the patient is chosen during login. Scopes and PKCE are explained next, and the curl walk-through below runs every step.

Scopes say what the token allows. In SMART v2, patient/Observation.rs means read and search Observations for the patient in context (v1 wrote patient/Observation.read). Ask for the narrowest scope the screen needs: a labs app has no business holding patient/*.rs, and v2 can narrow further with a search parameter, patient/Observation.rs?category=…|laboratory. The server may grant less than you asked for, so read scope in the token response.

Every SMART app must use PKCE (Proof Key for Code Exchange). The app makes a random verifier and sends only its SHA-256 hash, the challenge, when it asks for authorization. To swap the resulting code for a token it must show the verifier, so someone who intercepts the code can't use it. SMART servers must support S256 and must not support plain.

Walking the flow with curl

The public SMART launcher at launch.smarthealthit.org simulates an EHR, with an authorization server and a FHIR server of synthetic patients. Discovery comes first: a SMART server publishes its endpoints at .well-known/smart-configuration under the FHIR base. Then we play the EHR and the app by hand. The launcher's launch value is its own format, a base64url-encoded array that picks the patient and practitioner and turns on its “skip login” and “skip authorization” options, so curl can stand in for the browser:

$ ISS=https://launch.smarthealthit.org/v/r4/fhir
$ curl -s $ISS/.well-known/smart-configuration | jq '{
  authorization_endpoint, token_endpoint,
  code_challenge_methods_supported,
  capabilities: .capabilities[:4]}'
{
  "authorization_endpoint": "https://launch.smarthealthit.org/v/r4/auth/authorize",
  "token_endpoint": "https://launch.smarthealthit.org/v/r4/auth/token",
  "code_challenge_methods_supported": [
    "S256"
  ],
  "capabilities": [
    "launch-ehr",
    "launch-standalone",
    "client-public",
    "client-confidential-symmetric"
  ]
}
$ verifier=$(openssl rand -base64 48 | tr '+/' '-_' | tr -d '=\n')
$ challenge=$(printf %s "$verifier" |
  openssl dgst -sha256 -binary | base64 | tr '+/' '-_' | tr -d '=')
$ echo "$verifier"; echo "$challenge"
DryLevn6WBMthLwXeYALOvosGIkgjX93BExBfK7RRcAZr4SoKMGdq69tZ7Lfdb71
xA0R2fgb6rnXL8OtPOsM19InC6wQBS6TvimI6dyCF-I
$ cat launch.json; echo
[0,"87a339d0-8cae-418e-89c7-8651e6aab3c6","52919099-6a7a-442c-b0d5-2b02c0dd4b74","AUTO",1,1,0,"","","","","","","",0,1,""]
$ launch=$(base64 -w0 launch.json | tr '+/' '-_' | tr -d '=')
$ AUTH=https://launch.smarthealthit.org/v/r4/auth
$ CB=http://localhost:9000/cb
$ loc=$(curl -s -o /dev/null -w '%{redirect_url}' -G $AUTH/authorize \
  -d response_type=code -d client_id=labs-app \
  --data-urlencode redirect_uri=$CB \
  --data-urlencode 'scope=launch openid patient/Observation.rs' \
  -d state=abc123 --data-urlencode aud=$ISS -d launch=$launch \
  -d code_challenge=$challenge -d code_challenge_method=S256)
$ echo "$loc" | sed 's/code=[^&]*/code=.../'
http://localhost:9000/cb?code=...&state=abc123
$ code=$(echo "$loc" | sed 's/.*code=\([^&]*\).*/\1/')
$ token() { curl -s $AUTH/token -d grant_type=authorization_code \
  -d code=$code --data-urlencode redirect_uri=$CB \
  -d client_id=labs-app -d code_verifier=$1; }
$ token wrong-verifier | jq .
{
  "error": "invalid_grant",
  "error_description": "Invalid grant or Invalid PKCE Verifier, 'ZugODcX1jSZ8ehrZTQtS5NEW5sILxakqdD2YByJ-xH4' vs 'xA0R2fgb6rnXL8OtPOsM19InC6wQBS6TvimI6dyCF-I'."
}
$ token $verifier | jq 'del(.access_token, .id_token)'
{
  "token_type": "Bearer",
  "expires_in": 3600,
  "scope": "launch openid patient/Observation.rs",
  "need_patient_banner": true,
  "smart_style_url": "https://launch.smarthealthit.org/smart-style.json",
  "patient": "87a339d0-8cae-418e-89c7-8651e6aab3c6",
  "encounter": "418e38cf-9da6-4155-b205-0be24024b1db"
}
$ tok=$(token $verifier | jq -r .access_token)
$ p=87a339d0-8cae-418e-89c7-8651e6aab3c6
$ curl -s -o /dev/null -w '%{http_code}\n' \
  -H "Authorization: Bearer $tok" "$ISS/Condition?patient=$p"
200

The authorization request came straight back to our redirect URI with a code and our state. The wrong verifier was refused because its hash didn't match the challenge. The right one got a token, and the response carries the launch context, the patient and encounter the EHR had open: that's how an EHR-launched app knows whose chart it's in.

Two things there are sandbox behaviour your app must not rely on. We used the same code twice and both worked; OAuth 2.0 says a code must not be used more than once. And a token scoped to Observations read Conditions: the launcher's FHIR server doesn't enforce scopes. A real EHR does, so test scope handling against the vendor's sandbox.

Tested: the launcher sandbox accepted an authorization code twice and served Conditions to a token scoped to patient/Observation.rs. We did not run the browser flow: no login page, patient picker or consent screen was exercised; the launcher's options skipped them.

A SMART app in TypeScript

In practice the SMART JavaScript client, fhirclient, does discovery, state, PKCE and the token exchange. Here is the server-side Express version, in the shape of week 0's TypeScript app. The launch route starts authorization:

// The EHR opens /launch?iss=<FHIR base>&launch=<opaque>
app.get("/launch", (req, res, next) => {
  smart(req, res).authorize({
    clientId: "labs-app",
    scope: "launch openid fhirUser patient/Observation.rs",
    redirectUri: "/app",
  }).catch(next);
});

and the redirect route finishes it and reads labs and vital signs for the patient in context:

// The authorization server redirects back here with ?code=&state=
app.get("/app", async (req, res, next) => {
  try {
    const client = await smart(req, res).ready();
    const lines = [`patient ${client.patient.id}`,
                   `scope ${client.state.tokenResponse?.scope}`];
    for (const cat of ["laboratory", "vital-signs"]) {
      const bundle = await client.request<Bundle>(
        `Observation?patient=${client.patient.id}` +
        `&category=${cat}&_sort=-date&_count=4`);
      lines.push(`-- ${cat}`,
                 ...(bundle.entry ?? []).map((e) => show(e.resource)));
    }
    res.type("text/plain").send(lines.join("\n") + "\n");
  } catch (e) {
    next(e);
  }
});

We ran it with tsx and let curl play the browser, following redirects and keeping the session cookie:

$ npm init -y > /dev/null
$ npm install --no-fund --no-audit \
  fhirclient@3.0.1 express express-session tsx

added 80 packages in 644ms
$ PORT=9000 npx tsx labs-app.ts > app.log 2>&1 &
$ timeout 60 sh -c 'until grep -q "labs-app on" app.log; do
  sleep 1; done' || exit 1
$ curl -sL -c cookies.txt -b cookies.txt \
  "localhost:9000/launch?iss=$ISS&launch=$launch"
patient 87a339d0-8cae-418e-89c7-8651e6aab3c6
scope launch openid fhirUser patient/Observation.rs
-- laboratory
2020-11-11  Creatinine: 0.8 mg/dL
2020-11-11  Carbon Dioxide: 23.1 mmol/L
2020-11-11  Total Cholesterol: 191.2 mg/dL
2020-11-11  Low Density Lipoprotein Cholesterol: 100.3 mg/dL
-- vital-signs
2020-11-11  Blood Pressure: 77.9 mm[Hg] / 111.8 mm[Hg]
2020-11-11  Body Weight: 83.9 kg
2020-11-11  Pain severity - 0-10 verbal numeric rating [Score] - Reported: 3.6 {score}
2020-11-11  Body Mass Index: 30.1 kg/m2
$ kill %1

Labs and vitals for the launched patient. The sandbox's blood pressure lists the diastolic component first, so a real app should label each component by its code. This app reads one page per category; for a full history, follow next as before, or use fhirclient's pageLimit option. We did not open it in a browser or inside a real EHR. Download labs-app.ts and launch.json.

CDS Hooks

SMART puts your app in front of the clinician when they open it. CDS Hooks works the other way: the EHR calls your service at moments in the workflow called hooks, and shows what you return. patient-view fires when a chart is opened; order-select and order-sign fire while orders are written. You answer with cards: a summary, an indicator (info, warning or critical), a source, and optionally suggestions or links that launch a SMART app.

A service describes itself at {base}/cds-services, including a prefetch template: FHIR queries the EHR runs and sends along, so the service doesn't call back while a clinician waits. Ours shows the latest HbA1c:

A1C = ("Observation?patient={{context.patientId}}"
       "&code=http://loinc.org|4548-4&_sort=-date&_count=1")
SERVICE = {
    "hook": "patient-view",
    "id": "a1c-latest",
    "title": "Latest HbA1c",
    "description": "Shows the most recent HbA1c, or warns if none.",
    "prefetch": {"a1c": A1C},
}
SOURCE = {"label": "Week 4 demo service (synthetic data)"}


def fetch_a1c(req):
    """Used only when the EHR sent no prefetch: ask its FHIR server."""
    query = A1C.replace("{{context.patientId}}",
                        req["context"]["patientId"])
    http = urllib.request.Request(f"{req['fhirServer']}/{query}")
    token = (req.get("fhirAuthorization") or {}).get("access_token")
    if token:
        http.add_header("Authorization", f"Bearer {token}")
    with urllib.request.urlopen(http, timeout=10) as resp:
        return json.load(resp)


def cards(req):
    bundle = req.get("prefetch", {}).get("a1c")
    if bundle is None:
        bundle = fetch_a1c(req)
    entries = bundle.get("entry", [])
    if not entries:
        return [{"summary": "No HbA1c on file", "indicator": "warning",
                 "source": SOURCE}]
    obs = entries[0]["resource"]
    q = obs["valueQuantity"]
    when = obs["effectiveDateTime"][:10]
    return [{"summary": f"Latest HbA1c {q['value']} {q['unit']} ({when})",
             "indicator": "info", "source": SOURCE}]

We ran this service locally, with curl playing the EHR: once with a prefetched result from our HAPI, then for a patient with no HbA1c and no prefetch, so the service queried the fhirServer itself:

$ python3 cds-service.py 3001 > cds.log 2>&1 &
$ sleep 1; curl -s localhost:3001/cds-services | jq .
{
  "services": [
    {
      "hook": "patient-view",
      "id": "a1c-latest",
      "title": "Latest HbA1c",
      "description": "Shows the most recent HbA1c, or warns if none.",
      "prefetch": {
        "a1c": "Observation?patient={{context.patientId}}&code=http://loinc.org|4548-4&_sort=-date&_count=1"
      }
    }
  ]
}
$ F=localhost:8080/fhir
$ pid=$(curl -s "$F/Patient?name=Beahan375" |
  jq -r '.entry[0].resource.id')
$ curl -s "$F/Observation?patient=$pid&_sort=-date&_count=1\
&code=http://loinc.org%7C4548-4" > a1c.json
$ jq -n --arg pid $pid --slurpfile a1c a1c.json '{
  hook: "patient-view",
  hookInstance: "0b6f6c1e-3d1a-4f7e-9a51-2c4e8d7b9f10",
  context: {userId: "Practitioner/example", patientId: $pid},
  prefetch: {a1c: $a1c[0]}}' > hook.json
$ curl -s -H 'Content-Type: application/json' --data @hook.json \
  localhost:3001/cds-services/a1c-latest | jq .
{
  "cards": [
    {
      "summary": "Latest HbA1c 2.82 % (2026-10-31)",
      "indicator": "info",
      "source": {
        "label": "Week 4 demo service (synthetic data)"
      }
    }
  ]
}
$ pid2=$(curl -s "$F/Patient?name=Hickle134" |
  jq -r '.entry[0].resource.id')
$ jq -n --arg pid $pid2 --arg fhir "http://$F" '{
  hook: "patient-view",
  hookInstance: "5c2d9e47-8b1f-4c3a-b6e0-7f4a1d2c3b5e",
  fhirServer: $fhir,
  context: {userId: "Practitioner/example", patientId: $pid}}' |
  curl -s -H 'Content-Type: application/json' --data @- \
  localhost:3001/cds-services/a1c-latest | jq -c .
{"cards":[{"summary":"No HbA1c on file","indicator":"warning","source":{"label":"Week 4 demo service (synthetic data)"}}]}
$ kill %1; cat cds.log
127.0.0.1 - - [31/Oct/2026 18:26:20] "GET /cds-services HTTP/1.1" 200 -
127.0.0.1 - - [31/Oct/2026 18:26:20] "POST /cds-services/a1c-latest HTTP/1.1" 200 -
127.0.0.1 - - [31/Oct/2026 18:26:20] "POST /cds-services/a1c-latest HTTP/1.1" 200 -

That is the protocol's whole shape: discovery, a hook call with context and prefetch, cards back. We did not test it inside an EHR or the CDS Hooks sandbox, which also need CORS headers and verification of the JWT the EHR sends. And look at the value: an HbA1c of 2.82 % isn't something you'd expect on a real chart. Synthea's values come from its disease models and aren't always clinically plausible, so never test clinical logic only against them.

Cards interrupt busy people. Use the narrowest hook that fits, return no card when there's nothing to say, and keep the summary short (the spec caps it at 140 characters). A service that cries wolf trains clinicians to dismiss every card, including the one that matters.

Patient access, information blocking, TEFCA and Inferno

Much of this exists because of regulation. In the US, the ONC Cures Act Final Rule requires certified health IT to offer a standardized FHIR API with SMART authorization, including for patients reaching their own records, and its information blocking rules make it a problem to interfere with access to, exchange or use of electronic health information, outside listed exceptions. TEFCA, the Trusted Exchange Framework and Common Agreement, is the US national network of networks. In Canada, health care is run by the provinces and territories, and what their systems must support is set mostly by them and their programs, with CACDI and HL7 Canada's guides as the shared national reference.

To check conformance, Inferno, ONC's open test tool, runs test kits against a FHIR endpoint: US Core profiles and searches, SMART launch and bulk export. We did not run Inferno for this page.

Lab files: fetch-all.sh, minimal-patient.json, make-patients.py (uses week 3's bridge.py), ci-validate.sh, validate.yml, labs-app.ts, launch.json, cds-service.py.

Exercises

  1. What's the difference between USCDI and US Core? Answer for Canada too (CACDI against CA Baseline and CA Core+), and say which one a validator can check.
  2. Why does Synthea's own output fail validation? Strip the two extensions with jq and re-run against US Core and CA Baseline. What's left, and is any of it an error?
  3. What scope does an app need to read one patient's labs? Write it as a SMART v1 scope, a v2 scope, and a v2 scope narrowed to the laboratory category.
  4. Reading only the first page of a search: find a place in your week 0 kata or SMART app that does it and fix it. Prove the fix with a patient who has more results than fit on one page.
  5. Write one search that returns a patient's MedicationRequests with their prescribers and encounters. Explain why total doesn't match the number of entries.
  6. Add the validator to CI for your week 3 bridge (-ig hl7.fhir.us.core or hl7.fhir.ca.baseline), validate the Patients it writes and fix every error. Then map the JHN health card number to a second identifier and validate again.
  7. Run the week 0 SMART app through the SMART launcher in a real browser, with login and patient selection on, and add vital signs with labelled blood pressure components. Ask for the narrowest scope that still works.
  8. Run $export for one patient (Patient/[id]/$export). What would you add before pointing the same client at a production server?
  9. Stretch: put the CDS service behind the CDS Hooks sandbox. What does it need besides the code above? Decide when it should return no card at all.

For more drill on this week's skills, work through the week 4 practice problems.

Read

Tested with

Every command on this page was run on 31 Oct 2026 against the course lab: HAPI FHIR 8.12.0 in Docker, Synthea (master build of 21 Oct 2026), the HL7 FHIR validator 7.0.3 on OpenJDK 25, Node 20 with fhirclient 3.0.1, Python 3.12 and jq 1.7, plus the public SMART launcher sandbox. The outputs are copied from one run of the lab script. Yours will differ in server ids, timestamps and random values.


Course content © 2026 HeyItWorked. All rights reserved.

Site design adapted from The Missing Semester of Your CS Education under CC BY-NC-SA 4.0. See copyright and license.