FHIR R4 type generation with Pydantic models integrated with the fhirpy async client library.
This example demonstrates how to use generated Python/Pydantic models with the fhirpy async FHIR client. It includes:
- Full FHIR R4 resource type definitions as Pydantic models
- Integration with
fhirpyAsyncFHIRClient - Automatic validation and serialization
- Async/await patterns for FHIR operations
For a simpler example using requests, see python/.
- Create virtual environment:
cd examples/python-fhirpy
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
pip install fhirpy- Check Python version:
python --version # Should be 3.10 or higherTo generate Python/Pydantic types for FHIR R4 with fhirpy support:
bun run examples/python-fhirpy/generate.tsThis will output to ./examples/python-fhirpy/fhir_types/
Edit generate.ts to customize:
.python({
allowExtraFields: false, // Reject unknown fields in models
fieldFormat: "snake_case", // or "camelCase"
fhirpyClient: true // Enable fhirpy integration
})The fhirpyClient: true option generates models that inherit from a base class compatible with fhirpy's client API.
import asyncio
import base64
import json
from fhirpy import AsyncFHIRClient
from fhir_types.hl7_fhir_r4_core import HumanName
from fhir_types.hl7_fhir_r4_core.patient import Patient
from fhir_types.hl7_fhir_r4_core.organization import Organization
FHIR_SERVER_URL = "http://localhost:8080/fhir"
USERNAME = "root"
PASSWORD = "<SECRET>"
TOKEN = base64.b64encode(f"{USERNAME}:{PASSWORD}".encode()).decode()
async def main() -> None:
"""
Demonstrates usage of fhirpy AsyncFHIRClient to create and fetch FHIR resources.
Both Client and Resource APIs are showcased.
"""
client = AsyncFHIRClient(
FHIR_SERVER_URL,
authorization=f"Basic {TOKEN}",
dump_resource=lambda x: x.model_dump(exclude_none=True),
)
patient = Patient(
name=[HumanName(given=["Bob"], family="Cool2")],
gender="female",
birth_date="1980-01-01",
)
created_patient = await client.create(patient)
print(f"Created patient: {created_patient.id}")
print(json.dumps(created_patient.model_dump(exclude_none=True), indent=2))
organization = Organization(
name="Beda Software",
active=True
)
created_organization = await client.create(organization)
print(f"Created organization: {created_organization.id}")
patients = await client.resources(Patient).fetch()
for pat in patients:
print(f"Found: {pat.name[0].family}")
if __name__ == "__main__":
asyncio.run(main())Verify type safety with MyPy:
pip install mypy
mypy fhir_types/Start a FHIR server (e.g., using the docker-compose in examples/), then run:
python client.py- See python-simple/ for basic requests-based example
- See examples/ overview for other language examples
- Check ../../CLAUDE.md for architecture details
- Learn more about fhirpy