One exercise, four stacks

Week 0 · ~10 h: deep in one stack, 1–2 h each for the rest

Employers hire into a stack. A hospital that runs its integration on Java wants people who know HAPI FHIR; a vendor whose product sits on Azure wants C# and the Firely SDK; data teams write Python; patient-facing apps are often TypeScript. One identical exercise in Java, C#, Python and TypeScript shows how they differ, and your main stack's client returns in weeks 3–6.

The exercise is small on purpose, but every step in it guards against a bug that reaches patients. Look a patient up the wrong way and you update somebody else's chart. Create where you meant to update and the hospital now has two records for one person: allergies on one, medications on the other, and the clinician sees only half. Write without checking versions and a phone number that registration just corrected is silently put back, so the clinic can't reach the patient with a result. These bugs look the same in every language, and so do the defences. Only the syntax changes.

This week we start a local FHIR server, give it one synthetic patient, learn the handful of REST calls the exercise needs, and then do the same kata four times, once per stack, against the same patient. At the end we prove from the server's own history that each run wrote exactly once, and we push conditional updates until they fail, so you know what failure looks like.

Words you need first. EHR: electronic health record, the hospital's main clinical system. FHIR: the standard that describes health data as JSON resources (Patient, Observation and so on) served over a REST API. Resource: one JSON document of one type. MRN: medical record number, the id a hospital gives a patient. Upsert: update the record if it exists, create it if it doesn't. Conditional PUT: FHIR's upsert, “update the Patient with this MRN, or create one”. Weeks 1 and 4 go deeper.

Done when

This week you build one FHIR kata in four stacks. You are done when:

The kata

A kata is a drill you repeat until the moves are automatic. Ours is the smallest useful piece of integration work: a patient's details changed somewhere else, and we must update the one record that holds them. In order:

  1. Find the patient by medical record number (MRN). Expect exactly one match.
  2. Change something: add a mobile number.
  3. Ask the server to $validate the changed resource, and read the severity of every issue it reports.
  4. Write it back with a conditional PUT keyed on the MRN.
  5. Read it back by MRN. Expect one match, and a version one higher than before.
  6. Prove exactly one write happened.

Here are the kata's calls as tested. S is the identifier system, the namespace that says whose MRN this is:

# S = http://hospital.smarthealthit.org
#     (the MRN system in Synthea's output)
GET  /fhir/Patient?identifier=S|<mrn>
POST /fhir/Patient/$validate   # read every severity
PUT  /fhir/Patient?identifier=S|<mrn>
GET  /fhir/Patient?identifier=S|<mrn>  # version +1

Each kata prints one line per request with the method, the URL, the HTTP status and what it learned, then PASS or FAIL. That output format is the point. When a kata fails at work, the first question is always “which request, and what did the server answer?”, and an exercise that answers it on every line trains the habit.

A FHIR server to practice on

HAPI FHIR is an open-source Java implementation of FHIR, and its project publishes a ready-to-run server image. With no configuration it keeps its data inside the container, which is right for practice: remove the container and you have a clean server. Start it and open /fhir/metadata:

$ docker run -d --name hapi -p 8080:8080 hapiproject/hapi:latest > /dev/null
$ timeout 120 bash -c 'until curl -sf -o /dev/null \
  localhost:8080/fhir/metadata; do sleep 3; done'
$ curl -s localhost:8080/fhir/metadata | jq '{fhirVersion, software}'
{
  "fhirVersion": "4.0.1",
  "software": {
    "name": "HAPI FHIR Server",
    "version": "8.12.0"
  }
}

/metadata returns the server's CapabilityStatement: the FHIR version it speaks (4.0.1 is R4, the release this course uses), the resources and searches it supports, and what software it is. Check it before you trust a server.

One synthetic patient

We never practise on real people. Synthea generates synthetic patients with realistic medical histories, written out as FHIR transaction bundles. With -p 1 it makes one living patient; -s 42 fixes the random seed, so you get the same patient we did.

Synthea's default output claims US Core

Run it with the defaults first, into a separate directory:

$ java -jar synthea-with-dependencies.jar -p 1 -s 42 \
  --exporter.baseDirectory=uscore | grep -E '^1 --|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.
