FHIR R4 type generation with Pydantic models, configurable field formats, and validation.
This example demonstrates how to generate Python/Pydantic models from the FHIR R4 specification using the Atomic EHR Codegen toolkit. It includes:
- Full FHIR R4 resource type definitions as Pydantic models
- Automatic validation and serialization
- Configurable field naming conventions (snake_case or camelCase)
- Integration with Python type checking and IDE support
- Virtual environment setup
- Simple FHIR server client example using
requests
For an example using the fhirpy async client library, see python-fhirpy/.
- Create virtual environment:
cd examples/python
python3 -m venv venv
# On macOS/Linux:
source venv/bin/activate
# On Windows:
venv\Scripts\activate- Install Python dependencies:
pip install -r fhir_types/requirements.txt- Check Python version:
python --version # Should be 3.10 or higherTo generate Python/Pydantic types for FHIR R4:
bun run examples/python/generate.tsThis will output to ./examples/python/fhir_types/
Edit generate.ts to customize:
.python({
allowExtraFields: false, // Reject unknown fields in models
fieldFormat: "snake_case" // or "camelCase"
})Field Format Options:
snake_case: Python convention, convertsfirstName→first_namecamelCase: Preserves FHIR naming (less Pythonic)
Extra Fields:
true: Allow undefined fields (more lenient)false: Reject unknown fields (strict validation)
from fhir_types import Patient, Observation
from datetime import date
patient = Patient(
resource_type="Patient",
id="patient-1",
name=[{
"use": "official",
"family": "Smith",
"given": ["John"]
}],
birth_date=date(1980, 1, 15),
gender="male"
)
print(f"Patient: {patient.family_name}") # Snake case accessfrom pydantic import ValidationError
try:
patient = Patient(
resource_type="Patient",
gender="invalid" # Must be in value set
)
except ValidationError as e:
print(f"Validation error: {e}")# To JSON
json_str = patient.model_dump_json(indent=2)
# From JSON
patient = Patient.model_validate_json(json_str)
# To dictionary (excludes None values)
dict_data = patient.model_dump(exclude_none=True)
# From dictionary
patient = Patient.model_validate(dict_data)Verify type safety with MyPy:
pip install mypy
mypy fhir_types/Generated Pydantic models provide:
- Autocomplete for all fields
- Type hints for parameters and returns
- Inline documentation from FHIR specs
- Real-time validation errors
pytest test_sdk.py -v- See python-fhirpy/ for fhirpy async client example
- See examples/ overview for other language examples
- Check ../../CLAUDE.md for architecture details