Validation¶
Validation happens when a model is created and whenever a field is assigned.
Failures raise pydantic.ValidationError, which is also a
ValueError.
What is checked¶
Rule |
Example |
|---|---|
Data types and formats of primitives |
|
Required elements (cardinality |
|
Choice elements |
At most one of |
Lists vs single values |
|
Unknown elements |
Elements that are not in the definition are rejected. |
Matching |
A |
Polymorphic resources |
|
What is not checked¶
Terminology bindings. Codes are not checked against value sets, even for
requiredbindings likePatient.gender. See Enforcing enums.Reference targets.
Reference.referenceis not resolved, and the target type is not checked. See Checking reference types.Invariants / FHIRPath constraints (
ele-1,dom-2…) and profiles (US Core, IPS …). Use a dedicated FHIR validator for these, for example the HL7 validator.
Reading errors¶
>>> import pydantic
>>> from fhir.resources.observation import Observation
>>> try:
... Observation.model_validate({"resourceType": "Observation", "code": {"text": "x"}})
... except pydantic.ValidationError as exc:
... for err in exc.errors():
... print(err["loc"], "-", err["msg"])
('status',) - Value for the field 'status' is required.
Unknown elements:
>>> from fhir.resources.patient import Patient
>>> try:
... Patient.model_validate({"resourceType": "Patient", "nickname": "Ad"})
... except pydantic.ValidationError as exc:
... print(exc.errors()[0]["type"], exc.errors()[0]["loc"])
extra_forbidden ('nickname',)
To accept and drop unknown elements instead, see Global model config.
Choice elements (value[x])¶
Only one of the alternatives of a choice element may be set:
>>> try:
... Observation.model_validate({
... "resourceType": "Observation", "status": "final", "code": {"text": "x"},
... "valueString": "high", "valueBoolean": True,
... })
... except pydantic.ValidationError as exc:
... print("Any of one field value is expected" in str(exc))
True
Dates, times and partial values¶
FHIR allows partial dates ("1985", "1985-06") and leap seconds
(23:59:60), which Python’s datetime cannot represent. Those values
are kept as their original string; complete values become date /
datetime / time objects. Either way the JSON output is identical to
the input.
>>> Patient(birthDate="1985").birthDate
'1985'
>>> Patient(birthDate="1985-06-12").birthDate
datetime.date(1985, 6, 12)
>>> obs = Observation.model_validate({
... "resourceType": "Observation", "status": "final", "code": {"text": "x"},
... "effectiveDateTime": "2016-12-31T23:59:60Z",
... })
>>> obs.model_dump()["effectiveDateTime"]
'2016-12-31T23:59:60Z'
Missing required data¶
FHIR allows a
required primitive to be absent when an extension on it explains why, usually
the data-absent-reason extension. fhir.resources accepts this:
>>> from fhir.resources.medicationrequest import MedicationRequest
>>> mr = MedicationRequest.model_validate({
... "resourceType": "MedicationRequest",
... "status": "completed",
... "_intent": {"extension": [{
... "url": "http://hl7.org/fhir/StructureDefinition/data-absent-reason",
... "valueCode": "unknown",
... }]},
... "medication": {"concept": {"text": "Erythromycin 250 MG"}},
... "subject": {"reference": "Patient/1"},
... })
>>> mr.intent is None
True
>>> mr.intent__ext.extension[0].valueCode
'unknown'
Custom validators¶
Add your own business rules by subclassing a model and using Pydantic’s
model_validator() or field_validator().
The subclass keeps the resource type, serialization and all built-in checks.
>>> import datetime
>>> from pydantic import field_validator, model_validator
>>> class AdultPatient(Patient):
... @model_validator(mode="after")
... def birth_date_required(self):
... if self.birthDate is None:
... raise ValueError("birthDate is required")
... return self
...
... @field_validator("birthDate")
... @classmethod
... def must_be_adult(cls, value):
... if isinstance(value, datetime.date) and value > datetime.date(2000, 1, 1):
... raise ValueError("patient must be born before 2000")
... return value
>>> AdultPatient(birthDate="1980-01-01").get_resource_type()
'Patient'
>>> AdultPatient(birthDate="2010-01-01")
Traceback (most recent call last):
...
pydantic_core._pydantic_core.ValidationError: 1 validation error for AdultPatient
...
Note
add_root_validator from version 6/7 does not exist any more in the
Pydantic V2 based releases. Subclassing is the replacement.
Enforcing enums¶
The allowed codes of a required binding are published in each field’s
metadata, but not enforced (see #23 for the reasoning):
>>> Patient.model_fields["gender"].json_schema_extra["enum_values"]
['male', 'female', 'other', 'unknown']
>>> Patient(gender="robot").gender
'robot'
Enforce them with a validator:
>>> class StrictGenderPatient(Patient):
... @field_validator("gender")
... @classmethod
... def check_gender(cls, value):
... allowed = cls.model_fields["gender"].json_schema_extra["enum_values"]
... if value is not None and value not in allowed:
... raise ValueError(f"gender must be one of {allowed}")
... return value
>>> StrictGenderPatient(gender="robot")
Traceback (most recent call last):
...
pydantic_core._pydantic_core.ValidationError: 1 validation error for StrictGenderPatient
...
Checking reference types¶
Likewise, the resource types a Reference may point to are available as
enum_reference_types:
>>> Patient.model_fields["managingOrganization"].json_schema_extra["enum_reference_types"]
['Organization']