1 -- Corie618 Sofia418 Beahan375 (101 y/o F) Franklin, Massachusetts  (153177)
Records: total=1, alive=1, dead=0
$ ls uscore/fhir
Corie618_Sofia418_Beahan375_ba419d35-0dfe-8af7-347c-eebf02485a56.json
hospitalInformation1793484809781.json
practitionerInformation1793484809781.json
$ jq '.entry[0].resource.meta' uscore/fhir/Corie*.json
{
  "profile": [
    "http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient"
  ]
}

Three files: the patient's own bundle, and two bundles of the hospitals and clinicians who treated her. The SLF4J lines are Synthea's logging library announcing that no logger is configured; they are harmless. The interesting part is the patient's meta.profile. A profile is a set of extra rules on top of base FHIR, and by listing US Core's patient profile, the resource claims to follow those rules. US Core is the set of profiles the US uses for its core data. Now ask our server whether this patient is valid:

$ jq '.entry[0].resource' uscore/fhir/Corie*.json > p-uscore.json
$ curl -s -o oo.json -w '%{http_code}\n' \
  -H 'Content-Type: application/fhir+json' \
  --data-binary @p-uscore.json \
  'localhost:8080/fhir/Patient/$validate'
200
$ jq -r '.issue | group_by(.severity)[]
  | "\(length) \(.[0].severity)"' oo.json
2 error
5 information
1 warning
$ jq -r '.issue[] | select(.severity != "information")
  | "\(.severity) \(.expression[0])"' oo.json
warning Patient.identifier[2].type
error Patient.meta.profile[0]
error null
$ jq -r '.issue[] | select(.severity == "error")
  | .diagnostics' oo.json
Profile reference 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient' has not been checked because it could not be found, and the validator is set to not fetch unknown profiles
Invalid profile. Failed to retrieve profile with url=http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient

HTTP 200, and two errors. Both say the same thing: the resource claims a profile the server doesn't have, so it can't check the claim, and it counts the unverifiable claim as an error. Our server was never told about US Core. You could load the US Core package into it; we didn't, because this week is about plain R4.

The 200 is not HAPI being sloppy. The specification says this operation returns a 200 OK whether or not the resource is valid; a 4xx or 5xx means the validation itself could not run. $validate returns an OperationOutcome: read every issue's severity. Never trust an HTTP 200 from $validate: a client that checks the status code and moves on has validated nothing.

Tested: all four katas pass against one patient (versions 1 → 5, still one patient). HAPI's $validate answers 200 even with errors, and Synthea's default output fails it because it claims US Core.

Plain R4 output

Synthea's --exporter.fhir.use_us_core_ig=false drops the US Core profiles and extensions. Same seed, same patient, default output directory:

$ java -jar synthea-with-dependencies.jar -p 1 -s 42 \
  --exporter.fhir.use_us_core_ig=false | grep -E '^1 --|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.
1 -- Corie618 Sofia418 Beahan375 (101 y/o F) Franklin, Massachusetts  (153177)
Records: total=1, alive=1, dead=0
$ jq '.entry[0].resource' output/fhir/Corie*.json > p-plain.json
$ curl -s -o oo.json -w '%{http_code}\n' \
  -H 'Content-Type: application/fhir+json' \
  --data-binary @p-plain.json \
  'localhost:8080/fhir/Patient/$validate'
200
$ jq -r '.issue | group_by(.severity)[]
  | "\(length) \(.[0].severity)"' oo.json
2 information
1 warning
$ jq -r '.issue[] | select(.severity == "warning")
  | .expression[0], .diagnostics' oo.json
Patient.identifier[2].type
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)

