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
from fhirpy import AsyncFHIRClient
from fhir_types.hl7_fhir_r4_core import HumanName
from fhir_types.hl7_fhir_r4_core.patient import Patient
async def main():
client = AsyncFHIRClient(
"http://localhost:8080/fhir",
authorization="Basic <token>",
)
# Create a patient using typed models
patient = Patient(
name=[HumanName(given=["John"], family="Doe")],
gender="male",
birthDate="1980-01-01",
)
# Use fhirpy's client API with the typed model
created = await client.create(patient)
print(f"Created patient: {created.id}")
# Search for patients
patients = await client.resources("Patient").fetch()
for pat in patients:
print(f"Found: {pat.get('name', [{}])[0].get('family', 'N/A')}")
asyncio.run(main())from fhir_types.hl7_fhir_r4_core.organization import Organization
organization = Organization(
name="My Organization",
active=True
)
# Use fhirpy's resource API
org_resource = await client.resource(
"Organization",
**organization.model_dump(exclude_none=True)
).save()
print(f"Created organization: {org_resource.id}")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