Registry / serialization / fhir.resources

fhir.resources

JSON →
library8.0.0pypypi✓ verified 53d ago

Python library for FHIR (Fast Healthcare Interoperability Resources) providing Pydantic-based models for all FHIR resource types. Supports FHIR R4, R4B, R5, STU3, and DSTU2. Built on Pydantic v2 for validation, serialization, and deserialization of FHIR JSON. Current version targets FHIR R5 by default with backwards-compatible imports for older FHIR versions.

serializationai-ml
pip install fhir.resources
Install & Compatibility
Where this runs
tested against v8.2.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
glibc
py 3.10
✓ —
✓ 4.82s
py 3.11
✓ —
✓ 4.1s
py 3.12
✓ —
✓ 3.7s
py 3.13
✓ —
✓ 3.83s
py 3.9
6/10 runs
6/10 runs
51MB installed
● package 51MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Patient
from fhir.resources.patient import Patient
from fhir_resources import Patient
The package uses a namespace package 'fhir.resources'. Each resource type is in its own module with a lowercase name.
Patient (R4)
from fhir.resources.R4B.patient import Patient
from fhir.resources.patient import Patient # this gives R5
To use FHIR R4B resources, import from fhir.resources.R4B subpackage. Default top-level imports are R5.
Patient (STU3)
from fhir.resources.STU3.patient import Patient
STU3 resources live under the fhir.resources.STU3 subpackage.
Bundle
from fhir.resources.bundle import Bundle
Each FHIR resource is its own module. Import the class with the CamelCase name from the lowercase module.

Create, validate, and serialize a FHIR Patient resource using Pydantic v2 methods.

