Skip to content

Latest commit

 

History

History
 
 

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 

README.md

Python fhirpy Example

FHIR R4 type generation with Pydantic models integrated with the fhirpy async client library.

Overview

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 fhirpy AsyncFHIRClient
  • Automatic validation and serialization
  • Async/await patterns for FHIR operations

For a simpler example using requests, see python/.

Setup

Python Environment

  1. Create virtual environment:
cd examples/python-fhirpy
python3 -m venv venv

# On macOS/Linux:
source venv/bin/activate
# On Windows:
venv\Scripts\activate
  1. Install Python dependencies:
pip install -r fhir_types/requirements.txt
pip install fhirpy
  1. Check Python version:
python --version  # Should be 3.10 or higher

Generating Types

To generate Python/Pydantic types for FHIR R4 with fhirpy support:

bun run examples/python-fhirpy/generate.ts

This will output to ./examples/python-fhirpy/fhir_types/

Configuration

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.

Using with fhirpy

Basic Usage

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())

Type Checking

MyPy Integration

Verify type safety with MyPy:

pip install mypy
mypy fhir_types/

Running the Demo

Start a FHIR server (e.g., using the docker-compose in examples/), then run:

python client.py

Next Steps