Async/sync FHIR client for Python providing comprehensive API for CRUD operations over FHIR resources
68
Core client functionality for connecting to FHIR servers, creating resources and search sets, and performing direct CRUD operations. The package provides both async and sync clients with identical APIs except for async/await patterns.
Create FHIR client instances with server connection parameters and configuration options.
class AsyncFHIRClient:
def __init__(
self,
url: str,
authorization: str = None,
extra_headers: dict = None,
aiohttp_config: dict = None,
*,
dump_resource: Callable[[Any], dict] = lambda x: dict(x)
):
"""
Initialize async FHIR client.
Parameters:
- url: FHIR server base URL
- authorization: Authorization header value (e.g., 'Bearer TOKEN')
- extra_headers: Additional HTTP headers
- aiohttp_config: Configuration passed to aiohttp session
- dump_resource: Function to serialize resources for requests
"""
class SyncFHIRClient:
def __init__(
self,
url: str,
authorization: str = None,
extra_headers: dict = None,
requests_config: dict = None,
*,
dump_resource: Callable[[Any], dict] = lambda x: dict(x)
):
"""
Initialize sync FHIR client.
Parameters:
- url: FHIR server base URL
- authorization: Authorization header value (e.g., 'Bearer TOKEN')
- extra_headers: Additional HTTP headers
- requests_config: Configuration passed to requests session
- dump_resource: Function to serialize resources for requests
"""Create resource instances and search sets for FHIR operations.
def resource(self, resource_type: str, **kwargs) -> FHIRResource:
"""
Create a new resource instance.
Parameters:
- resource_type: FHIR resource type (e.g., 'Patient', 'Observation')
- **kwargs: Resource attributes
Returns:
Resource instance ready for CRUD operations
"""
def resources(self, resource_type: str) -> FHIRSearchSet:
"""
Create a search set for resource type.
Parameters:
- resource_type: FHIR resource type to search
Returns:
SearchSet instance for building queries
"""
def reference(
self,
resource_type: str = None,
id: str = None,
reference: str = None,
**kwargs
) -> FHIRReference:
"""
Create a reference to a resource.
Parameters:
- resource_type: Resource type for reference
- id: Resource ID for reference
- reference: Full reference string (alternative to resource_type/id)
- **kwargs: Additional reference attributes
Returns:
Reference instance
"""Perform Create, Read, Update, Delete operations directly on the client.
async def get(self, resource_type: str, id: str) -> FHIRResource:
"""
Get resource by type and ID.
Parameters:
- resource_type: FHIR resource type
- id: Resource identifier
Returns:
Resource instance
Raises:
- ResourceNotFound: If resource doesn't exist
"""
async def create(self, resource, **kwargs):
"""
Create resource on server.
Parameters:
- resource: Resource instance or dict
- **kwargs: Additional creation parameters
Returns:
Created resource data
"""
async def update(self, resource, **kwargs):
"""
Update existing resource on server.
Parameters:
- resource: Resource instance with updates
- **kwargs: Additional update parameters
Returns:
Updated resource data
"""
async def patch(self, resource, **kwargs):
"""
Patch existing resource on server.
Parameters:
- resource: Resource instance with changes
- **kwargs: Additional patch parameters
Returns:
Patched resource data
"""
async def delete(self, resource, **kwargs):
"""
Delete resource from server.
Parameters:
- resource: Resource instance to delete
- **kwargs: Additional delete parameters
"""
async def save(self, resource, **kwargs):
"""
Save resource (create if new, update if exists).
Parameters:
- resource: Resource instance to save
- **kwargs: Additional save parameters
Returns:
Saved resource data
"""Execute custom FHIR operations and interact with server endpoints directly.
async def execute(
self,
path: str,
method: str = "post",
data: dict = None,
params: dict = None
) -> Any:
"""
Execute custom operation on FHIR server.
Parameters:
- path: Server endpoint path
- method: HTTP method (get, post, put, delete, patch)
- data: Request body data
- params: Query parameters
Returns:
Server response data
"""import asyncio
from fhirpy import AsyncFHIRClient, SyncFHIRClient
# Async client
async def async_example():
client = AsyncFHIRClient(
'https://hapi.fhir.org/baseR4',
authorization='Bearer your-token-here',
extra_headers={'Custom-Header': 'value'}
)
# Use client for operations
patient = await client.get('Patient', 'example-id')
print(patient['name'])
# Sync client
def sync_example():
client = SyncFHIRClient(
'https://hapi.fhir.org/baseR4',
authorization='Bearer your-token-here'
)
# Use client for operations
patient = client.get('Patient', 'example-id')
print(patient['name'])async def resource_management():
client = AsyncFHIRClient('https://hapi.fhir.org/baseR4')
# Create new patient
patient = client.resource('Patient',
name=[{'family': 'Doe', 'given': ['John']}],
gender='male',
active=True
)
# Save to server
created_patient = await client.create(patient)
print(f"Created patient with ID: {created_patient['id']}")
# Update patient
created_patient['active'] = False
updated_patient = await client.update(created_patient)
# Delete patient
await client.delete(updated_patient)async def custom_operations():
client = AsyncFHIRClient('https://hapi.fhir.org/baseR4')
# Execute $validate operation
validation_result = await client.execute(
'Patient/$validate',
method='post',
data={
'resourceType': 'Patient',
'name': [{'family': 'Test'}]
}
)
# Get server capabilities
capabilities = await client.execute(
'metadata',
method='get'
)
# Custom search with parameters
search_results = await client.execute(
'Patient',
method='get',
params={'name': 'John', '_count': '10'}
)Install with Tessl CLI
npx tessl i tessl/pypi-fhirpyevals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10