No errors. Two information issues remain (Synthea's own extensions, which the server has no definitions for) and one warning, which points at Patient.identifier[2].type: the type code on the social security number is SS, and SS isn't in the identifier type value set that R4 binds there. The diagnostics spell out why that is only a warning: the binding allows other codes when the value set has no suitable one. Learn to read severities this way. Errors stop the kata. Warnings and information are worth reading once, and then you decide which ones your interface accepts.

Loading in order

The patient's bundle doesn't contain her doctors or hospitals. It points at them by search, with references such as Practitioner?identifier=http://hl7.org/fhir/sid/us-npi|…, and the server resolves each one when the transaction runs. So the order matters: the hospital bundle, then the practitioner bundle, then the patient.

$ ls output/fhir
Corie618_Sofia418_Beahan375_ba419d35-0dfe-8af7-347c-eebf02485a56.json
hospitalInformation1793484816066.json
practitionerInformation1793484816066.json
$ for f in output/fhir/hospital*.json \
         output/fhir/practitioner*.json \
         output/fhir/Corie*.json; do
  curl -s -o /dev/null -w "%{http_code} %{time_total}s $f\n" \
    -H 'Content-Type: application/fhir+json' \
    --data-binary @"$f" localhost:8080/fhir
done
200 0.114475s output/fhir/hospitalInformation1793484816066.json
200 0.052819s output/fhir/practitionerInformation1793484816066.json
200 5.689073s output/fhir/Corie618_Sofia418_Beahan375_ba419d35-0dfe-8af7-347c-eebf02485a56.json
$ curl -s 'localhost:8080/fhir/Patient?_summary=count' | jq .total
1

About five thousand resources arrived in a few seconds. When we tried the patient bundle first on a fresh server, HAPI rejected the whole transaction with a 404 (HAPI-1091: Invalid match URL "Practitioner?identifier=…" - No resources match this search) and saved nothing. A transaction is all or nothing. That is what you want: half a patient is worse than none.

Tested: the same seed gave the same patient, Corie618 Beahan375, and the same MRN in every run, with or without US Core. The hospital and practitioner file names changed from run to run, so we load them with a wildcard.

FHIR REST in five minutes

Everything the kata does is plain HTTP, so we try it with curl before any library hides it. Three ideas carry the whole week:

$ export FHIR=http://localhost:8080/fhir
$ export S=http://hospital.smarthealthit.org
$ export MRN=$(jq -r '.entry[0].resource.identifier[]
  | select(.system==env.S) | .value' output/fhir/Corie*.json)
$ echo $MRN
ba419d35-0dfe-8af7-347c-eebf02485a56
$ curl -s "$FHIR/Patient?identifier=$S|$MRN" | jq '{resourceType,
  total, id: .entry[0].resource.id,
  version: .entry[0].resource.meta.versionId}'
{
  "resourceType": "Bundle",
  "total": 1,
  "id": "1015",
  "version": "1"
}
$ curl -s "$FHIR/Patient?_id=$MRN" | jq .total
0
$ ID=$(curl -s "$FHIR/Patient?identifier=$S|$MRN" \
  | jq -r '.entry[0].resource.id')
$ curl -s "$FHIR/Patient/$ID" | jq -c '{resourceType, id, meta}'
{"resourceType":"Patient","id":"1015","meta":{"versionId":"1","lastUpdated":"2026-10-31T22:13:40.877+00:00"}}

Look at the two lookups in the middle. The search by identifier finds Corie. The search by _id with her MRN finds nothing: _id is the server's id, and this server called her 1015. Server ids aren't MRNs; another server gives her another id. The MRN is what the hospital knows her by, printed on her wristband and sent in every message about her, so the kata starts from the MRN and discovers the id: identifier=system|value, never _id.

The system half matters as much as the value. MRNs are only unique within the organization that issues them, so 100234 at one hospital and 100234 at another are different people. Always search with both halves.

The read shows the last idea: meta.versionId. Each update bumps meta.versionId, the server keeps every version, and lastUpdated records when it changed. The kata uses the version to prove a write happened. Concurrency control uses it too: an If-Match header carrying the version you read stops two writers clobbering each other. We test that at the end.

The kata in four stacks

Each stack gets the server's base URL and the MRN from the environment (FHIR and MRN, exported above), and the mobile number as its argument. Each stack uses a different number, 555-0101 to 555-0104, so every run really changes the patient. Download the four projects: java/pom.xml with Kata.java, csharp/Kata.csproj with Program.cs, python/requirements.txt with kata.py, and typescript/package.json with tsconfig.json and src/server.ts. The test patient used at the end is test-patient.json.

Java: HAPI FHIR client

HAPI FHIR is the most widely used Java FHIR library, and Java is everywhere in hospital integration: Open Integration Engine, the open-source fork of Mirth Connect, is written in it. The client is a fluent builder: client.search().byUrl(…).returnBundle(Bundle.class).execute(). It hides HTTP well, which is a problem when you want to print status codes, so we register an interceptor that remembers the last response:

IGenericClient client = FhirContext.forR4()
    .newRestfulGenericClient(System.getenv("FHIR"));
client.registerInterceptor(new IClientInterceptor() {
  public void interceptRequest(IHttpRequest req) {}
  public void interceptResponse(IHttpResponse res) {
    status = res.getStatus();
  }
});

The middle of the kata is two calls. validate() sends the $validate request; conditionalByUrl turns an update into a conditional PUT:

// 3. $validate: HTTP 200 says nothing; count severities
OperationOutcome oo = (OperationOutcome) client.validate()
    .resource(p).execute().getOperationOutcome();
Map<String, Integer> sev = new TreeMap<>();
for (var issue : oo.getIssue())
  sev.merge(issue.getSeverity().toCode(), 1, Integer::sum);
log("validate POST Patient/$validate", sev.toString());
check(!sev.containsKey("fatal") && !sev.containsKey("error"),
    "invalid");

// 4. Conditional update on the identifier
client.update().resource(p).conditionalByUrl(byMrn).execute();
log("update   PUT  Patient?identifier=S|MRN", "");

Build and run it with Maven:

$ cd java
$ mvn -q compile
WARNING: A terminally deprecated method in sun.misc.Unsafe has been called
WARNING: sun.misc.Unsafe::objectFieldOffset has been called by com.google.common.util.concurrent.AbstractFuture$UnsafeAtomicHelper (file:/usr/share/maven/lib/guava.jar)
WARNING: Please consider reporting this to the maintainers of class com.google.common.util.concurrent.AbstractFuture$UnsafeAtomicHelper
WARNING: sun.misc.Unsafe::objectFieldOffset will be removed in a future release
$ export MAVEN_OPTS=--sun-misc-unsafe-memory-access=allow
$ mvn -q exec:java -Dexec.args=555-0101
search   GET  Patient?identifier=S|MRN   200  1 match, id 1015, v1
validate POST Patient/$validate          200  {information=2, warning=1}
update   PUT  Patient?identifier=S|MRN   200
re-read  GET  Patient?identifier=S|MRN   200  1 match, v2
history  GET  Patient/1015/_history      200  2 versions
PASS java: v1 -> v2, one patient

The first command warns four times before doing anything. Those warnings come from Maven 3.8.7 itself: its bundled Guava calls an internal JDK API (sun.misc.Unsafe) that JDK 25 now warns about. They are not from our code and not from HAPI. The JDK flag in MAVEN_OPTS allows the old API and silences them; a newer Maven is the real fix. Then the kata: version 1 to version 2, one match.

C#: Firely SDK

The Firely SDK is the standard FHIR library for .NET, and Microsoft's Azure FHIR service is built on it. Its FhirClient is async throughout, and it keeps the status of the last response in LastResult, so logging is one line. A conditional update is a method of its own:

// LastResult is the response line of the last call
void Log(string call, string note) => Console.WriteLine(
    $"{call,-40} {client.LastResult?.Status}  {note}".TrimEnd());

// 3. $validate: HTTP 200 says nothing; count severities
var oo = await client.ValidateResourceAsync(p);
var sev = oo.Issue.GroupBy(i => i.Severity.ToString().ToLower())
    .OrderBy(g => g.Key).Select(g => $"{g.Key}={g.Count()}");
Log("validate POST Patient/$validate",
    "{" + string.Join(", ", sev) + "}");
Check(!oo.Issue.Any(i =>
    i.Severity is Severity.Fatal or Severity.Error), "invalid");

// 4. Conditional update on the identifier
await client.ConditionalUpdateAsync(p, byMrn);
Log("update   PUT  Patient?identifier=S|MRN", "");
$ cd csharp
$ dotnet build -v q --nologo

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:01.71
$ dotnet run --no-build -- 555-0102
search   GET  Patient?identifier=S|MRN   200  1 match, id 1015, v2
validate POST Patient/$validate          200  {information=2, warning=1}
update   PUT  Patient?identifier=S|MRN   200
re-read  GET  Patient?identifier=S|MRN   200  1 match, v3
history  GET  Patient/1015/_history      200  3 versions
PASS csharp: v2 -> v3, one patient
$ cd ~/.nuget/packages/hl7.fhir.base/6.8.0/lib/net8.0
$ grep -c ValidateResourceAsync Hl7.Fhir.Base.dll Hl7.Fhir.Base.xml
Hl7.Fhir.Base.dll:3
Hl7.Fhir.Base.xml:0

Version 2 to 3. The last two commands show the gotcha in the table below: ValidateResourceAsync is in the compiled library but not in its XML documentation file, so your editor shows no help for it. If you search the docs for “validate” and find nothing, the method still exists.

Python: fhirclient

fhirclient is the SMART on FHIR project's Python client. It gives you model classes for every R4 resource (Patient, ContactPoint, OperationOutcome) and search through Patient.where(…).perform(server). It has no helper for a conditional update, so we drop down to server.put_json, and it doesn't expose status codes, so we hook the requests session it uses underneath. Here is the whole kata:

"""Week 0 kata: find by MRN, add a mobile, $validate,
conditional PUT, prove exactly one write."""
import os
import sys
from collections import Counter

from fhirclient import client
from fhirclient.models.contactpoint import ContactPoint
from fhirclient.models.operationoutcome import (
    OperationOutcome)
from fhirclient.models.patient import Patient

S = "http://hospital.smarthealthit.org"
mrn, mobile = os.environ["MRN"], sys.argv[1]
by_mrn = f"Patient?identifier={S}|{mrn}"

smart = client.FHIRClient(settings={
    "app_id": "kata", "api_base": os.environ["FHIR"]})
server = smart.server
status = None


def remember(res, *args, **kwargs):
    global status
    status = res.status_code


# fhirclient hides HTTP; a requests hook shows us each status
server.session.hooks["response"].append(remember)


def log(call, note=""):
    print(f"{call:<40} {status}  {note}".rstrip())


def check(ok, why):
    if not ok:
        sys.exit(f"FAIL python: {why}")


def search():
    return Patient.where(
        {"identifier": f"{S}|{mrn}"}).perform(server)


# 1. Search by identifier (never _id: server id is not the MRN)
found = search()
check(found.total == 1, f"expected 1 match, got {found.total}")
p = found.entry[0].resource
before = int(p.meta.versionId)
log("search   GET  Patient?identifier=S|MRN",
    f"1 match, id {p.id}, v{before}")

# 2. Replace any mobile number with ours
p.telecom = [t for t in p.telecom or [] if t.use != "mobile"]
p.telecom.append(ContactPoint(
    {"system": "phone", "use": "mobile", "value": mobile}))

# 3. $validate: HTTP 200 says nothing; count the severities
res = server.post_json("Patient/$validate", p.as_json())
oo = OperationOutcome(res.json())
sev = Counter(i.severity for i in oo.issue)
log("validate POST Patient/$validate",
    "{" + ", ".join(f"{k}={n}" for k, n in sorted(sev.items()))
    + "}")
check(not {"fatal", "error"} & sev.keys(), "invalid")

# 4. Conditional update on the identifier (no helper for it)
server.put_json(by_mrn, p.as_json())
log("update   PUT  Patient?identifier=S|MRN")

# 5. Read back: still one patient, one version more
again = search()
after = int(again.entry[0].resource.meta.versionId)
log("re-read  GET  Patient?identifier=S|MRN",
    f"{again.total} match, v{after}")
check(again.total == 1, "duplicate patient")
check(after == before + 1, f"expected v{before + 1}, got v{after}")

# 6. History holds every version: none lost, none extra
hist = server.request_json(f"Patient/{p.id}/_history")
log(f"history  GET  Patient/{p.id}/_history",
    f"{hist['total']} versions")
check(hist["total"] == after, f"history has {hist['total']}")

print(f"PASS python: v{before} -> v{after}, one patient")
$ cd python
$ cat requirements.txt
fhirclient==4.4.0
$ python3 -m venv .venv
$ .venv/bin/pip install -q -r requirements.txt
$ .venv/bin/python kata.py 555-0103
search   GET  Patient?identifier=S|MRN   200  1 match, id 1015, v3
validate POST Patient/$validate          200  {information=2, warning=1}
update   PUT  Patient?identifier=S|MRN   200
re-read  GET  Patient?identifier=S|MRN   200  1 match, v4
history  GET  Patient/1015/_history      200  4 versions
PASS python: v3 -> v4, one patient

TypeScript: fhirclient and Express

The JavaScript fhirclient comes from the same SMART project, and its main job is SMART on FHIR: apps launched from inside an EHR, which week 4 builds. On a server, you import fhirclient/node and create a client per HTTP request with smart(req, res), because a SMART launch is a conversation with the user's browser. So in TypeScript the kata is an Express route, and you run it with curl:

app.get("/kata/:mobile", async (req, res) => {
  const client = smart(req, res).client(FHIR);
  const out: string[] = [];
  let status = 0;

  async function call<T>(method: string, url: string, body?: object) {
    const r = await client.request<{ body: T; response: Response }>({
      url, method, includeResponse: true,
      headers: { "content-type": "application/fhir+json" },
      body: body && JSON.stringify(body),
    });
    status = r.response.status;
    return r.body;
  }

Asking for includeResponse: true returns the response next to the body, which is how we get the status. TypeScript checks our use of FHIR types at build time, through the type definitions fhirclient pulls in, so found.entry![0].resource! has to admit that a Bundle might be empty.

$ cd typescript
$ npm install --no-audit --no-fund

added 82 packages in 2s
$ npm run build

> build
> tsc
$ node dist/server.js & sleep 2
kata on http://localhost:3000/kata/:mobile
$ curl -s localhost:3000/kata/555-0104
search   GET  Patient?identifier=S|MRN   200  1 match, id 1015, v4
validate POST Patient/$validate          200  {information=2, warning=1}
update   PUT  Patient?identifier=S|MRN   200
re-read  GET  Patient?identifier=S|MRN   200  1 match, v5
history  GET  Patient/1015/_history      200  5 versions
PASS typescript: v4 -> v5, one patient
$ kill %1

We didn't need express-session here, because we never ran a SMART launch: our server is open and needs no authorization. In a SMART app the library keeps the launch state in req.session between the redirect to the authorization server and the return; that is why SMART needs express-session (see the table below).

What differs, and what doesn't

StackLibrary (tested)Gotcha we hit
JavaHAPI FHIR 8.2 (OIE itself is Java)The client hides HTTP status codes; an interceptor exposes them
C#Firely SDK 6.8 on .NET 8 (Azure's FHIR service is built on it)ValidateResourceAsync is missing from the XML docs
Pythonfhirclient 4.4No helper for a conditional update, and no status codes without a hook
TypeScriptfhirclient 3.0, ExpressImport fhirclient/node; SMART needs express-session

We installed these versions of the FHIR clients: HAPI FHIR 8.2.2, Hl7.Fhir.R4 6.8.0, fhirclient 4.4.0 and fhirclient 3.0.1. Two more gotchas wait for later weeks, and we did not re-run them this week: HAPI HL7v2's default validation rejects a bad PID-7 (week 3 and the Java extra), and the Python package fhir.resources no longer ships R4.

The shape is identical in all four; the friction moves around. Java needs the most ceremony: a build file, a fluent API and an interceptor just to see status codes. C# came out shortest (66 lines against 86 to 98 for the others), because conditional update, validation and history are each one method. Python's library stops at search, so the write is raw JSON. TypeScript made us think about the request we run inside, which pays off once there is a real user and a real login. After each run, write down what was easier or harder; that note is what you bring to an interview.

Proving exactly one write

Each kata asserted its own write. Now check the total from outside, with the server's history, which holds every version of the resource:

$ curl -s "$FHIR/Patient?identifier=$S|$MRN&_summary=count" \
  | jq .total
1
$ curl -s "$FHIR/Patient/$ID/_history" | jq -r '.entry[]
  | [.resource.meta.versionId, .request.method,
     (.resource.telecom | map(select(.use=="mobile").value)
      | join(","))] | @tsv'
5	PUT	555-0104
4	PUT	555-0103
3	PUT	555-0102
2	PUT	555-0101
1	POST	
$ cd python && .venv/bin/python kata.py 555-0104; echo "exit $?"
search   GET  Patient?identifier=S|MRN   200  1 match, id 1015, v5
validate POST Patient/$validate          200  {information=2, warning=1}
update   PUT  Patient?identifier=S|MRN   200
re-read  GET  Patient?identifier=S|MRN   200  1 match, v5
FAIL python: expected v6, got v5
exit 1

Still one patient with that MRN, and five versions: the original load, then one PUT per stack, each with its own mobile number. That is the proof: the count shows no duplicate was created, and the history shows exactly one new version per run, so nothing was lost and nothing was written twice.

The last command is the interesting one. We ran the Python kata again with the number TypeScript had already written. The PUT answered 200, but the version stayed at 5 and the kata failed: HAPI saw that nothing had changed and created no version. That is good behaviour, since an interface that receives the same update twice shouldn't grow the history, and the failure is honest: the kata was asked to prove a write, and none happened. Exercise 3 asks you to tell those two cases apart.

Conditional updates and their failure modes

A conditional update is PUT Patient?identifier=…: the server runs the search, and what it does depends on how many matches it finds. It updates one match, creates if none, and fails with 412 if several. The specification lists those cases (and a fourth: one match, but the body carries a different id, which is a 400). Notice that the R4 specification still marks conditional create, update, patch and delete as trial use. Servers differ at the edges, so test the one you deploy against.

Creates if none

The test patient is hand-made, with an example.org identifier system so that nobody mistakes it for a real MRN:

$ H='Content-Type: application/fhir+json'
$ cat test-patient.json
{
  "resourceType": "Patient",
  "identifier": [
    {"system": "http://example.org/mrn", "value": "100235"}
  ],
  "name": [{"family": "Kata", "given": ["Test"]}],
  "telecom": [{"system": "phone", "value": "555-0100", "use": "home"}],
  "birthDate": "1980-02-14"
}
$ Q="$FHIR/Patient?identifier=http://example.org/mrn|100235"
$ curl -s -o /dev/null -w '%{http_code}\n' -X PUT -H "$H" \
  -d @test-patient.json "$Q"
201
$ curl -s -o /dev/null -w '%{http_code}\n' -X PUT -H "$H" \
  -d @test-patient.json "$Q"
200
$ curl -s "$Q" | jq -c '[.total, .entry[0].resource.meta.versionId]'
[1,"1"]

201 Created the first time, 200 the second, and still one patient at version 1: the second PUT matched the first patient and, as before, changed nothing. This is the upsert that interfaces want. A sender can repeat a message as often as it likes, and the record ends up the same.

POST is not an upsert

Now do what the conditional PUT replaces: POST the same patient twice.

$ H='Content-Type: application/fhir+json'
$ jq '.identifier[0].value="100236"' test-patient.json > dupe.json
$ for i in 1 2; do
  curl -s -o /dev/null -w '%{http_code}\n' -H "$H" \
    -d @dupe.json "$FHIR/Patient"
done
201
201
$ Q="$FHIR/Patient?identifier=http://example.org/mrn|100236"
$ curl -s "$Q&_summary=count" | jq .total
2
$ curl -s -o oo.json -w '%{http_code}\n' -X PUT -H "$H" \
  -d @dupe.json "$Q"
412
$ jq -r '.issue[0].diagnostics' oo.json
HAPI-0988: Failed to UPDATE Patient with match URL "Patient?identifier=http://example.org/mrn|100236" because this search matched 2 resources

Don't use POST for upserts. Two POSTs made two patients in our test, with the same MRN, and the server accepted both without complaint, because a plain create doesn't search first. Now the conditional PUT can't decide which record to update, so it refuses with 412 Precondition Failed. That refusal is the right answer and it is also bad news: a person now has to work out whether these are one patient or two and merge them. Keep POST for things that are new by definition, and use conditional writes for anything that might be repeated. Synthea's patient bundle uses plain POSTs, so that is worth remembering before you load it twice (exercise 4).

Canada: the same rules apply, and the identifier shared across organizations is usually the provincial health card number. The R4 identifier type value set we met above includes JHN, jurisdictional health number, for it. Canada's counterpart of US Core is CA Core+, led by Canada Health Infoway; we didn't validate against it here.

Version-aware updates with If-Match

The last problem is two writers. Registration and a patient portal both read version 1, both change something, both write. Without a check, the second write silently undoes the first. The fix is to send the version you read in an If-Match header, so the server refuses the write if someone got there first. Try it on the test patient: one write with the right version, then a second write that still claims version 1, then the same stale header on a conditional PUT:

$ H='Content-Type: application/fhir+json'
$ Q="$FHIR/Patient?identifier=http://example.org/mrn|100235"
$ T=$(curl -s "$Q" | jq -r '.entry[0].resource.id')
$ curl -s "$FHIR/Patient/$T" | jq '.active=false' > t.json
$ curl -s -o /dev/null -w '%{http_code}\n' -X PUT -H "$H" \
  -H 'If-Match: W/"1"' -d @t.json "$FHIR/Patient/$T"
200
$ jq '.active=true' t.json > t2.json
$ curl -s -o oo.json -w '%{http_code}\n' -X PUT -H "$H" \
  -H 'If-Match: W/"1"' -d @t2.json "$FHIR/Patient/$T"
409
$ jq -r '.issue[0].diagnostics' oo.json
HAPI-0550: HAPI-0989: Trying to update Patient/5766/_history/1 but this is not the current version
$ curl -s -o /dev/null -w '%{http_code}\n' -X PUT -H "$H" \
  -H 'If-Match: W/"1"' -d @t2.json "$Q"
200
$ curl -s "$FHIR/Patient/$T" | jq -c '[.meta.versionId, .active]'
["3",true]

The first write made version 2. The stale write was refused, but with 409 Conflict, although the specification says a server returns 412 Precondition Failed when the version doesn't match; client code that only checks for 412 will miss it. And the conditional PUT ignored the stale header and made version 3. If you need both, find the record by identifier, then update it by id with If-Match, and treat 409 and 412 the same.

Tested: the 409 and the ignored header are what HAPI FHIR 8.12.0 did. We didn't try other servers; run this session against the one you deploy before you rely on either behaviour.

Three more stacks to recognise

You will meet more than four stacks. Three more are worth an hour each in a container, just so you recognise them in a job description: PowerShell, InterSystems IRIS and MUMPS (via YottaDB). PowerShell turns up in Windows-heavy hospital IT for scripting servers and interfaces. InterSystems IRIS is the platform under InterSystems' health products, including the HealthShare Health Connect integration engine; pull its image from InterSystems' own registry, because the Docker Hub image crashed for us. MUMPS is a programming language with its own built-in database, and YottaDB is an open-source implementation of it. We last ran these three before this version of the course and did not re-test them.

Pick the stack you want to be hired into and go deep: make its kata yours, then add the extras in the exercises. Give the other three an hour or two each, enough to read their code and run it.

AI this week: let it scaffold files in an unfamiliar stack; write the assertions yourself.

Exercises

  1. Why can't you look a patient up by _id when all you hold is an MRN? Use the two searches from the REST section in your answer, and say why a hard-coded server id is a bug even though Corie was Patient/1015 on every fresh server we started.
  2. What does a conditional PUT do when two patients match? Reproduce the 412 from your main stack's client, and make your kata print the OperationOutcome's diagnostics instead of a stack trace.
  3. How do you prove exactly one write happened? Change your kata so that a second run with the same number reports “no change, still v5” and passes, while a run that creates a second patient or skips a version still fails.
  4. POST the patient bundle a second time. How many patients have Corie's MRN now? Look at the request of the first entry in the patient bundle and of the first entry in the hospital bundle, and explain why only one of them is safe to load twice.
  5. Add If-Match to your main stack's kata: search by identifier, then update by id with the version you read. Run two copies at once with different numbers. One should fail with 409 (on HAPI) or 412; make the kata say which.
  6. Validate the US Core version of Corie with the HL7 validator (validator_cli.jar from the prework, with the US Core package loaded) instead of the server. Which of the two errors disappear, and do new ones appear?
  7. Java extra: with HAPI HL7v2, parse an ADT message with an impossible birth date in PID-7 and answer it with an AE acknowledgment rather than an exception. Week 3 has sample messages.
  8. Python extra: write a function that strips a Patient down to an allowlist of elements before it is logged or exported, so no identifier can leave by accident. Test it on Corie, who carries an SSN, a driver's licence and a passport number.
  9. TypeScript extra: turn the Express app into a SMART app that lists the patient's lab results, with express-session holding the launch state.

Read

Tested with

Every command on this page was run on 31 Oct 2026 against the course lab: a local HAPI FHIR 8.12.0 server in Docker, Synthea (master build of 21 Oct 2026), the HAPI FHIR 8.2.2 client on OpenJDK 25, Firely SDK 6.8.0 on .NET SDK 8.0.121, fhirclient 4.4.0 on Python 3.12, and fhirclient 3.0.1 with Express 5.3 on Node 20. The outputs are copied from those runs. Yours will differ in timestamps, server ids and file names.


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.