Most healthcare MVPs live or die on one integration: reading from and writing to the hospital’s EHR. If a clinician has to retype vitals from your app into the chart, the pilot is over. In the US that integration surface is now mostly a FHIR API: the federal certification criterion for patient and population API access (ONC § 170.315(g)(10)) names HL7 FHIR Release 4.0.1, US Core and SMART App Launch 2.0.0 as the required standards.
The catch is that you cannot develop against a hospital’s production EHR, and you must not copy real patient data into a dev environment. So this post builds the next best thing: a small, spec-faithful FHIR R4 server stub in Python that runs locally and in CI, plus a client that talks to it the same way it would talk to a real server.
What we will build and test:
- Resource models and validation with fhir.resources (and the R4 vs R5 import trap).
- Errors as OperationOutcome, with the right HTTP status for each failure.
- create and conditional create with If-None-Exist.
- Search parameters: patient, code (token), date with ge/le prefixes and precision.
- Bundle paging with link[next], and _include.
- Resource versions, ETag and If-Match to stop lost updates.
- SMART on FHIR scopes, conceptually.
Stack: Python 3.13, fhir.resources 8.3.0, pydantic 2.14.2, fastapi 0.162.0, httpx 0.28.1, pytest 9.2.0. Every output block below is copied from a real run of the code. All data is synthetic: generated names, fake MRNs under an urn:example system, random heart rates.
Request flow: a Python client calls the local FastAPI FHIR stub, which validates with R4B models, stores versions in memory and answers with Bundles or OperationOutcomes
What is a FHIR API, in one table
FHIR (Fast Healthcare Interoperability Resources) models clinical data as typed JSON resources (Patient, Observation, Condition, …) and exposes them over a REST API with a fixed set of interactions. R4 (version 4.0.1, published October 30, 2019) is the release most production EHR APIs speak today. Epic’s developer site, for example, lists its resources under DSTU2, STU3 and R4 and offers a sandbox with test data; the patterns below are the ones you will meet there.
| Interaction | HTTP | Success | Typical failures |
|---|---|---|---|
read |
GET [base]/Patient/123 |
200 + ETag
|
404, 410 (deleted) |
vread |
GET [base]/Patient/123/_history/2 |
200 |
404 |
create |
POST [base]/Observation |
201 + Location + ETag
|
400, 422
|
conditional create |
POST + If-None-Exist: identifier=...
|
201 or 200
|
412 (multiple matches) |
update |
PUT [base]/Patient/123 + If-Match
|
200 |
400, 412, 422
|
search |
GET [base]/Observation?patient=123&date=ge2026-03-10 |
200 + Bundle
|
400 |
Content type is application/fhir+json, and every failure body is an OperationOutcome. Keep this table in mind: the rest of the post implements and tests each row.
Project layout
code/
fhirlab/models.py # R4B models + validation -> OperationOutcome
fhirlab/search.py # token, reference, string, date search
fhirlab/server.py # FastAPI stub: create, read, vread, update, search
fhirlab/client.py # httpx client: paging, If-None-Exist, If-Match
fhirlab/synthetic.py # deterministic synthetic patients and vitals
fhirlab/smart.py # SMART scope check (illustration)
demo.py # every scenario in this post
tests/ # 20 pytest tests
Step 1. Model and validate resources (and the R4 vs R5 trap)
fhir.resources generates pydantic v2 models from the FHIR spec, which gives you parsing and structural validation for free. The trap: since version 7.0.0 the package root is R5, and there is no separate R4 sub-package. R4-compatible models live under fhir.resources.R4B. R4B is a small update to R4, and for Patient and Observation the changes do not affect this code. If you write from fhir.resources.encounter import Encounter against an R4 server, valid R4 data fails:
R4B model: AMB
default (R5) model: ('class',) Input should be a valid list
In R4, Encounter.class is a single Coding; in R5 it became a list of CodeableConcept. The error is loud here, but other R4/R5 differences are silent field renames, so pin the import path in one module:
def validate(resource_type: str, body: dict) -> dict:
"""Parse and validate a resource; return normalized JSON or raise FhirError(400)."""
if resource_type not in MODELS:
raise FhirError(404, "not-supported", f"Resource type {resource_type} is not supported")
if body.get("resourceType") != resource_type:
raise FhirError(400, "invalid",
f"resourceType is {body.get('resourceType')!r}, URL expects {resource_type!r}")
try:
model = MODELS[resource_type].model_validate(body)
except ValidationError as exc:
issues = [f"{resource_type}." + ".".join(str(p) for p in err["loc"]) for err in exc.errors()]
msgs = "; ".join(err["msg"] for err in exc.errors())
raise FhirError(400, "structure", msgs, expression=issues) from None
if resource_type == "Observation" and model.status not in OBSERVATION_STATUS:
raise FhirError(400, "code-invalid",
f"Observation.status {model.status!r} is not in ObservationStatus",
expression=["Observation.status"])
return model.model_dump(mode="json", exclude_none=True)
Two things worth knowing about what the models do and do not check:
- They reject unknown fields. A typo such as valu instead of value[x] fails with extra_forbidden. That is good: a misspelled field otherwise vanishes silently.
- They do not enforce required terminology bindings. Observation.status is a code with a required binding to ObservationStatus, yet the model accepts "status": "done". The server above checks that value set itself. Profile validation (US Core, for example) is another layer again; in production you would add a validator service, not hand-written checks.
Step 2. Return errors as OperationOutcome, with the right status
A FHIR client should never have to parse an HTML error page. Every failure in the stub raises one exception type that carries the HTTP status and a single OperationOutcome.issue with severity, code, diagnostics and expression (the FHIRPath of the bad element). A catch-all handler turns unexpected exceptions into a 500 exception outcome without a stack trace.
Which status? The R4 HTTP page separates content that fails basic FHIR validation (400) from content that is valid FHIR but violates profiles or business rules (422). The stub uses 422 for one rule: an Observation.subject must point to a Patient that exists.
400 application/fhir+json {"severity": "error", "code": "code-invalid", "diagnostics": "Observation.status 'done' is not in ObservationStatus", "expression": ["Observation.status"]}
400 {"severity": "error", "code": "structure", "diagnostics": "Extra inputs are not permitted", "expression": ["Observation.valu"]}
400 {"severity": "error", "code": "structure", "diagnostics": "Value error, DateTime value string does not match spec regex.", "expression": ["Observation.effectiveDateTime"]}
422 {"severity": "error", "code": "business-rule", "diagnostics": "Referenced Patient/does-not-exist does not exist", "expression": ["Observation.subject"]}
404 {"severity": "error", "code": "not-found", "diagnostics": "Patient/nope is not known"}
Line three deserves attention. heart_rate(..., datetime(2026, 3, 1, 9, 30)) was built from a naive Python datetime, so isoformat() produced 2026-03-01T09:30:00 with no offset. The R4 dateTime type requires a time zone whenever a time is present, and the model rejects it. Always build timestamps with tzinfo=timezone.utc.
Step 3. Create, and create only once with If-None-Exist
POST [base]/Patient returns 201 with a Location header pointing at the new version (/Patient/{id}/_history/1) and a weak ETag such as W/"1". The server assigns the id and ignores any id you send.
Retries are where MVPs make duplicate patients. A network timeout after a successful POST, then a retry, and the same person exists twice. Conditional create fixes this: the client sends the search that identifies the record in an If-None-Exist header (the query string without the ?), and the server applies three rules from the spec:
- no match: create, 201;
- one match: do nothing, return 200 with the existing resource;
- more than one match: 412 Precondition Failed.
@app.post("/{rtype}")
async def create(rtype: str, req: Request):
resource = validate(rtype, await read_body(req))
resource.pop("id", None) # create ignores any client-supplied id
check_references(resource)
with store.lock:
condition = req.headers.get("if-none-exist")
if condition:
_, hits = run_search(rtype, parse_qsl(condition), strict=True)
if len(hits) == 1: # already there: do nothing, return 200
return fhir_response(hits[0], 200, version_headers(base(req), hits[0]))
if len(hits) > 1:
raise FhirError(412, "multiple-matches",
f"If-None-Exist '{unquote(condition)}' matched {len(hits)} resources")
saved = store.put(rtype, uuid.uuid4().hex[:12], resource)
if req.headers.get("prefer") == "return=minimal":
return fhir_response(None, 201, version_headers(base(req), saved))
return fhir_response(saved, 201, version_headers(base(req), saved))
attempt 1: HTTP 201 id=6877ed419d0a version=1
attempt 2: HTTP 200 id=6877ed419d0a version=1
after a plain duplicate POST: HTTP 412 multiple-matches: If-None-Exist 'identifier=urn:example:synthetic-mrn|SYN-0001' matched 2 resources
The third line shows why the rule exists: once a plain POST has created a duplicate, the server cannot know which record you meant. Note the lock around search plus insert. Without it, two concurrent conditional creates can both see zero matches and both insert. A real server needs the same guarantee from its database (a unique index on the identifier, or a serializable transaction).
Step 4. Search parameters: token, reference and date
FHIR search is a query language in the URL. The stub implements the parameters an MVP touches first:
| Parameter | Type | Example | Matches |
|---|---|---|---|
patient |
reference | patient=123 |
Observation.subject = Patient/123 |
code |
token |
code=http://loinc.org|8867-4
|
coding with that system and code |
code |
token | code=8867-4 |
that code in any system |
date |
date | date=ge2026-03-10 |
Observation.effective[x] |
identifier |
token |
identifier=urn:example:synthetic-mrn|SYN-1000
|
Patient.identifier |
Repeating a parameter means AND; a comma inside one value means OR. That is how you express a range: date=ge2026-03-10&date=le2026-03-20.
Dates are the part most hand-rolled implementations get wrong. In FHIR a date is an implicit range set by its precision: 2026-03 is the whole month, 2026-03-14 is the whole day. The prefixes are defined in terms of ranges too. For ge, the spec says the target matches if the range above the search value overlaps it, or if the search value’s range fully contains it. So a reading stored with month precision (2026-03) matches both ge2026-03-14 and le2026-03-14, and an open-ended Period that starts on 2013-01-21 matches both ge2013-03-14 and le2013-03-14 (the spec’s own example).
def date_range(value: str) -> tuple[datetime, datetime]:
"""Turn a FHIR date/dateTime of any precision into a half-open UTC range [start, end).
'2026-03' covers the whole month. Values without a time zone use the server
time zone, which is UTC here.
"""
m = DATE_RE.match(value)
if not m:
hint = " (a '+' in a query string must be sent as %2B)" if " " in value else ""
raise FhirError(400, "value", f"Invalid date {value!r}{hint}")
y, mo, d = int(m["y"]), int(m["m"] or 1), int(m["d"] or 1)
tz = timezone.utc
if m["tz"] and m["tz"] != "Z":
sign = 1 if m["tz"][0] == "+" else -1
hh, mm = map(int, m["tz"][1:].split(":"))
tz = timezone(sign * timedelta(hours=hh, minutes=mm))
start = datetime(y, mo, d, int(m["H"] or 0), int(m["M"] or 0), int(m["S"] or 0), tzinfo=tz)
if m["S"]:
end = start + timedelta(seconds=1)
elif m["M"]:
end = start + timedelta(minutes=1)
elif m["d"]:
end = start + timedelta(days=1)
elif m["m"]:
end = datetime(y + mo // 12, mo % 12 + 1, 1, tzinfo=tz)
else:
end = datetime(y + 1, 1, 1, tzinfo=tz)
return start.astimezone(timezone.utc), end.astimezone(timezone.utc)
def match_date(param: str, resource: dict) -> bool:
prefix, value = ("eq", param)
if param[:2] in PREFIXES:
prefix, value = param[:2], param[2:]
elif param[:2].isalpha():
raise FhirError(400, "not-supported", f"Date prefix {param[:2]!r} is not supported")
ps, pe = date_range(value)
t = target_range(resource)
if t is None:
return False
ts, te = t
contains = ps <= ts and te <= pe
return {
"eq": contains,
"ne": not contains,
"gt": te > pe, # range above the value overlaps the target
"lt": ts < ps, # range below the value overlaps the target
"ge": te > pe or contains,
"le": ts < ps or contains,
"sa": ts >= pe, # starts after
"eb": te <= ps, # ends before
}[prefix]
Running it against nine synthetic heart-rate readings for one patient, spread through March 2026:
date=2026-03 -> 9
date=ge2026-03-10 -> 6
date=le2026-03-10 -> 4
ge2026-03-10 & le2026-03-20 -> 4
2026-03-10T15:00:00Z 95 bpm
2026-03-13T12:00:00Z 58 bpm
2026-03-16T10:00:00Z 85 bpm
2026-03-19T13:00:00Z 75 bpm
unencoded '+' in tz -> 400 Invalid date '2026-03-10T00:00:00 02:00' (a '+' in a query string must be sent as %2B)
encoded %2B -> 200 total 6
Note that 6 + 4 is 10, not 9. The reading at 2026-03-10T15:00:00Z sits inside the one-day range of 2026-03-10, so both ge and le match it. That is the spec working as designed, and it is why a range query uses ge on one side and lt (or le on the last included day) on the other, chosen deliberately.
The last two lines show a bug that will hit your client sooner or later. In a query string + decodes to a space, so ge2026-03-10T00:00:00+02:00 arrives as ...T00:00:00 02:00. Use %2B or let httpx/urlencode build the query. The stub returns a 400 with a hint instead of quietly matching nothing.
FHIR date search: how ge, le and eq compare implicit ranges for a dateTime, a month-precision value and an open Period
LOINC and SNOMED CT in test data. The synthetic generator uses real codes so that searches look like production queries: LOINC 8867-4 (Heart rate) and 29463-7 (Body weight), and SNOMED CT 36225005 taken from the HL7 R4 Condition example. The codes are real; every patient, identifier and value attached to them is generated. That follows the advice in the PixelPlex healthcare MVP guide: keep real patient data out of development and test with synthetic records.
Step 5. Bundles, paging and _include
A search returns a Bundle of type searchset. Bundle.total counts matches across all pages; it does not count included resources. Paging uses links: self, and when there is more, next (also previous, first, last). The R4 spec states that these links are opaque to the client and that the client must use the server-supplied links. So the client loop is simple and does no URL math:
def search(self, rtype: str, params: dict | list, max_pages: int = 100) -> SearchResult:
"""Run a search and follow Bundle.link[next] until it disappears."""
out = SearchResult()
url: str | None = f"/{rtype}?{urlencode(params, doseq=True)}"
while url and out.pages < max_pages:
bundle = self._check(self.http.get(url, headers=self.headers)).json()
out.pages += 1
out.total = bundle.get("total", out.total)
for e in bundle.get("entry", []):
res = e["resource"]
if e.get("search", {}).get("mode") == "include":
out.included[f"{res['resourceType']}/{res['id']}"] = res
else:
out.matches.append(res)
# links are opaque: use them as-is, never rebuild them from _offset math
url = next((l["url"] for l in bundle.get("link", []) if l["relation"] == "next"), None)
return out
The naive version reads only the first page, and the bug hides well because the first page looks like a complete answer:
naive client (first page only): 10 observations
following link[next]: 27 observations in 3 pages, Bundle.total=27
On the server side, a continuation must not re-run the query. If a new observation arrives between page 1 and page 2, an offset-based re-query shifts everything by one and the client sees a duplicate or misses a record. The spec leaves the method to the server (“at the discretion of the server how to best ensure that the continuation retains integrity”). The stub stores a snapshot of matching ids and puts its key in the next link:
if "_getpages" in q: # continuation: the snapshot, not a new query
snap = pages.get(q["_getpages"])
if snap is None or snap["type"] != rtype:
raise FhirError(410, "not-found", "Search snapshot expired; run the search again")
ids, used, includes = snap["ids"], snap["used"], snap["includes"]
offset = int(q.get("_offset", 0))
else:
strict = "handling=strict" in req.headers.get("prefer", "")
used, hits = run_search(rtype, params, strict)
ids, offset = [r["id"] for r in hits], 0
snap_id = uuid.uuid4().hex
pages[snap_id] = {"type": rtype, "ids": ids, "used": used, "includes": includes}
q["_getpages"] = snap_id
page = [store.current(rtype, i) for i in ids[offset: offset + count]]
root = base(req)
entries = [{"fullUrl": f"{root}/{rtype}/{r['id']}", "resource": r,
"search": {"mode": "match"}} for r in page]
seen = set()
for inc in includes:
element, target = INCLUDES[inc]
for r in page:
ref = r.get(element, {}).get("reference", "")
ttype, _, tid = ref.partition("/")
if (target and ttype != target) or (ttype, tid) in seen or (ttype, tid) not in store.history:
continue
seen.add((ttype, tid))
entries.append({"fullUrl": f"{root}/{ref}", "resource": store.current(ttype, tid),
"search": {"mode": "include"}})
self_q = used + [("_count", str(count))] + [("_include", i) for i in includes]
links = [{"relation": "self", "url": f"{root}/{rtype}?{urlencode(self_q)}"}]
nav = {"_getpages": q["_getpages"], "_count": count}
if offset + count < len(ids):
links.append({"relation": "next",
"url": f"{root}/{rtype}?{urlencode({**nav, '_offset': offset + count})}"})
if offset > 0:
links.append({"relation": "previous",
"url": f"{root}/{rtype}?{urlencode({**nav, '_offset': max(offset - count, 0)})}"})
bundle = {"resourceType": "Bundle", "type": "searchset", "total": len(ids),
"link": links, "entry": entries}
_include saves round trips. Observation?code=...&_include=Observation:patient returns the matching observations plus the referenced patients, each marked with search.mode = include. The client indexes them by Patient/{id} so it can resolve subject.reference without another request:
matches=27 included patients=3 total=27
first match: 2026-03-04T11:00:00Z -> Alex Testpatient
page 1 entry modes: ['match', 'match', 'include', 'include'] total: 27
Two more search rules the spec spells out. Servers must never return more than _count resources, but may return fewer, so cap it. And servers should ignore unknown parameters unless the client sends Prefer: handling=strict. Lenient mode is dangerous with typos: valeu-quantity=gt100 is silently dropped, and the patient’s full history comes back as if every value were above 100. The self link shows which parameters the server actually used, so check it, or use strict handling in tests:
lenient: 200 total 9 | self: patient=514b67a9330c&_count=10
strict: 400 {"severity": "error", "code": "not-supported", "diagnostics": "Unknown search parameter(s): valeu-quantity"}
FHIR search Bundle anatomy: total, self and next links, match and include entries across three pages
Step 6. Versions, ETag and If-Match
Every write creates a new version. The server returns it as meta.versionId and as a weak ETag (W/"3"), and vread gives you any old version. With that, optimistic locking takes a few lines: send the ETag you read as If-Match, and the server refuses the update with 412 if someone else wrote in between.
with store.lock:
if (rtype, rid) not in store.history:
raise FhirError(405, "not-supported", "Update-as-create (client-assigned ids) is disabled")
current = store.current(rtype, rid)
if_match = req.headers.get("if-match")
if if_match is None and require_if_match:
raise FhirError(400, "required", "This server requires If-Match on update")
expected = f'W/"{current["meta"]["versionId"]}"'
if if_match is not None and if_match != expected:
raise FhirError(412, "conflict",
f"If-Match {if_match} does not match current version {expected}")
saved = store.put(rtype, rid, resource)
The demo has two “clinicians” open the same synthetic patient. A adds a phone number, B adds an address, both based on version 1:
both read W/"1"
without If-Match: W/"3" telecom=False address=True <- phone lost
A with If-Match W/"3" -> W/"4"
B with If-Match W/"3" -> HTTP 412 conflict: If-Match W/"3" does not match current version W/"4"
B retried -> W/"5" telecom=True address=True
vread _history/1: telecom=False address=False
vread _history/2: telecom=True address=False
vread _history/3: telecom=False address=True
vread _history/4: telecom=True address=True
vread _history/5: telecom=True address=True
Lost update vs If-Match: without If-Match the second PUT overwrites the phone number; with If-Match it gets 412, re-reads and retries, and version 5 keeps both changes
Without If-Match, B’s write silently replaces A’s (version 3 has the address but no phone). With If-Match, B gets a 412, re-reads, re-applies its change and retries, and version 5 has both. History keeps every version, which also gives you a free audit trail of what changed. Some servers make If-Match mandatory and answer 400 without it; create_app(require_if_match=True) reproduces that, and one test covers it. The spec also allows 409 Conflict in some servers (for example with server-side locking), so handle both in the client.
Step 7. SMART on FHIR scopes, conceptually
A real EHR will not let your app call these endpoints without OAuth 2.0. SMART App Launch defines how the app gets a token and what the token allows. The scopes look like this (SMART v2 syntax):
| Scope | Meaning |
|---|---|
patient/Observation.rs |
read and search Observations for the patient in context |
user/*.cruds |
everything the logged-in user may access |
system/*.rs |
backend service, read and search, for example bulk export |
launch/patient |
ask the EHR to pick a patient at launch |
openid fhirUser |
identity token plus the FHIR URL of the current user |
offline_access |
refresh token that outlives the session |
The permission letters are a subset of cruds in that order: create, read (also vread and instance history), update, delete, search. SMART v1 used .read and .write; they map to .rs and .cud. A v2 scope can also carry a query restriction, such as patient/Observation.rs?category=...|laboratory. A tiny check in smart.py shows the mapping (in a real server the scopes come from a validated token, and query-restricted scopes need extra filtering):
Observation search -> True
Observation create -> False
Patient read -> True
Condition search -> False
For an MVP, ask for the narrowest scopes your first feature needs. A vitals dashboard needs patient/Observation.rs and patient/Patient.rs, not user/*.cruds.
Tests
The suite pins down every rule above: 201 + Location + W/"1", conditional create for 0/1/many matches, OperationOutcome codes for 400/404/412/422, paging without duplicates, snapshot stability when data changes between pages, the _count cap, _include modes and total, lenient vs strict parameters, date prefix semantics including the spec’s open-Period example, the %2B hint, lost-update prevention, mandatory If-Match, vread, and SMART scope mapping.
20 passed in 1.90s
Gotchas we hit while building this
- Wrong FHIR version from the default import. fhir.resources 8.x defaults to R5. Use fhir.resources.R4B for R4 servers.
- Naive datetimes. A dateTime with a time must carry a time zone. Python’s datetime.isoformat() omits it unless you set tzinfo.
- Model-valid is not spec-valid. Required bindings (like Observation.status) and profiles are not enforced by the pydantic models.
- First-page-only clients. 10 of 27 results looked like a full answer. Follow link[next] until it is gone.
- Lenient search with a typo returns more data than you asked for. Check the self link or use Prefer: handling=strict.
- + in time zone offsets turns into a space in query strings.
- Duplicates on retry. Use If-None-Exist on a business identifier, and back it with a unique constraint.
- Lost updates. Send If-Match on every PUT.
- Unbounded snapshots. The stub keeps search snapshots forever. A real server needs a TTL and returns an error (the stub uses 410) when a page link expires.
From stub to a real server
The stub is for fast feedback and CI, not production. When you connect to a real endpoint (a vendor sandbox, an open-source server such as HAPI FHIR, or a hospital’s test environment):
- Read GET [base]/metadata first. The CapabilityStatement lists the resources, interactions, search parameters and _include values the server supports. Do not assume yours match the stub.
- Expect implementation guides. In the US that means US Core profiles and the searches US Core requires servers to support.
- Keep the client generic: it already takes any httpx.Client, so FhirClient(httpx.Client(base_url=..., auth=...)) works unchanged.
- Run the same tests against both targets where possible, and only synthetic data in every non-production environment.
A short checklist for the integration layer of a healthcare MVP:
- ☐ Models pinned to the server’s FHIR version
- ☐ Every error path returns and parses OperationOutcome
- ☐ Conditional create on business identifiers, plus DB uniqueness
- ☐ If-Match on updates, 412/409 retry path in the client
- ☐ Paging via link[next], _count capped
- ☐ Date params built with time zones and URL-encoded
- ☐ Narrow SMART scopes
- ☐ Synthetic data only outside production
The full code (about 600 lines including tests) runs with pip install -r requirements.txt && python demo.py && pytest.
Which part of a FHIR API integration has cost you the most time: paging, terminology, or authorization? I would like to hear what broke first in your project.




Top comments (0)