from fhir.resources.patient import Patient # Create from dict patient_data = { "resourceType": "Patient", "id": "example", "active": True, "name": [ { "use": "official", "family": "Doe", "given": ["John"] } ], "gender": "male", "birthDate": "1990-01-01" } patient = Patient.model_validate(patient_data) print(patient.name[0].family) # 'Doe' # Serialize back to FHIR JSON print(patient.model_dump_json(indent=2)) # Parse from JSON string json_str = patient.model_dump_json() patient2 = Patient.model_validate_json(json_str) print(patient2.id) # 'example'
Debug
Known issues
breakingfhir.resources 7.x+ requires Pydantic v2. Pydantic v2 leverages modern Python typing features (like the '|' operator for unions) that are fully supported from Python 3.10 onwards. Running fhir.resources 7.x+ with Python 3.9 or older (alongside Pydantic v2) will result in a TypeError due to unrecognized syntax. Projects still on Pydantic v1 must use fhir.resources 6.x.
fix
Either upgrade your Python environment to 3.10 or later and install 'pydantic>=2.0', or pin fhir.resources<7.0.0 for Pydantic v1 compatibility (which supports Python 3.8+).
affects: >= 7.0.0
breakingDefault FHIR version changed from R4B to R5 in fhir.resources 7.x+. Top-level imports now return R5 models.
fix
For R4B resources, import from fhir.resources.R4B.* subpackage instead of top-level fhir.resources.*.
affects: >= 7.0.0
breakingPydantic v2 migration changed validation and serialization methods. .parse_obj() and .json() are replaced.
fix
Use Patient.model_validate(data) instead of Patient.parse_obj(data), and patient.model_dump_json() instead of patient.json().
affects: >= 7.0.0
gotchaThe package installs as a namespace package (fhir.resources). Do not create your own 'fhir' package in your project or it will shadow the library.
fix
Avoid naming your own modules or packages 'fhir' to prevent import conflicts.
affects: all
gotchaFHIR resource validation is strict by default. Missing required fields or invalid value sets will raise ValidationError.
fix
Catch pydantic.ValidationError and inspect e.errors() for details on which fields failed validation.
affects: all
gotcharesourceType field must match the class name exactly. Passing resourceType='patient' (lowercase) will raise a validation error.
fix
Always use the exact CamelCase resourceType, e.g. 'Patient', 'Observation', 'Bundle'.
affects: all
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'pydantic_core._pydantic_core'
This error typically occurs when `fhir.resources` (version 7.0.0 or higher) is installed in an environment where Pydantic v1 is present, or an older version of `fhir.resources` (prior to 7.0.0) is attempting to run with Pydantic v2. `fhir.resources` 7.x+ depends on Pydantic v2, which includes `pydantic_core`.
fix
Ensure that your Pydantic installation is compatible with your `fhir.resources` version. For `fhir.resources` v7.0.0 and above, upgrade Pydantic to version 2.x: `pip install --upgrade pydantic`. For older `fhir.resources` versions, you might need to downgrade Pydantic: `pip install 'pydantic<2'`.
pydantic.error_wrappers.ValidationError: 1 validation error for Patient\nresource -> status\n field required (type=value_error.missing)
This Pydantic validation error indicates that a required field within the FHIR resource (e.g., `status` for a `Patient` resource) is missing in the data provided when instantiating the `fhir.resources` model, violating the FHIR specification.
fix
Provide a valid value for the missing required field. For example, when creating a `Patient` resource, ensure all mandatory fields as per the FHIR specification are included:
```python
from fhir.resources.R5.patient import Patient

patient_data = {
    "resourceType": "Patient",
    "id": "example",
    "active": True,
    "name": [
        {
            "use": "official",
            "family": "Chalmers",
            "given": ["Peter"]
        }
    ],
    "gender": "male",
    "birthDate": "1974-12-25"
}

patient = Patient(**patient_data)
# Or, if loading from JSON string
# patient = Patient.parse_raw(json_string_data)
```
Note: `Patient` itself does not have a 'status' field, but other resources like `Observation` or `ServiceRequest` do. The example `Patient` data is shown to illustrate providing required fields.
AttributeError: module 'fhir.resources' has no attribute 'R4'
This error occurs when trying to import FHIR resources from a specific version (like R4) using an incorrect path. The `fhir.resources` library (version 7.0.0+) defaults to R5, and older versions (STU3, R4B) are located in specific sub-packages. R4 is explicitly noted to not have its own sub-package in newer versions, with R4B being the closest available.
fix
Import resources from the correct FHIR version sub-package. For R4B resources, use `from fhir.resources.R4B.patient import Patient`. For STU3 resources, use `from fhir.resources.STU3.patient import Patient`. If you intend to use the default R5, simply use `from fhir.resources.R5.patient import Patient` or `from fhir.resources.patient import Patient` (as R5 is the default).
pydantic.error_wrappers.ValidationError: ... extra fields not permitted (type=value_error.extra)
This validation error from Pydantic indicates that the input JSON or dictionary for a FHIR resource contains fields that are not defined in the FHIR specification for that resource type or its current profile, or it may contain elements from a different FHIR version.
fix
Ensure that the input data strictly conforms to the FHIR specification for the target resource and version. Remove any extraneous fields that are not part of the standard, or ensure that you are using the correct FHIR version's resource definition. For example, if parsing a resource, inspect the input JSON to remove unexpected keys:
```python
from fhir.resources.R5.patient import Patient

# This will raise 'extra fields not permitted' because 'unexpectedField' is not part of Patient
malformed_data = {
    "resourceType": "Patient",
    "id": "example",
    "active": True,
    "gender": "male",
    "unexpectedField": "some value"
}

try:
    patient = Patient(**malformed_data)
except Exception as e:
    print(e)

# Corrected data
correct_data = {
    "resourceType": "Patient",
    "id": "example",
    "active": True,
    "gender": "male"
}
patient = Patient(**correct_data)
```
Upgrade
Version history
8.2.0latest on PyPI
Audit
Dependencies
pydanticrequiredCore dependency. fhir.resources 8.x requires Pydantic v2. Pydantic v1 is not supported.
orjsonoptionalOptional faster JSON serializer. Used automatically if installed.
Agent activity
54 hits · last 30 days
node
10
ahrefsbot
3
amazonbot
1
Resources