Skip to main content

resource_fetch

Cached, error-handled fetching of FHIR R4 resources from a FHIR server.

Classes​

SearchExecutor​

class SearchExecutor(    fhir_client: FHIRClient,    *,    profile: ProviderProfile | None = None,    cache_scope: str | None = None,):

Runs searches against one FHIR server.

Owns how a search is run: what the server is known not to support, searches given up on, params left off or dropped and retried, the response cache and its scope, and reporting each outcome back to the server knowledge (FHIRServerKnowledge).

Arguments

  • fhir_client: The client for the server.
  • profile: The provider's quirks; the default profile when not given.
  • cache_scope: The response cache's scope; the server's when not given.

Variables​

  • cache_scope : str - The response cache's scope.
  • knowledge : FHIRServerKnowledge - What is known about the server.

    Reading it does not fetch the CapabilityStatement; search, get and first load it before their first request.

  • profile : ProviderProfile - The provider's quirks.

Methods​


fetch_page​

def fetch_page(    self, path: str, params: Mapping[str, Any], headers: Mapping[str, str] | None = None,) ‑> Any:

Request one page of a search directly, uncached.

For callers that page by hand, such as patient listing.

Arguments

  • path: The request path, e.g. Patient.
  • params: The search parameters.
  • headers: Extra request headers, if any.

Returns The parsed response body.

first​

def first(    self,    resource_type: str,    search_params: Mapping[str, str | Sequence[str]],    *,    search_failure_as_missing: bool = False,) ‑> dict[str, typing.Any] | None:

Get first matching FHIR resource with error handling.

Wraps _cached_first_resource so transient errors are not cached. Shares the resource-type support tracking used by search: a type the server does not support is skipped proactively (advertised absent from its CapabilityStatement) or reactively (revealed unsupported by an earlier request, while that finding stands). An unsupported type raises FHIRR4ResourceTypeNotSupportedError, or answers None with search_failure_as_missing.

A failed search propagates by default too. None from this function otherwise means "no such resource", so swallowing an outage into it reports a definite absence the server never confirmed — the same conflation search avoids by not returning []. A caller for whom the lookup is genuinely optional enrichment opts in with search_failure_as_missing.

A bare 404 is part of that, not an exception to it. Some servers answer a request for a type they do not serve with a 404 rather than an empty bundle, so "the endpoint is not there" and "this patient has no such resource" arrive identically — and only the caller knows which reading is safe for it.

Arguments

  • resource_type: The type of FHIR resource to search for.
  • search_params: JSON-serializable search parameters.
  • search_failure_as_missing: When True, a failed search answers None instead of raising. Covers a bare 404 and an unsupported resource type as well as a broken search: all mean "no answer", and a caller that reads None as "this patient has none" must not opt in.

Returns The first matching resource, or None when there is none.

Raises

  • FHIRR4APIError: When the search failed, unless search_failure_as_missing is True.
  • OperationOutcome: As FHIRR4APIError, for a server that reports the failure that way.
  • FHIRR4ResourceTypeNotSupportedError: When the server does not support resource_type, whether that is already recorded or discovered by this call, unless search_failure_as_missing is True.
  • ResourceNotFound: On a bare 404, unless search_failure_as_missing is True.

get​

def get(    self, resource_type: str, search_params: dict[str, str],) ‑> dict[str, typing.Any] | None:

Get a single FHIR resource with error handling.

Wraps _cached_get_resource so transient errors are not cached. Shares the resource-type support tracking used by search/first: a type the server does not support is skipped proactively or reactively, and a live unsupported-type response is recorded.

Returns None when no resource matched (an empty search result, or a bare 404, which _cached_get_resource caches as None) and when the server does not support resource_type, whether already known or discovered by this call. Any other failure is logged and raised, so a caller resolving a patient cannot mistake a failed lookup for an absent patient.

An answer that cannot be read is raised as FHIRR4APIError, chained to the error it was read with: a 200 that is not a Bundle (fhirpy's InvalidResponse) or not JSON (json.JSONDecodeError, or UnicodeDecodeError for a body that is not UTF-8), and fhirpy's own OperationOutcome. The client's own errors are raised as they are.

Arguments

  • resource_type: The type of FHIR resource to get.
  • search_params: JSON-serializable search parameters.

Returns The single matching resource, or None as described above.

Raises

  • FHIRR4AuthenticationError: If the server rejected the request as unauthenticated.
  • FHIRR4APIError: When the request failed, or its answer could not be read.
  • MultipleResourcesFound: If more than one resource matches.
  • 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.
def search(self, spec: SearchSpec) ‑> list[dict[str, typing.Any]]:

Search for FHIR resources with error handling.

Wraps _cached_search_resources, which caches only successful responses, so a failed search is never answered from the cache. A failure propagates by default; a spec with search_failure_as_empty answers an empty list for a search that failed outright instead.

A FHIR search returns a 200 empty bundle when a patient has no matching resources; a 404 (ResourceNotFound) instead means the type/endpoint is unavailable (the server does not support it). Those are different: the former is "confirmed empty", the latter "could not determine". By default a 404 therefore propagates, so callers that must distinguish the two (e.g. the code-states path, where a false "confirmed empty" would corrupt eligibility) can. Callers that just want to skip a missing element (the JSON dump) pass missing_resource_as_empty=True; the appointment and encounter lookups deliberately do not, since a [] there is read as a confirmed negative.

Arguments

  • spec: The search; see SearchSpec.

Returns List of serialized FHIR resources. An empty list means the search succeeded and matched nothing (a 200 empty bundle) — except when search_failure_as_empty is set, the one case where it can also mean the search failed.

Raises

  • FHIRR4ResourceTypeNotSupportedError: When the server does not support the resource type (known in advance or revealed by a 404), unless missing_resource_as_empty is True. Subclasses ResourceNotFound.
  • FHIRR4ResourceTypeUnresponsiveError: When this search (see search_plan.search_filters) has timed out MAX_CONSECUTIVE_TIMEOUTS times in a row and is given up on until its recheck is due, and the response cache holds no answer to it, unless search_failure_as_empty is True. Notably not suppressed by missing_resource_as_empty: an endpoint that stopped answering is not an endpoint the server lacks.
  • FHIRR4CodesRejectedError: When codes is searched one code at a time (Nextech) and the server refused every code as a search value.
  • ResourceNotFound: On a 404, unless missing_resource_as_empty is True.
  • FHIRR4APIError: When the search failed and the param-less retry did not recover it, unless search_failure_as_empty is True.
  • OperationOutcome: As FHIRR4APIError, for a server that reports the failure as an OperationOutcome instead.
  • requests.Timeout: As FHIRR4APIError, for a search that timed out.
  • TypeError: When the plan's action is not one this method runs.