FHIRClient Python Library

4.4.0 · active · verified Wed Apr 15

fhirclient is a flexible Python client for interacting with FHIR (Fast Healthcare Interoperability Resources) servers, supporting the SMART on FHIR protocol. It provides data model classes for FHIR resources and utilities for API interactions like reading, searching, and authorization. Currently at version 4.4.0, the library is actively maintained with regular releases addressing Python compatibility, FHIR specification updates, and feature enhancements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `FHIRClient`, fetch a specific patient resource by ID, and perform a basic search query. It uses environment variables for configuration to ensure security and flexibility, falling back to a public SMART Health IT sandbox for demonstration. The example also shows the use of `perform_resources_iter` for handling search results, which is recommended for robust pagination.

import os
from fhirclient import client
from fhirclient.models.patient import Patient

# Configure settings for an open FHIR server
settings = {
    'app_id': os.environ.get('FHIR_APP_ID', 'my_app'),
    'api_base': os.environ.get('FHIR_API_BASE', 'https://r4.smarthealthit.org')
}

# Initialize the FHIRClient
smart = client.FHIRClient(settings=settings)

# Try to read a specific patient by ID
try:
    patient_id = os.environ.get('FHIR_PATIENT_ID', '2cda5aad-e409-4070-9a15-e1c35c46ed5a') # Example ID for smarthealthit.org sandbox
    patient = Patient.read(patient_id, smart.server)
    print(f"Successfully fetched Patient: {patient.id}")
    if patient.name:
        print(f"Patient Name: {smart.human_name(patient.name[0])}")
    if patient.birthDate:
        print(f"Birth Date: {patient.birthDate.isostring}")
except Exception as e:
    print(f"Error fetching patient: {e}")

# Example of a simple search for Patients
try:
    search = Patient.where({'gender': 'female'}).limit(2)
    # Using perform_resources_iter for robust pagination handling (introduced in v4.3.0)
    female_patients = list(search.perform_resources_iter(smart.server))
    print(f"\nFound {len(female_patients)} female patients (first 2):")
    for p in female_patients:
        print(f" - {smart.human_name(p.name[0]) if p.name else 'Unnamed'} (ID: {p.id})")
except Exception as e:
    print(f"Error during patient search: {e}")

view raw JSON →