Creating resources¶
Every FHIR resource and complex data type is a Pydantic model. You can create instances in four ways; pick the one that matches where your data comes from.
Method |
Use when |
|---|---|
|
You build the resource in Python code. |
|
You already have a parsed JSON |
|
You have raw JSON (HTTP body, file contents). Fastest option. |
|
See Serialization. |
Keyword arguments¶
Pass nested elements either as model instances or as plain dicts. Both
are validated the same way.
>>> from fhir.resources.patient import Patient
>>> from fhir.resources.address import Address
>>> patient = Patient(
... id="p001",
... active=True,
... address=[Address(country="Switzerland"), {"city": "Bern"}],
... )
>>> [type(a).__name__ for a in patient.address]
['Address', 'Address']
Field names use the JSON element name (birthDate, managingOrganization)
so you can copy names straight from the FHIR specification. The only exceptions
are elements that clash with Python keywords; see Naming conventions.
From a dict or JSON¶
resourceType is optional, but if it is present it must match the model:
>>> from fhir.resources.patient import Patient
>>> Patient.model_validate({"resourceType": "Patient", "id": "p1"}).id
'p1'
>>> Patient.model_validate({"resourceType": "Observation"})
Traceback (most recent call last):
...
pydantic_core._pydantic_core.ValidationError: 1 validation error for Patient
...
>>> json_str = '''{
... "resourceType": "Patient",
... "id": "p001",
... "active": true,
... "name": [{"text": "Adam Smith"}],
... "birthDate": "1985-06-12"
... }'''
>>> pat = Patient.model_validate_json(json_str)
>>> pat.name[0].text
'Adam Smith'
Looking up a model by name¶
fhir.resources.get_fhir_model_class() returns the R5 class for a resource
or data type name. It is handy for generic code that receives
resourceType at runtime:
>>> import json
>>> from fhir.resources import get_fhir_model_class
>>> payload = json.loads('{"resourceType": "Practitioner", "id": "dr-1"}')
>>> model = get_fhir_model_class(payload["resourceType"])
>>> model.model_validate(payload).id
'dr-1'
>>> get_fhir_model_class("NotAResource")
Traceback (most recent call last):
...
ValueError: NotAResource is not a valid FHIR Model
Note
get_fhir_model_class replaces the construct_fhir_element and
FHIRElementFactory helpers of older versions. See Migration guide.
Bundles and contained resources¶
Fields typed as Resource (Bundle.entry.resource,
DomainResource.contained, Parameters.parameter.resource …) are
polymorphic: the right class is chosen from each item’s resourceType.
>>> from fhir.resources.bundle import Bundle
>>> bundle = Bundle.model_validate({
... "resourceType": "Bundle",
... "type": "collection",
... "entry": [
... {"resource": {"resourceType": "Patient", "id": "a"}},
... {"resource": {"resourceType": "Observation", "status": "final",
... "code": {"text": "Heart rate"}}},
... ],
... })
>>> [type(e.resource).__name__ for e in bundle.entry]
['Patient', 'Observation']
Modifying a resource¶
Models validate on assignment, so you cannot put a wrong value into an existing resource by accident:
>>> pat = Patient(id="p1")
>>> pat.birthDate = "2001-02-03"
>>> pat.birthDate
datetime.date(2001, 2, 3)
>>> pat.birthDate = "yesterday"
Traceback (most recent call last):
...
pydantic_core._pydantic_core.ValidationError: 1 validation error for Patient
...
To copy and change a resource without mutating the original, use Pydantic’s
model_copy:
>>> inactive = pat.model_copy(update={"active": False})
>>> pat.active is None, inactive.active
(True, False)
Warning
model_copy(update=...) does not validate the updated values. Only
pass values you know to be valid, or re-validate with
Patient.model_validate(inactive.model_dump()).
Building without validation¶
Model.model_construct() creates an instance with no validation at all.
It is useful for building a resource step by step:
>>> from fhir.resources.organization import Organization
>>> org = Organization.model_construct()
>>> org.name = "Acme Corporation"
>>> org.alias = ["Acme"]
>>> org.model_dump_json()
'{"resourceType":"Organization","name":"Acme Corporation","alias":["Acme"]}'
Caution
Validation still runs on attribute assignment, which can fail for resources with several required fields that are not set yet. See this comment on issue #56. Prefer passing everything to the constructor when possible.