import asyncio
from fhirpy import AsyncFHIRClient
async def main():
# Create an instance
client = AsyncFHIRClient(
'http://fhir-server/',
authorization='Bearer TOKEN',
)
# Search for patients
resources = client.resources('Patient') # Return lazy search set
resources = resources.search(name='John').limit(10).sort('name')
patients = await resources.fetch() # Returns list of AsyncFHIRResource
# Create Organization resource
organization = client.resource(
'Organization',
name='beda.software',
active=False
)
await organization.save()
# Update (PATCH) organization. Resource support accessing its elements
# both as attribute and as a dictionary keys
if organization['active'] is False:
organization.active = True
await organization.save(fields=['active'])
# `await organization.patch(active=True)` would do the same PATCH operation
# Get patient resource by reference and delete
patient_ref = client.reference('Patient', 'new_patient')
# Get resource from this reference
# (throw ResourceNotFound if no resource was found)
patient_res = await patient_ref.to_resource()
await patient_res.delete()
# Iterate over search set
org_resources = client.resources('Organization')
# Lazy loading resources page by page with page count = 100
async for org_resource in org_resources.limit(100):
print(org_resource.serialize())
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Sometimes you can find that fhir-py does not implement some search parameters from the FHIR specification.
In this case, you can use Raw() wrapper without any transformations
from fhirpy.base.searchset import Raw
patients = client.resources('Patient')
patients.search(Raw(**{'general-practitioner.name': 'Hospital'}))
# /Patient?general-practitioner.name=Hospital
# Get only specified set of elements for each resource
patients.elements('identifier', 'active', 'link')
# /Patient?_elements=identifier,active,link
# Get all elements except specified set
practitioners.elements('address', 'telecom', exclude=True)
Include
result = await client.resources('EpisodeOfCare') \
.include('EpisodeOfCare', 'patient').fetch_raw()
# /EpisodeOfCare?_include=EpisodeOfCare:patient
for entry in result.entry:
print(entry.resource)
await client.resources('MedicationRequest') \
.include('MedicationRequest', 'patient', target_resource_type='Patient') \
.fetch_raw()
# /MedicationRequest?_include=MedicationRequest:patient:Patient
Modifier :iterate (or :recurse in some previous versions of FHIR)
# For FHIR version >= 3.5 we can also use modifier :iterate
await client.resources('MedicationRequest') \
.include('MedicationDispense', 'prescription') \
.include('MedicationRequest', 'performer', iterate=True) \
.fetch_raw()
# /MedicationRequest?_include=MedicationDispense:prescription
# &_include:iterate=MedicationRequest:performer
# For FHIR version 3.0-3.3 use modifier :recurse
await client.resources('MedicationDispense') \
.include('MedicationRequest', 'prescriber', recursive=True) \
.fetch_raw()
# /MedicationDispense?_include:recurse=MedicationRequest:prescriber
Wild card (any search parameter of type=reference be included)
# searchset.get_or_create(resource)
# executes POST /Patient?identifier=fhirpy
patient, created = await client.resources("Patient").search(identifier="fhirpy").get_or_create(patient_to_save)
# no match -> created is True
# one match -> created is False, return existing resource
# multiple matches -> 412 'MultipleResourcesFound'
# resource, created: bool = searchset.patch(resource)
# executes PUT /Patient?identifier=fhirpy
patient_to_update = client.resource("Patient",
identifier=[{"system": "http://example.com/env", "value": "fhirpy"}],
active=False)
new_patient, created = await client.resources("Patient").search(identifier="fhirpy").update(patient_to_update)
# no match -> created is True
# one match -> created is False, the matched resource is overwritten
# multiple matches -> 412 'MultipleResourcesFound'
response_data, status_code = await self.client.resources("Patient").search(identifier="abc").delete()
# no match -> status_code = 204 'No Content'
# one match -> status_code = 200 'OK'
# multiple matches -> status_code = 412 'MultipleResourcesFound' (implementation specific)
Data models
Third party typing data models might be used along with fhir-py.
The typing data models should match ResourceProtocol, e.g. have resourceType attribute, optional id and be iterable for serialization.
There's a third party repository fhir-py-types that is written on top of pydantic models is fully compatible with fhir-py.
Static typechecking
fhir-py uses typehints in the codebase and it statically checked by mypy. Some interfaces that are described below designed in the way to properly infer the return type based on the model class or instance.
Resource instantiation
To instantiate a resource, simply use type model constructor, e.g.
Delete accepts different syntaxes for resource deletion, there're also syntaxes similar to patch, but without output type because delete usually returns nothing.
Delete using reference defined by separate resource type and id:
await client.delete('Patient', 'id')
Delete using reference string:
await client.delete('Patient/id')
Delete using model class and id
await client.delete(Patient, 'id')
Delete using model instance
await client.delete(patient)
Read
For fetching single resource by resourceType and id:
ss = await client.get(Patient, 'id') # returns Patient
For fetching multiple resources, SearchSet needs to be instantiated using the model class as the first argument
In that case search set infers model type for all methods that described above in the sections about search sets, including data fetching and conditional CRUD.
patient = await client.resources('Patient').first()
# Work with the resource as a dictionary
patient_family = patient['name'][0]['family']
# Or access value by an attribute
patient_given_name = patient.name[0].given[0]
get_by_path(path, default=None)
patient_postal = patient.get_by_path(['resource', 'address', 0, 'postalCode'])
# get_by_path can be also used on any nested attribute
patient_name = patient.name[0]
patient_fullname = '{} {}'.format(
patient_name.get_by_path(['given', 0]),
patient_name.get_by_path(['family'])
)
# Get identifier value by specified system or empty string
uid = patient.get_by_path([
'resource', 'identifier',
{'system':'http://example.com/identifier/uid'},
'value'
], '')
# Get base value amount or 0
invoice = await client.resources('Invoice').first()
base_value = invoice.get_by_path([
'totalPriceComponent',
{'type': 'base'},
'amount', 'value'], 0)
async .execute(path, method='post', data=None, params=None, *, extra_headers=None) - returns a result of FHIR operation
data model methods:
async .get(resource_type: type[T], id) - returns T instance by resourceType/id
async .get(resource_type: type[T], reference) - returns T instance by reference
async .get(resource_type: str, id) - gets instance by resourceType/id
async .get(reference: str) - gets instance by reference
async .save(resource: T, fields=[]) - creates or updates or patches (with fields=[...]) T instance
async .create(resource: T) - creates T instance
async .update(resource: T) - updates T instance
async .patch(resource: T, **kwargs) - patches T instance
async .patch(resource_type: type[T], id, **kwargs) - patches instance by resourceType/id and returns T instance
async .patch(resource_type: type[T], reference, **kwargs) - patches instance by reference and returns T instance
async .patch(resource_type: str, id, **kwargs) - patches instance by resourceType/id
async .patch(reference: str, **kwargs) - patches instance by reference
async .delete(resource: T) - deletes T instance
async .delete(resource_type: type[T], id) - deletes resource by resourceType/id
async .delete(resource_type: type[T], reference) - deletes resource by reference
async .delete(resource_type: str, id) - deletes instance by resourceType/id
async .delete(reference: str) - deletes instance by reference
Per-request headers
Both AsyncFHIRClient.execute and SyncFHIRClient.execute accept the keyword-only
extra_headers argument. These headers override matching keys in the client headers
for that request only, without changing either input dictionary or subsequent requests.
Omitting the argument, passing None, or passing an empty dictionary keeps the client headers.
For example, explicitly supply If-Match for a version-aware update:
Use the same calls without await for SyncFHIRClient. The caller supplies the header;
the client does not infer it automatically from resource metadata. This option applies
to the client-level execute method and does not change the existing error handling.
Aiohttp request parameters
Sometimes you need more control over the way http request is made and provide additional aiohttp session's request parameters like ssl, proxy, cookies, timeout etc. It's possible by providing aiohttp_config dict for AsyncFHIRClient:
Be careful and don't override other request values like params, json, data, auth, because it'll interfere with the way fhir-py works and lead to an incorrect behavior.
Url aliases
If the server is reachable at an internal address but returns absolute urls pointing at a public
one (for example Bundle.link built from an ingress hostname), pass url_aliases so those urls
are rewritten back onto the client's base url instead of being rejected:
client = AsyncFHIRClient(
"http://devbox:80/fhir/",
url_aliases=["https://myprod.com/fhir"],
)
# a next link of https://myprod.com/fhir/Patient?_count=100
# is requested as http://devbox:80/fhir/Patient?_count=100
AsyncFHIRResource
provides:
.serialize() - serializes resource
.get_by_path(path, default=None) – gets the value at path of resource
async .save(fields=[]) - creates or updates or patches (with fields=[...]) resource instance
async .fetch() - makes query to the server and returns a list of Resource filtered by resource type
async .fetch_all() - makes query to the server and returns a full list of Resource filtered by resource type
async .fetch_raw() - makes query to the server and returns a raw Bundle Resource
async .first() - returns Resource or None
async .get() - returns Resource or raises ResourceNotFound when no resource found or MultipleResourcesFound when more than one resource found (parameter 'id' is deprecated)
async .count() - makes query to the server and returns the total number of resources that match the SearchSet
Be careful and don't override other request values like params, json, data, headers, which may interfere with the way fhir-py works and lead to an incorrect behavior.
Url aliases
If the server is reachable at an internal address but returns absolute urls pointing at a public
one (for example Bundle.link built from an ingress hostname), pass url_aliases so those urls
are rewritten back onto the client's base url instead of being rejected:
client = SyncFHIRClient(
"http://devbox:80/fhir/",
url_aliases=["https://myprod.com/fhir"],
)
# a next link of https://myprod.com/fhir/Patient?_count=100
# is requested as http://devbox:80/fhir/Patient?_count=100
SyncFHIRResource
The same as AsyncFHIRResource but with sync methods
SyncFHIRReference
provides:
The same as AsyncFHIRReference but with sync methods
SyncFHIRSearchSet
The same as AsyncFHIRSearchSet but with sync methods
Clone this repository:
https://github.com/beda-software/fhir-py.git
Go to fhir-py folder and install dev dependencies:
cd fhir-py
pip install -r requirements.txt
If you've already installed fhir-py library and want to test the last changes, reinstall it by running python setup.py install (or uninstall pip uninstall fhirpy)
Provide ENV variables FHIR_SERVER_URL and FHIR_SERVER_AUTHORIZATION, or edit tests/config.py
Run pytest
If you've found any bugs or think that some part of fhir-py is not compatible with FHIR spec, feel free to create an issue/pull request.
Alternatives
Use instead of fhirpy: tools that do the same job, closest first.