Quickstart¶
This page walks through the everyday tasks in five minutes. Every example on this site is executed as part of the documentation build, so you can paste it into a Python shell as-is.
1. Import a model¶
Each FHIR resource or data type lives in a module named after it, in lower
case. Patient is in fhir.resources.patient, HumanName is in
fhir.resources.humanname, and so on.
>>> from fhir.resources.patient import Patient
>>> from fhir.resources.humanname import HumanName
If you only know the name at runtime, look the class up instead:
>>> from fhir.resources import get_fhir_model_class
>>> get_fhir_model_class("Observation")
<class 'fhir.resources.observation.Observation'>
2. Build a resource¶
From keyword arguments:
>>> patient = Patient(
... id="p001",
... active=True,
... name=[HumanName(family="Smith", given=["Adam"])],
... birthDate="1985-06-12",
... )
>>> patient.get_resource_type()
'Patient'
From a dict (for example parsed JSON from an API):
>>> patient = Patient.model_validate({
... "resourceType": "Patient",
... "id": "p001",
... "active": True,
... "name": [{"family": "Smith", "given": ["Adam"]}],
... })
From a JSON string or bytes, which is the fastest path:
>>> patient = Patient.model_validate_json(
... '{"resourceType": "Patient", "id": "p001", "active": true}'
... )
>>> patient.active
True
From a file:
>>> from fhir.resources.observation import Observation
>>> import pathlib
>>> path = pathlib.Path("observation.json")
>>> obs = Observation.model_validate_json(path.read_bytes())
Tip
There is no parse_file in Pydantic V2; read the bytes yourself and
pass them to model_validate_json.
3. Read and change values¶
Nested elements are real model instances and primitive values are converted to Python types:
>>> patient = Patient.model_validate({
... "resourceType": "Patient",
... "name": [{"family": "Smith", "given": ["Adam"]}],
... "birthDate": "1985-06-12",
... })
>>> type(patient.name[0]).__name__
'HumanName'
>>> patient.birthDate
datetime.date(1985, 6, 12)
>>> patient.active = False
>>> patient.active
False
4. Get the data back out¶
>>> data = patient.model_dump()
>>> list(data)
['resourceType', 'active', 'name', 'birthDate']
>>> data["birthDate"]
datetime.date(1985, 6, 12)
>>> print(patient.model_dump_json(indent=2))
{
"resourceType": "Patient",
"active": false,
"name": [
{
"family": "Smith",
"given": [
"Adam"
]
}
],
"birthDate": "1985-06-12"
}
Output always follows the element order defined by the FHIR specification and omits empty values, so it can be sent straight to a FHIR server.
5. Catch invalid data¶
Invalid input raises pydantic.ValidationError with a precise
location:
>>> import pydantic
>>> try:
... Patient.model_validate({"resourceType": "Patient", "birthDate": "not-a-date"})
... except pydantic.ValidationError as exc:
... print(exc.errors()[0]["loc"])
('birthDate',)
Next steps¶
FHIR releases — use R4B or STU3 instead of R5.
Validation — what exactly gets validated.
Serialization — XML, YAML, and output options.