querier
Provides a high-level abstraction for extracting patient info from FHIR R4 APIs.
Classes
FHIRR4PatientQuerier
class FHIRR4PatientQuerier( patient_id: str, *, fhir_client: FHIRClient, fhir_patient_info: RetrievedPatientDetailsJSON | None = None, ehr_provider: str | None = None, patient_dict: dict[str, Any] | None = None, search_executor: SearchExecutor | None = None,):Provides query/data extraction methods for a given patient.
This class is a higher-level abstraction than the direct API interactions, providing methods for extracting/munging data from the API responses.
Its data methods come from the domain readers in readers/, one mixin per
resource family. This class adds the patient lookup (the from_* factories
and get_patient_response_*) and get_patient_code_states, which combines
the condition, procedure and medication readers.
This is the FHIR R4 PatientRecord. FHIRR4EHRService builds every
record on a connection with the connection's executor (through the
factories below, or directly for a trusted ID), so its records share
what is known about the server and the connection's auth budget.
NOTE: This querier is used by all FHIR R4 providers. The "generic r4" provider serves as the baseline FHIR R4 implementation that adheres strictly to the FHIR standard without any provider-specific customizations. If provider-specific elements (e.g., Epic-specific) are added to this class or its methods, ensure that "generic r4" continues to work as the baseline standard FHIR R4 provider.
Arguments
patient_id: The patient ID this querier corresponds to.fhir_client: FHIRClient instance.fhir_patient_info: FHIR Patient Info with contact details.ehr_provider: The EHR provider e.g. "nextech", "epic", "generic r4"patient_dict: Optional patient details. If we've created this class with from_patient_query, we'll store the obtained patient_dict for later reference.search_executor: Runs this querier's searches; the one executor shared by every querier and lister on the EHR connection. When not given, a new executor for this querier's client and provider is built per use.
Ancestors
Variables
demographics : RetrievedPatientDetailsJSON | None- The patient's names, date of birth, contacts and practitioners.
profile : ProviderProfile- The quirks of this querier's EHR provider.
raw_patient : Mapping[str, Any] | None- ThePatientresource the patient was found by, if any.
Static methods
from_mrn
def from_mrn( mrn: str, *, fhir_client: FHIRClient, ehr_provider: EHRProvider | None = None, search_executor: SearchExecutor | None = None,) ‑> FHIRR4PatientQuerier:Build a FHIRR4PatientQuerier from MRN.
Arguments
mrn: Medical Record Number as a ready-made identifier search token (valueorsystem|value); the caller escapes it.fhir_client: FHIRClient instanceehr_provider: The EHR providersearch_executor: The executor the record runs its searches on, for the same client and provider; a new one per use when not given. The patient lookup itself does not use it.
Returns FHIRR4PatientQuerier for the target patient.
Raises
NoMatchingFHIRR4PatientError: No patient matching the MRN could be foundNonSpecificFHIRR4PatientError: Multiple patients match the MRNNoFHIRR4PatientIDError: Patient matching the MRN was found, but no patient ID was associatedFHIRR4APIError: The patient search failed (e.g. an HTTP error such as a 400 for an identifier the server will not accept, an authentication failure or an errorOperationOutcome), or its answer could not be read (seeSearchExecutor.get).ValidationError: The patient found is not a validPatient.
from_patient_id
def from_patient_id( patient_id: str, *, fhir_client: FHIRClient | None = None, ehr_provider: EHRProvider | None = None, search_executor: SearchExecutor | None = None,) ‑> FHIRR4PatientQuerier:Build a FHIRR4PatientQuerier directly from a known patient ID.
Unlike from_patient_query/from_mrn, this does not search for the
patient by demographics; the patient ID is already known. The /Patient
endpoint is queried by ID to retrieve contact details; if no patient
has that ID, NoMatchingFHIRR4PatientError is raised so the caller
can skip the patient rather than issuing further queries with no
confirmed patient context. A lookup that fails raises its API error
instead, so it is not mistaken for an absent patient.
Arguments
patient_id: The known patient ID.fhir_client: FHIRClient instance.ehr_provider: The EHR provider.search_executor: The executor the record runs its searches on, for the same client and provider; a new one per use when not given. The patient lookup itself does not use it.
Returns FHIRR4PatientQuerier for the target patient.
Raises
ValueError: Iffhir_clientis not supplied.NoMatchingFHIRR4PatientError: No patient has the given ID.MultipleResourcesFound: More than one patient record was returned for the given ID.FHIRR4APIError: The patient lookup failed (e.g. an HTTP error, an authentication failure or an errorOperationOutcome), or its answer could not be read (seeSearchExecutor.get).ValidationError: The patient found is not a validPatient.
from_patient_query
def from_patient_query( patient_dob: str | date, given_name: str | None = None, family_name: str | None = None, *, fhir_client: FHIRClient | None = None, ehr_provider: EHRProvider | None = None, search_executor: SearchExecutor | None = None,) ‑> FHIRR4PatientQuerier:Build a FHIRR4PatientQuerier from patient query details.
Arguments
patient_dob: Patient date of birth.given_name: Patient given name.family_name: Patient family name.fhir_client: FHIRClient instanceehr_provider: The EHR providersearch_executor: The executor the record runs its searches on, for the same client and provider; a new one per use when not given. The patient lookup itself does not use it.
Returns FHIRR4PatientQuerier for the target patient.
Raises
ValueError: Iffhir_clientis not supplied.NoMatchingFHIRR4PatientError: No patients matching the name/dob criteria could be foundNonSpecificFHIRR4PatientError: Multiple patients match the criteria, could not determine the correct oneNoFHIRR4PatientIDError: Patient matching the criteria was found, but no patient ID was associatedFHIRR4APIError: The patient search failed (e.g. an HTTP error, an authentication failure or an errorOperationOutcome), or its answer could not be read (seeSearchExecutor.get).ValidationError: The patient found is not a validPatient.
get_patient_response_by_mrn
def get_patient_response_by_mrn( fhir_client: FHIRClient, mrn: str,) ‑> dict[str, typing.Any] | None:Get JSON response from /Patient endpoint given an MRN.
Arguments
fhir_client: FHIRClient instancemrn: Medical Record Number as a ready-made identifier search token (valueorsystem|value). The caller escapes it (seebitfount.externals.ehr.fhir_search); it is sent as given.
Returns Patient resource dict if found, None otherwise
get_patient_response_by_name
def get_patient_response_by_name( fhir_client: FHIRClient, patient_dob: str | date, given_name: str | None = None, family_name: str | None = None,) ‑> dict[str, typing.Any] | None:Get JSON response from /Patient endpoint given name and DOB.
Methods
acuity_in_documents_only
def acuity_in_documents_only(self) ‑> bool:Inherited from:
DocumentAcuityReader.acuity_in_documents_only :
Whether the server is marked as serving acuity only in documents.
Asks the server knowledge. False for a provider that does not read
acuity from documents.
document_infos
def document_infos(self) ‑> Iterable[list[EHRDocumentInfo]]:The patient's documents, in batches, without their content.
Lazy: nothing is requested until the first batch is read, so a listing that fails raises then, not on this call.
download_all_documents
def download_all_documents( self, save_path: Path,) ‑> tuple[list[DownloadedEHRDocumentInfo], list[FailedEHRDocumentInfo]]:Inherited from:
DocumentAcuityReader.download_all_documents :
Download PDF documents for the current patient.
A document that cannot be downloaded is returned as failed; a listing
that fails raises, as get_document_infos does.
Arguments
save_path: Documents path for the PDF documents to be saved.
Raises
FHIRR4APIError: If a page of the listing fails (seeget_document_infos).OperationOutcome: AsFHIRR4APIError, for a server that reports the failure that way.requests.RequestException: If the server could not be reached or did not answer in time while listing.
download_documents
def download_documents( self, save_path: Path, infos: Sequence[EHRDocumentInfo] | None = None,) ‑> tuple[list[DownloadedEHRDocumentInfo], list[FailedEHRDocumentInfo]]:Download the patient's documents to save_path.
Arguments
save_path: Where to save the documents.infos: The documents to download, fromdocument_infos; every document whenNone.
Returns The documents downloaded, and those that could not be.
download_documents_batch
def download_documents_batch( self, save_path: Path, batch_document_infos: list[EHRDocumentInfo],) ‑> tuple[list[DownloadedEHRDocumentInfo], list[FailedEHRDocumentInfo]]:Inherited from:
DocumentAcuityReader.download_documents_batch :
Downloads a batch of documents.
Returns A tuple containing:
- list of info of documents that were successfully downloaded.
- list of info of documents that could not be downloaded.
get_document_acuity
def get_document_acuity( self, codes: Sequence[tuple[str | None, str]], *, observed: Mapping[Eye, date] | None = None,) ‑> DocumentAcuityResult:Inherited from:
DocumentAcuityReader.get_document_acuity :
The visual acuity observations recorded in the patient's newest CCDs.
Lists the patient's DocumentReferences (asking for CCDs by type
where the server allows it), reads the newest CCDs, at most three, and
keeps each eye's readings from the newest CCD that has any. A CCD is a
document that parsed as a CDA or failed; a weak candidate that was not
a CDA takes none of the three. At most ten candidate documents are
tried in all. The search stops once both eyes are covered. Readings
that name no eye, or both eyes, are kept only from the first CCD that
has any readings, and cover neither eye.
Given the date of both eyes' newest best-corrected readings in the
patient's Observations (observed), the documents are listed and
their candidates chosen as usual, but nothing is downloaded unless a
candidate may be newer than the older of the two readings: the newest
of its date, period end, period start and last-updated time is on or
after that reading's date, compared by calendar date, or it states
none readably. A partial time stands for its last possible day
(2025-03 for 2025-03-31). Otherwise the result is complete with no
readings, counted as ccd_not_newer. When a candidate may be newer,
counted as ccd_may_be_newer, only the candidates that may be newer are
read, newest first as usual. A capped listing is read as usual, since
the check cannot be made.
Within a document, only XML-typed and untyped renditions are tried, and the first that parses as a CDA is read. A document fails when none of its renditions parses, unless it was a weak (XML-only) candidate whose renditions all turned out not to be a CDA: that is a document of another kind, not a CCD that could not be read.
Documents are held in memory only. Nothing about a document, its
patient or an error's message is logged or counted: only counts and
text_shape masks.
Arguments
codes: The(system, code)pairs of the acuity observations to read.systemis a short name fromCODE_SYSTEM_TO_IDENTIFIER(e.g."loinc"), orNonefor the code in LOINC or SNOMED.observed: The date of each eye's newest best-corrected reading in the patient'sObservations. With both eyes given, the CCDs are downloaded only if one may be newer (see above).None, or one eye, reads them as usual.
Returns
The readings found. complete is False if the listing was
capped, the server does not serve DocumentReference (no readings,
counted as listing_unsupported), a CCD that could have supplied
an eye failed, or the ten documents were tried with an eye still
uncovered and candidates left (documents_tried_capped).
Raises
EHRFetchUnsupportedError: Only if the provider does not read acuity from documents. A server that will not list documents for a provider that does gives an incomplete result instead.FHIRR4APIError: If a page of the listing fails (seeget_document_infos).OperationOutcome: AsFHIRR4APIError, for a server that reports the failure that way.requests.RequestException: If the server could not be reached or did not answer in time while listing.
get_document_infos
def get_document_infos( self,) ‑> Iterable[list[EHRDocumentInfo]]:Inherited from:
DocumentAcuityReader.get_document_infos :
Yields document items related to this patient, a page at a time.
A listing that fails raises as it is iterated, so a failure is never read as a patient with no (more) documents.
Raises
FHIRR4APIError: If a page of the listing fails, including an answer that is not a Bundle (such as anOperationOutcomesent with a 200), which is raised with fhirpy'sInvalidResponseas its__cause__.OperationOutcome: AsFHIRR4APIError, for a server that reports the failure that way.requests.RequestException: If the server could not be reached or did not answer in time: the connection or timeout error left after the client's retries.
get_next_appointment
def get_next_appointment(self) ‑> datetime.date | None:Inherited from:
PractitionerReader.get_next_appointment :
Get the next appointment date for the patient.
Falls back to encounters if appointments are not available or empty.
Returns The next appointment date for the patient from today, or None if they have no future appointment. Any cancelled or errored appointments are ignored.
Raises
FHIRR4GetPatientInfoError: If unable to retrieve patient information.
get_patient_allergies
def get_patient_allergies(self) ‑> list[Allergy]:Inherited from:
AllergiesReader.get_patient_allergies :
Get allergy/intolerance information for this patient.
Fetched unfiltered (no code list to search by): allergy lists are
small enough per patient to fetch whole and match against a
criteria_tree leaf's own code/system afterwards. code
(AllergyIntolerance's own top-level CodeableConcept, 0..1) and
each reaction[].substance (also a CodeableConcept, 0..*) can
each carry more than one coding. One Allergy is returned per
FHIR resource, with codings holding every coding on its own
code and each AllergyReaction.substance_codings holding every
coding on that reaction's substance — not one entry per coding,
so the same clinical fact is never stored more than once. A code
with no coding at all still leaves code_system/code_code/
code_display and codings empty — AllergyIntolerance.code is
0..1, so a resource may carry no coded diagnosis and rely
entirely on reaction[].substance instead. An allergy whose
verificationStatus is entered-in-error is left out.
Returns A list of Allergy objects relevant for the patient, sorted by date.
Raises
FHIRR4GetPatientInfoError: If unable to retrieve patient allergy information.
get_patient_associated_medical_practitioner
def get_patient_associated_medical_practitioner(self) ‑> str | None:Inherited from:
PractitionerReader.get_patient_associated_medical_practitioner :
Retrieve an associated medical practitioner for the patient.
This prefers a practitioner referenced on the Patient resource via
generalPractitioner. If none is available there, it falls back to
the practitioner on the latest appointment or encounter.
Returns The practitioner's name, or None if no associated practitioner can be resolved.
Raises
FHIRR4GetPatientInfoError: If unable to retrieve patient encounter information.
get_patient_code_states
def get_patient_code_states( self, *, include_medications: bool = False,) ‑> PatientCodeDetails:Get information of Conditions, Procedures, and (optionally) Medications.
Sugar method that combines get_patient_conditions(), get_patient_procedures(), and — when requested — get_patient_medications(), returning a pre-constructed PatientCodeDetails container.
Arguments
include_medications: When True, also fetches medications (4 extra HTTP round-trips against MedicationRequest/Statement/ Dispense/Administration). Defaults to False so the many existing callers that only readcondition_codes/procedure_codesdo not pay for a fetch whose result they never consume.
Returns
A PatientCodeDetails instance detailing the presence or absence of the
provided Conditions, Procedures, and Medications for the patient.
medication_codes is None when include_medications is False,
the same as a fetch that was never attempted.
Raises
FHIRR4GetPatientInfoError: If unable to retrieve condition information.
get_patient_conditions
def get_patient_conditions( self, statuses_filter: list[ClinicalStatus] | None = None, code_types_filter: list[CodeSystems] | None = None,) ‑> list[Condition]:Inherited from:
ConditionsReader.get_patient_conditions :
Get conditions related to this patient.
A condition whose verificationStatus is entered-in-error is left
out. A condition's onset date is its onsetDateTime, else its
onsetPeriod.start, else its recordedDate.
Arguments
statuses_filter: If provided, returns only conditions of that status e.g. ['active','recurrence']code_types_filter: If provided, returns only conditions with codes of a specific code system (ICD10, Snomed) e.g. ["icd10"]
Returns A list of Condition objects relevant for the patient, detailing its status and dates, sorted by condition onset date.
Raises
FHIRR4GetPatientInfoError: If unable to retrieve patient condition information.
get_patient_devices
def get_patient_devices(self) ‑> list[Device]:Inherited from:
DevicesReader.get_patient_devices :
Get device information for this patient.
Fetched unfiltered (no code list to search by): device lists are
small enough per patient to fetch whole and match against a
criteria_tree leaf's own code/system afterwards. type
(Device's own top-level CodeableConcept, 0..1) can itself
carry more than one coding; codings holds every one of them. One
Device is returned per FHIR resource. A type with no coding at
all (or absent entirely) still leaves code_system/code_code/
code_display and codings empty. A device whose status is
entered-in-error is left out.
Returns
A list of Device objects relevant for the patient, sorted by
code for deterministic output (FHIR R4 Device has no field
meaning "when this became relevant to the patient" to sort by).
Raises
FHIRR4GetPatientInfoError: If unable to retrieve patient device information.
get_patient_medications
def get_patient_medications(self) ‑> list[Medication]:Inherited from:
MedicationsReader.get_patient_medications :
Get medication-related information for this patient.
This method queries MedicationRequest, MedicationStatement,
MedicationDispense, and MedicationAdministration in sequence.
This matches every other resource type this querier fetches. A
server may support only some of these four resource types. If so,
that server still gives us whatever it has. The whole call does
not fail just because one of the four resource types is absent.
A resource whose status is entered-in-error is left out.
Returns A list of Medication objects for the patient, sorted by date.
Raises
FHIRR4MedicationsUnsupportedError: Every resource type came backUNSUPPORTED. None processed, and none errored. This exception is aFHIRR4GetPatientInfoErrorsubclass. It is the only case that means "this server structurally does not support medications".FHIRR4GetPatientInfoError: At least one resource type genuinely failed (a network error or a deserialisation error), and none processed successfully. This result is too uncertain to report as the more specific "unsupported" signal above.
get_patient_observations
def get_patient_observations( self, codes: Sequence[tuple[str | None, str]],) ‑> list[Observation]:Inherited from:
ObservationsReader.get_patient_observations :
Get Observation resources matching any of the given codes.
Arguments
codes:(code_system, code)pairs to search for.code_systemis a short name fromCODE_SYSTEM_TO_IDENTIFIER(e.g."loinc","snomed");Nonematches the code value across any system.
Returns Observations for the patient matching any of the given codes, should be sorted by date (newest first).
Raises
FHIRR4GetPatientInfoError: If unable to retrieve Observation information for the patient.
get_patient_observations_by_category
def get_patient_observations_by_category( self, categories: Sequence[str],) ‑> list[Observation]:Inherited from:
ObservationsReader.get_patient_observations_by_category :
Get Observation resources matching any of the given categories.
Arguments
categories: Core FHIR observation-category values to search for (e.g.["laboratory", "vital-signs"]).
Returns Observations for the patient matching any of the given categories, sorted by date (newest first).
Raises
FHIRR4GetPatientInfoError: If unable to retrieve Observation information for the patient.
get_patient_procedures
def get_patient_procedures( self, statuses_filter: list[ProcedureStatus] | None = None, code_types_filter: list[CodeSystems] | None = None,) ‑> list[Procedure]:Inherited from:
ProceduresReader.get_patient_procedures :
Get information of procedure codes this patient has.
A procedure whose status is entered-in-error is left out.
Arguments
statuses_filter: If provided, returns only procedures of that status e.g. ['completed', 'in-progress']code_types_filter: If provided, returns only conditions with codes of a specific code system (CPT4, Snomed) e.g. ["cpt4", "snomed"]
Returns A list of Procedure objects relevant for the patient, detailing its status and dates, sorted by procedure date.
Raises
FHIRR4GetPatientInfoError: If unable to retrieve patient procedures information.
get_patient_response_by_id
def get_patient_response_by_id(self) ‑> dict[str, typing.Any] | None:Get JSON response from /Patient endpoint given a Patient ID.
Best-effort: its callers treat the patient resource as optional detail
for an already-identified patient, so a read that fails returns None
like an absent one rather than raising, and is logged without the ID.
That covers an API error or an error OperationOutcome, an answer
that cannot be read (not a Bundle, or not JSON), each a
FHIRR4APIError (see SearchExecutor.get), and a connection or
timeout error left after the client's retries.
Raises
FHIRR4AuthenticationError: If the EHR rejected the read.MultipleResourcesFound: If more than one patient has the ID.
get_previous_appointment_details
def get_previous_appointment_details( self, include_maybe_attended: bool = True,) ‑> list[EHRAppointmentEncounter]:Inherited from:
PractitionerReader.get_previous_appointment_details :
Get list of previous appointments for the patient.
A cancelled, no-show or entered-in-error appointment is left out, and
so is one only booked or proposed (waitlist, booked, pending,
proposed) unless include_maybe_attended is true.
Returns A list of EHRAppointmentEncounter for the patient, sorted chronologically (oldest first), or an empty list if they have no previous appointments.
Raises
FHIRR4GetPatientInfoError: If unable to retrieve patient information.
get_previous_encounter_details
def get_previous_encounter_details( self, include_maybe_attended: bool = True,) ‑> list[EHRAppointmentEncounter]:Inherited from:
PractitionerReader.get_previous_encounter_details :
Get list of previous encounters for the patient.
A cancelled, on-leave or entered-in-error encounter is left out, and so
is one not yet known to have happened (planned, in-progress,
triaged, unknown) unless include_maybe_attended is true.
Returns A list of EHRAppointmentEncounter for the patient, sorted chronologically (oldest first), or an empty list if they have no previous appointments.
Raises
FHIRR4GetPatientInfoError: If unable to retrieve patient information.
get_visual_acuity
def get_visual_acuity(self) ‑> Observation | None:Inherited from:
ObservationsReader.get_visual_acuity :
Get Visual Acuity observation for a patient.
json_dump
def json_dump( self, save_path: Path, elements: Container[str] = frozenset({'procedures', 'patientInfo', 'encounters', 'medications', 'chart', 'appointments', 'conditions'}),) ‑> collections.abc.Mapping[str, typing.Any] | None:Inherited from:
Save a JSON dump of the patient's record to save_path.
The querier's produce_json_dump, under the protocol's name.
Arguments
save_path: Where to save the dump.elements: The parts of the record to dump.
Returns
The dump, or None if there was nothing to dump.
produce_json_dump
def produce_json_dump( self, save_path: Path, elements_to_dump: Container[str] = frozenset({'procedures', 'patientInfo', 'encounters', 'medications', 'chart', 'appointments', 'conditions'}),) ‑> bitfount.externals.ehr.fhir_r4.readers.json_dump._FHIRR4PatientJSONDump:Inherited from:
JSONDumpReader.produce_json_dump :
Produce a JSON dump of patient information for the target patient.
Saves the JSON dump out to file and the contents can be controlled by
elements_to_dump.
The following options are recognised:
- "patientInfo": /Patient
- "appointments":
/Appointment(not always available) - "conditions":
/Conditions - "encounters":
/Encounters - "medications":
/MedicationRequest - "procedures":
/Procedures
Arguments
save_path: The file location to save the JSON dump to.elements_to_dump: Collection of elements to include in the dump. See above for what options can be included.
Returns The assembled JSON dump. Elements that could not be retrieved (or that the server does not support) are omitted, so callers can inspect the result to decide whether the dump contains anything meaningful.
reads_acuity_from_documents
def reads_acuity_from_documents(self) ‑> bool:Inherited from:
DocumentAcuityReader.reads_acuity_from_documents :
Whether the provider reads acuity from documents (get_document_acuity).
record_acuity_sources
def record_acuity_sources(self, *, in_observations: bool, in_documents: bool) ‑> None:Inherited from:
DocumentAcuityReader.record_acuity_sources :
Record where this patient's acuity was found, in the server knowledge.
Does nothing for a provider that does not read acuity from documents.
Arguments
in_observations: Whether the patient'sObservations held a reading for either eye.in_documents: Whether the patient's documents held a reading for either eye.
with_name
def with_name( self, *, given_name: str | None = None, family_name: str | None = None,) ‑> Self:Inherited from:
The same patient's record, with these names in its demographics.
A shallow copy: it shares this record's connection and raw patient
resource. Its demographics are a copy of the top-level dict, so the
names set here do not reach this record, but nested values (such as
the lists of numbers and practitioners) are shared. A name left as
None keeps the record's own. This record is not changed.
A record with no demographics gets demographics holding the patient's
ID and the names given, every other detail empty (None, or an empty
list); given no names, the copy has no demographics either.
Arguments
given_name: The given names to carry, joined by spaces.family_name: The family name to carry.