Python for FHIR Health Data — Core Concepts
What FHIR actually is
FHIR (Fast Healthcare Interoperability Resources) is an open standard created by HL7 International that defines how healthcare data should be structured and exchanged. Unlike older standards (HL7 v2 messages, CDA documents), FHIR uses modern web technology: RESTful APIs, JSON payloads, and OAuth2 authentication.
Every piece of health data in FHIR is a Resource. There are about 150 resource types, but a handful cover most use cases:
- Patient — demographics, identifiers, contact info
- Observation — lab results, vital signs, survey answers
- Condition — diagnoses and problems
- MedicationRequest — prescriptions
- Encounter — visits, admissions, appointments
- DiagnosticReport — lab reports, imaging reports
Each resource has a standard JSON schema. A Patient resource always has fields for name, birthDate, gender, and identifier, regardless of which hospital system generated it.
Python’s FHIR ecosystem
fhir.resources — Pydantic models for FHIR
The fhir.resources library provides Pydantic models for every FHIR resource type, giving you validation, autocompletion, and type safety:
from fhir.resources.patient import Patient
patient = Patient.parse_obj({
"resourceType": "Patient",
"name": [{"family": "Garcia", "given": ["Maria"]}],
"birthDate": "1985-07-14",
"gender": "female"
})
print(patient.name[0].family) # "Garcia"
print(patient.json()) # Valid FHIR JSON
Invalid data raises validation errors immediately, catching mistakes before they reach the server.
fhirclient — SMART on FHIR client
fhirclient implements the SMART on FHIR authorization framework and provides a high-level API for querying FHIR servers:
from fhirclient import client
from fhirclient.models.patient import Patient
settings = {
"app_id": "my_app",
"api_base": "https://r4.smarthealthit.org"
}
smart = client.FHIRClient(settings=settings)
# Search for patients named "Garcia"
search = Patient.where(struct={"name": "Garcia"})
results = search.perform_resources(smart.server)
Direct REST with httpx
For full control, you can interact with FHIR APIs directly. FHIR servers speak standard REST:
import httpx
base = "https://hapi.fhir.org/baseR4"
# Get all observations for a patient
response = httpx.get(
f"{base}/Observation",
params={"patient": "12345", "code": "85354-9"}, # blood pressure LOINC
headers={"Accept": "application/fhir+json"}
)
bundle = response.json()
for entry in bundle.get("entry", []):
obs = entry["resource"]
systolic = obs["component"][0]["valueQuantity"]["value"]
print(f"Blood pressure: {systolic} mmHg")
Key FHIR operations
| Operation | HTTP Method | Example |
|---|---|---|
| Read | GET | GET /Patient/123 |
| Search | GET | GET /Observation?patient=123&code=85354-9 |
| Create | POST | POST /Patient with JSON body |
| Update | PUT | PUT /Patient/123 with full resource |
| Delete | DELETE | DELETE /Patient/123 |
| Batch/Transaction | POST | POST / with a Bundle resource |
FHIR search supports chaining (Observation?patient.name=Garcia), reverse includes (Patient?_revinclude=Observation:patient), and date ranges (Observation?date=ge2025-01-01).
SMART on FHIR authorization
Accessing real patient data requires authorization. SMART on FHIR layers OAuth2 on top of FHIR, defining scopes like patient/Observation.read (read observations for the current patient) or user/Patient.write (create patients as the logged-in user).
The authorization flow:
- App redirects to the EHR’s authorization endpoint
- User (clinician or patient) logs in and approves access
- App receives an authorization code, exchanges it for an access token
- App includes the token in FHIR API requests
This is how Apple Health, patient portals, and third-party apps access hospital data securely.
Common misconception
“FHIR means all health data is freely accessible.” FHIR defines the data format and API, not the access policies. Every FHIR server enforces its own authorization rules. In the US, the 21st Century Cures Act requires hospitals to offer FHIR APIs, but patients must still authenticate, and providers control which apps get access. FHIR enables interoperability — it does not remove privacy controls.
Real-world applications
- Apple Health Records pulls patient data from participating hospitals using FHIR and SMART on FHIR, displaying medications, lab results, and immunizations on the user’s iPhone.
- CMS Blue Button 2.0 exposes Medicare claims data via a public FHIR API, enabling Python developers to build tools that help beneficiaries understand their healthcare costs.
- Epic MyChart exposes FHIR endpoints that power third-party apps for medication tracking, appointment scheduling, and clinical data aggregation.
The one thing to remember: Python’s FHIR libraries turn the complexity of health data exchange into straightforward REST calls with validated data models, making it practical to build apps that connect the fragmented healthcare system.
See Also
- Python Electronic Health Records How Python helps hospitals organize and learn from millions of patient records to improve healthcare for everyone.