Searching for FHIR resources Stay organized with collections Save and categorize content based on your preferences.
This page explains the basic instructions for how to search for FHIR resources in a FHIR store. Searching forFHIR resources is the primary way to query and get insights from FHIR data.
You can search for FHIR resources in the Cloud Healthcare APIin the following ways:
- Using the FHIR viewer in the Google Cloud console.
- Using the
projects.locations.datasets.fhirStores.fhir.searchmethod. The method provides the following ways of searching for FHIR resources:GETrequestsPOSTrequests
This page summarizes manyof the commonly used search features, but is not an exhaustive list of parts of theFHIR search specification supported by the Cloud Healthcare API.
Using the FHIR viewer
The FHIR viewer is a page in the Google Cloud console that lets you search forandview the contents of FHIR resources.
To search for resources in a FHIR store, complete the following steps:
In the Google Cloud console, go to theFHIR viewer page.
In theFHIR Store drop-down list, select a dataset, and then selecta FHIR store in the dataset.
To filter the list of resource types, search for the resource types that youwant to display:
Click theResource Type field.
In theProperties drop-down list that appears, selectResource Type.
Enter a resource type.
To search for another resource type, selectOR from theOperators drop-down list that appears, and then enter another resource type.
In the list of resource types, select the resource type that you want tosearch on.
In the search box for the table of resources that appears, enter the valuethat you want to search for.
The FHIR viewer displays the search results in a table. After you select aresource, the FHIR viewer displays the contents of the resource.
When you view the contents of a resource, you can search for data inside theresource.
To search for data inside a resource, follow these steps:
Select a resource.
In theFHIR viewer pane, click theElements tab.
In the search box, enter the value that you want to search for.
Downloading binary data within FHIR resources
To download the available binary data associated with a resource in the FHIRviewer, follow these steps:
Select a resource.
In theFHIR viewer pane, click theElements tab.
If necessary, expand the elements to access the required resource element.
ClickDownload File to download the available data.
Creating and running advanced search queries
You can use advanced search queries to search for specific FHIR resources usingtheFHIR search specification.
To create an advanced search query, complete the following steps:
On theFHIR viewer page, click theSearch tab.
To create a search query, clickOpen query Builder.
TheQuery Selection panel is displayed.
From theSelect a FHIR resource type list, choose the FHIRresource type you want to search for.
ClickContinue.
From theParameter list, select the parameter that you want to useto search for resources.
From theModifier list, select the modifier to apply to thequery. The list only includes modifiers compatible with the data type of theselected parameter.
This is an optional selection. If no modifier is selected, then an equalitycheck is performed.
In theValue field, enter the value of the query parameter.
To add more than one parameter value, clickOR. This enables you toinclude multiple values of your resource parameter in your search query.
As you build your search query, the query is displayed on theQueryPreview pane. To view the full URL of the search query, clickShow fullpath.
To add more than one parameter, clickAND.
ClickContinue.
To include resources that are referenced by the resources returned in yoursearch query, choose the resource parameter from theIncluded parametersdrop-down list.
To include resources that reference the resources returned in your searchquery, choose the resource parameter from theReverse includedparameters drop-down list.
ClickDone to save your search query.
The saved search query is displayed in theFHIR search operation field.
To search for resources with the query, clickRun Search.
The search results are displayed in theSearch results list. To viewdetails of a resource returned by the search, click a resource in the list.
To save the query as a query template, clickSave template and chooseSave template orSave template as. You are prompted for a name and description for the query.The query parameters are saved in a template, but any defined values areremoved.
Example search query
The following example shows a search query that searches for Claim resources from aspecific healthcare provider, Practitioner/12345, for the month of August, 2021:
- Parameter:
care-team- Value:
Practitioner/12345
- Value:
- Operator:AND
- Parameter:
created- Prefix:
lt (lesser than) - Value:
8/1/21, 12:00 AM
- Prefix:
- Operator:AND
- Parameter:
created- Prefix:
gt (greater than) - Value:
8/31/21, 11:59 PM
- Prefix:
This is configured as follows in theQuery Selection panel and the query ispreviewed in theQuery Preview pane. The query will be displayed in theFHIR search operation field.
Note: The CareTeam resource includes a reference to a Practitioner resourcewhich is defined by including the resource type, Practitioner, before theresource's unique ID,12345.
Editing search queries
To edit a search query, do one of the following:
- To edit the query in the query builder, clickOpen Query Builder.
- To manually edit the query, edit the parameter values in the textbox.
Running query templates
To run a query from a saved template, complete the following steps:
ClickSaved templates.
TheSearch templates tab of theQuery Selection panel is displayed,showing all saved query templates.
Select the query template you want to run and clickDone.
The template's search query is displayed in theFHIR search operationfield without any values.
To define the values of your search query, edit the parameter values in the field.
ClickRun Search to search for resources with the query.
Share FHIR resources
You can share a link to the current or historical versions of a FHIR resource.
Permissions required for this task
To perform this task, you must have been granted the following permissionsor the followingIdentity and Access Management (IAM) roles:
Permissions
healthcare.fhirResources.get
Roles
- Healthcare FHIR Resource Reader (
roles/healthcare.fhirResourceReader)
You can ask your administrator to grant you these Identity and Access Management roles. For instructions ongranting roles, seeManage access orControl access to Cloud Healthcare API resources.You might also be able to get the required permissions throughcustom roles or otherpredefined roles.
Note: If you created a Google Cloud project for this guide, then, as the project creator, you're automatically granted the Owner (roles/owner) IAM role, which has the permissions. You don't need to be granted any additional IAM roles.Console
In the Google Cloud console, go to theFHIR viewer page.
In theFHIR store menu, select a dataset, and then selecta FHIR store in the dataset.
To filter the list of FHIR resource types, search for the resource types that youwant to display.
Click theResource type field.
In theProperties drop-down list that appears, selectResource Type.
Enter a FHIR resource type.
In the list of FHIR resource types, select a resource type.
In the table of FHIR resources that appears, select orsearch fora resource.
In theFHIR viewer pane, clickShare. A link to share the FHIRresource is automatically copied to the clipboard.
Using thesearch method
To search for FHIR resources with the REST API, use theprojects.locations.datasets.fhirStores.fhir.searchmethod. You can call the method usingGET orPOST requests.
Using thesearch method withGET
The following samples show how to search for resources in a given FHIR storeusing theprojects.locations.datasets.fhirStores.fhir.searchmethod withGET.
curl
To search for resources in a FHIR store, make aGET request andspecify the following information:
- The name of the dataset
- The name of the FHIR store
- The type of resource to search for
- A query string containing the information you're searching for, as describedin theConstructing a search query section
- An access token
The following sample shows aGET request usingcurl to search for allpatients with the last name "Smith".
curl-XGET\-H"Authorization: Bearer$(gcloudauthapplication-defaultprint-access-token)"\"https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient?family:exact=Smith"
If the request is successful, the server returns the response as a FHIRBundlein JSON format. TheBundle.type issearchset and the search results areentries in theBundle.entry array. In this example, the request returns asingle Patient resource including the data inside that resource:
{ "entry": [ { "fullUrl": "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/PATIENT_ID", "resource": { "birthDate": "1970-01-01", "gender": "female", "id": "PATIENT_ID", "meta": { "lastUpdated": "LAST_UPDATED", "versionId": "VERSION_ID" }, "name": [ { "family": "Smith", "given": [ "Darcy" ], "use": "official" } ], "resourceType": "Patient" }, "search": { "mode": "match" } } ], "link": [ { "url": "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/?family%3Aexact=Smith" } ], "resourceType": "Bundle", "total": 1, "type": "searchset"}PowerShell
To search for resources in a FHIR store, make aGET request andspecify the following information:
- The name of the dataset
- The name of the FHIR store
- The type of resource to search for
- A query string containing the information you're searching for, as describedin theConstructing a search query section
- An access token
The following sample shows aGET request using Windows PowerShell to searchfor all patients with the last name "Smith".
$cred=gcloudauthapplication-defaultprint-access-token$headers=@{Authorization="Bearer$cred"}Invoke-RestMethod`-MethodGet`-Headers$headers`-Uri"https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/RESOURCE_TYPE?family:exact=Smith"|ConvertTo-Json
If the request is successful, the server returns the response as a FHIRBundlein JSON format. TheBundle.type issearchset and the search results areentries in theBundle.entry array. In this example, the request returns asingle Patient resource including the data inside that resource:
{ "entry": [ { "fullUrl": "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/PATIENT_ID", "resource": { "birthDate": "1970-01-01", "gender": "female", "id": "PATIENT_ID", "meta": { "lastUpdated": "LAST_UPDATED", "versionId": "VERSION_ID" }, "name": [ { "family": "Smith", "given": [ "Darcy" ], "use": "official" } ], "resourceType": "Patient" }, "search": { "mode": "match" } } ], "link": [ { "url": "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/?family%3Aexact=Smith" } ], "resourceType": "Bundle", "total": 1, "type": "searchset"}Java
importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.api.client.json.JsonFactory;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.healthcare.v1.CloudHealthcare;importcom.google.api.services.healthcare.v1.CloudHealthcareScopes;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importjava.io.IOException;importjava.net.URISyntaxException;importjava.util.Collections;importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.HttpStatus;importorg.apache.http.client.HttpClient;importorg.apache.http.client.methods.HttpUriRequest;importorg.apache.http.client.methods.RequestBuilder;importorg.apache.http.client.utils.URIBuilder;importorg.apache.http.entity.StringEntity;importorg.apache.http.impl.client.HttpClients;publicclassFhirResourceSearchGet{privatestaticfinalStringFHIR_NAME="projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/%s";// The endpoint URL for the Healthcare API. Required for HttpClient.privatestaticfinalStringAPI_ENDPOINT="https://healthcare.googleapis.com";privatestaticfinalJsonFactoryJSON_FACTORY=newGsonFactory();privatestaticfinalNetHttpTransportHTTP_TRANSPORT=newNetHttpTransport();publicstaticvoidfhirResourceSearchGet(StringresourceName)throwsIOException,URISyntaxException{// String resourceName =// String.format(// FHIR_NAME, "project-id", "region-id", "dataset-id", "fhir-store-id");// String resourceType = "Patient";// Instantiate the client, which will be used to interact with the service.HttpClienthttpClient=HttpClients.createDefault();Stringuri=String.format("%s/v1/%s",API_ENDPOINT,resourceName);URIBuilderuriBuilder=newURIBuilder(uri).setParameter("access_token",getAccessToken());// To set additional parameters for search filtering, add them to the URIBuilder. For// example, to search for a Patient with the family name "Smith", specify the following:// uriBuilder.setParameter("family:exact", "Smith");HttpUriRequestrequest=RequestBuilder.get().setUri(uriBuilder.build()).build();// Execute the request and process the results.HttpResponseresponse=httpClient.execute(request);HttpEntityresponseEntity=response.getEntity();if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){System.err.print(String.format("Exception searching GET FHIR resources: %s\n",response.getStatusLine().toString()));responseEntity.writeTo(System.err);thrownewRuntimeException();}System.out.println("FHIR resource GET search results: ");responseEntity.writeTo(System.out);}privatestaticCloudHealthcarecreateClient()throwsIOException{// Use Application Default Credentials (ADC) to authenticate the requests// For more information see https://cloud.google.com/docs/authentication/productionGoogleCredentialscredential=GoogleCredentials.getApplicationDefault().createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));// Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.HttpRequestInitializerrequestInitializer=request->{newHttpCredentialsAdapter(credential).initialize(request);request.setConnectTimeout(60000);// 1 minute connect timeoutrequest.setReadTimeout(60000);// 1 minute read timeout};// Build the client for interacting with the service.returnnewCloudHealthcare.Builder(HTTP_TRANSPORT,JSON_FACTORY,requestInitializer).setApplicationName("your-application-name").build();}privatestaticStringgetAccessToken()throwsIOException{GoogleCredentialscredential=GoogleCredentials.getApplicationDefault().createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));returncredential.refreshAccessToken().getTokenValue();}}Node.js
// Import google-auth-library for authentication.const{GoogleAuth}=require('google-auth-library');constsearchFhirResourcesGet=async()=>{constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/cloud-platform',});// TODO(developer): uncomment these lines before running the sample// const cloudRegion = 'us-central1';// const projectId = 'adjective-noun-123';// const datasetId = 'my-dataset';// const fhirStoreId = 'my-fhir-store';// const resourceType = 'Patient';consturl=`https://healthcare.googleapis.com/v1/projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}`;constparams={};// Specify search filters in a params object. For example, to filter on a// Patient with the last name "Smith", set resourceType to "Patient" and// specify the following params:// params = {'family:exact' : 'Smith'};constclient=awaitauth.getClient();constresponse=awaitclient.request({url,method:'GET',params});constresources=response.data.entry;console.log(`Resources found:${resources.length}`);console.log(JSON.stringify(resources,null,2));};searchFhirResourcesGet();Python
defsearch_resources_get(project_id,location,dataset_id,fhir_store_id,resource_type,):""" Uses the searchResources GET method to search for resources in the given FHIR store. See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir before running the sample."""# Imports Python's built-in "os" moduleimportos# Imports the google.auth.transport.requests transportfromgoogle.auth.transportimportrequests# Imports a module to allow authentication using a service accountfromgoogle.oauth2importservice_account# Gets credentials from the environment.credentials=service_account.Credentials.from_service_account_file(os.environ["GOOGLE_APPLICATION_CREDENTIALS"])scoped_credentials=credentials.with_scopes(["https://www.googleapis.com/auth/cloud-platform"])# Creates a requests Session object with the credentials.session=requests.AuthorizedSession(scoped_credentials)# URL to the Cloud Healthcare API endpoint and versionbase_url="https://healthcare.googleapis.com/v1"# TODO(developer): Uncomment these lines and replace with your values.# project_id = 'my-project' # replace with your GCP project ID# location = 'us-central1' # replace with the parent dataset's location# dataset_id = 'my-dataset' # replace with the parent dataset's ID# fhir_store_id = 'my-fhir-store' # replace with the FHIR store ID# resource_type = 'Patient' # replace with the FHIR resource typeurl=f"{base_url}/projects/{project_id}/locations/{location}"resource_path="{}/datasets/{}/fhirStores/{}/fhir/{}".format(url,dataset_id,fhir_store_id,resource_type)response=session.get(resource_path)response.raise_for_status()resources=response.json()print("Using GET request, found a total of{}{} resources:".format(resources["total"],resource_type))print(json.dumps(resources,indent=2))returnresourcesUsing thesearch method withPOST
The following samples show how to search for resources in a given FHIR storeusing theprojects.locations.datasets.fhirStores.fhir.searchmethod withPOST.
curl
To search for resources in a FHIR store, make aPOST request andspecify the following information:
- The name of the dataset
- The name of the FHIR store
- The type of resource to search for
- A query string containing the information you're searching for, as describedin theConstructing a search query section
- An access token
The following sample shows aPOST request usingcurl to search for allpatients with the last name "Smith".
curl-XPOST\--data""\-H"Authorization: Bearer$(gcloudauthapplication-defaultprint-access-token)"\-H"Content-Type: application/fhir+json; charset=utf-8"\"https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/_search?family:exact=Smith"
If the request is successful, the server returns the response as a FHIRBundlein JSON format. TheBundle.type issearchset and the search results areentries in theBundle.entry array. In this example, the request returns asingle Patient resource including the data inside that resource:
{ "entry": [ { "fullUrl": "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/PATIENT_ID", "resource": { "birthDate": "1970-01-01", "gender": "female", "id": "PATIENT_ID", "meta": { "lastUpdated": "LAST_UPDATED", "versionId": "VERSION_ID" }, "name": [ { "family": "Smith", "given": [ "Darcy" ], "use": "official" } ], "resourceType": "Patient" }, "search": { "mode": "match" } } ], "link": [ { "url": "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/?family%3Aexact=Smith" } ], "resourceType": "Bundle", "total": 1, "type": "searchset"}PowerShell
To search for resources in a FHIR store, make aPOST request andspecify the following information:
- The name of the dataset
- The name of the FHIR store
- The type of resource to search for
- A query string containing the information you're searching for, as describedin theConstructing a search query section
- An access token
The following sample shows aPOST request using Windows PowerShell to searchfor all patients with the last name "Smith".
$cred=gcloudauthapplication-defaultprint-access-token$headers=@{Authorization="Bearer$cred"}Invoke-RestMethod`-MethodPost`-Headers$headers`-ContentType:"application/fhir+json; charset=utf-8"`-Uri"https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/_search?family:exact=Smith"|ConvertTo-Json
If the request is successful, the server returns the response as a FHIRBundlein JSON format. TheBundle.type issearchset and the search results areentries in theBundle.entry array. In this example, the request returns asingle Patient resource including the data inside that resource:
{ "entry": [ { "fullUrl": "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/PATIENT_ID", "resource": { "birthDate": "1970-01-01", "gender": "female", "id": "PATIENT_ID", "meta": { "lastUpdated": "LAST_UPDATED", "versionId": "VERSION_ID" }, "name": [ { "family": "Smith", "given": [ "Darcy" ], "use": "official" } ], "resourceType": "Patient" }, "search": { "mode": "match" } } ], "link": [ { "url": "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/?family%3Aexact=Smith" } ], "resourceType": "Bundle", "total": 1, "type": "searchset"}Java
importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.api.client.json.JsonFactory;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.healthcare.v1.CloudHealthcare;importcom.google.api.services.healthcare.v1.CloudHealthcareScopes;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importjava.io.IOException;importjava.net.URISyntaxException;importjava.util.Collections;importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.HttpStatus;importorg.apache.http.client.HttpClient;importorg.apache.http.client.methods.HttpUriRequest;importorg.apache.http.client.methods.RequestBuilder;importorg.apache.http.client.utils.URIBuilder;importorg.apache.http.entity.StringEntity;importorg.apache.http.impl.client.HttpClients;publicclassFhirResourceSearchPost{privatestaticfinalStringFHIR_NAME="projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/%s";// The endpoint URL for the Healthcare API. Required for HttpClient.privatestaticfinalStringAPI_ENDPOINT="https://healthcare.googleapis.com";privatestaticfinalJsonFactoryJSON_FACTORY=newGsonFactory();privatestaticfinalNetHttpTransportHTTP_TRANSPORT=newNetHttpTransport();publicstaticvoidfhirResourceSearchPost(StringresourceName)throwsIOException,URISyntaxException{// String resourceName =// String.format(// FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "resource-type");// Instantiate the client, which will be used to interact with the service.HttpClienthttpClient=HttpClients.createDefault();Stringuri=String.format("%s/v1/%s/_search",API_ENDPOINT,resourceName);URIBuilderuriBuilder=newURIBuilder(uri).setParameter("access_token",getAccessToken());// To set additional parameters for search filtering, add them to the URIBuilder. For// example, to search for a Patient with the family name "Smith", specify the following:// uriBuilder.setParameter("family:exact", "Smith");// Set a body otherwise HttpClient complains there is no Content-Length set.StringEntityrequestEntity=newStringEntity("");HttpUriRequestrequest=RequestBuilder.post().setUri(uriBuilder.build()).setEntity(requestEntity).addHeader("Content-Type","application/fhir+json").addHeader("Accept-Charset","utf-8").addHeader("Accept","application/fhir+json; charset=utf-8").build();// Execute the request and process the results.HttpResponseresponse=httpClient.execute(request);HttpEntityresponseEntity=response.getEntity();if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){System.err.print(String.format("Exception searching POST FHIR resources: %s\n",response.getStatusLine().toString()));responseEntity.writeTo(System.err);thrownewRuntimeException();}System.out.println("FHIR resource POST search results: ");responseEntity.writeTo(System.out);}privatestaticCloudHealthcarecreateClient()throwsIOException{// Use Application Default Credentials (ADC) to authenticate the requests// For more information see https://cloud.google.com/docs/authentication/productionGoogleCredentialscredential=GoogleCredentials.getApplicationDefault().createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));// Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.HttpRequestInitializerrequestInitializer=request->{newHttpCredentialsAdapter(credential).initialize(request);request.setConnectTimeout(60000);// 1 minute connect timeoutrequest.setReadTimeout(60000);// 1 minute read timeout};// Build the client for interacting with the service.returnnewCloudHealthcare.Builder(HTTP_TRANSPORT,JSON_FACTORY,requestInitializer).setApplicationName("your-application-name").build();}privatestaticStringgetAccessToken()throwsIOException{GoogleCredentialscredential=GoogleCredentials.getApplicationDefault().createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));returncredential.refreshAccessToken().getTokenValue();}}Node.js
// Import google-auth-library for authentication.const{GoogleAuth}=require('google-auth-library');constsearchFhirResourcesPost=async()=>{constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/cloud-platform',// Set application/fhir+json header because this is a POST request.headers:{'Content-Type':'application/fhir+json'},});// TODO(developer): uncomment these lines before running the sample// const cloudRegion = 'us-central1';// const projectId = 'adjective-noun-123';// const datasetId = 'my-dataset';// const fhirStoreId = 'my-fhir-store';// const resourceType = 'Patient';consturl=`https://healthcare.googleapis.com/v1/projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/_search`;constparams={};// Specify search filters in a params object. For example, to filter on a// Patient with the last name "Smith", set resourceType to "Patient" and// specify the following params:// params = {'family:exact' : 'Smith'};constclient=awaitauth.getClient();constresponse=awaitclient.request({url,method:'POST',params});constresources=response.data.entry;console.log(`Resources found:${resources.length}`);console.log(JSON.stringify(resources,null,2));};searchFhirResourcesPost();Python
defsearch_resources_post(project_id,location,dataset_id,fhir_store_id):""" Searches for resources in the given FHIR store. Uses the _search POST method and a query string containing the information to search for. In this sample, the search criteria is 'family:exact=Smith' on a Patient resource. See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir before running the sample."""# Imports Python's built-in "os" moduleimportos# Imports the google.auth.transport.requests transportfromgoogle.auth.transportimportrequests# Imports a module to allow authentication using a service accountfromgoogle.oauth2importservice_account# Gets credentials from the environment.credentials=service_account.Credentials.from_service_account_file(os.environ["GOOGLE_APPLICATION_CREDENTIALS"])scoped_credentials=credentials.with_scopes(["https://www.googleapis.com/auth/cloud-platform"])# Creates a requests Session object with the credentials.session=requests.AuthorizedSession(scoped_credentials)# URL to the Cloud Healthcare API endpoint and versionbase_url="https://healthcare.googleapis.com/v1"# TODO(developer): Uncomment these lines and replace with your values.# project_id = 'my-project' # replace with your GCP project ID# location = 'us-central1' # replace with the parent dataset's location# dataset_id = 'my-dataset' # replace with the parent dataset's ID# fhir_store_id = 'my-fhir-store' # replace with the FHIR store IDurl=f"{base_url}/projects/{project_id}/locations/{location}"fhir_store_path="{}/datasets/{}/fhirStores/{}/fhir".format(url,dataset_id,fhir_store_id)resource_path=f"{fhir_store_path}/Patient/_search?family:exact=Smith"# Sets required application/fhir+json header on the requestheaders={"Content-Type":"application/fhir+json;charset=utf-8"}response=session.post(resource_path,headers=headers)response.raise_for_status()resources=response.json()print("Using POST request, found a total of{} Patient resources:".format(resources["total"]))print(json.dumps(resources,indent=2))returnresourcesConstructing a search query
The query string is a series ofname=value pairs encoded in URL form. A searchcombines all the pairs with a logicalAND. Each value can be acomma-separated list of values, which are treated as a logicalOR of thosevalues. For example,Patient?key1=value1&key2=value2,value3 is a search onPatient resources using the following criteria:
(key1 = value1) AND (key2 = value2 OR key2 = value3)
There is no syntax to perform anOR of twoname=value pairs.
Each FHIR resource type defines its own search parameters in each version ofFHIR. The available parameters are documented in the FHIR specificationfor each resource. For an example, seeFHIR R4 Patient.You can retrieve the parameters programmatically through thecapability statement.The Cloud Healthcare API supports most search parameters; you can find exclusionsthrough the capability statement orFHIR conformance statement.
Pagination and sorting
The number of resources returned on each page of the FHIR search results dependson the following factors:
- The
_countparameter. It controls the maximum number of resourcesreturned from the search method. For example,_count=10returns, at most,10 resources matching the query. The default is 100 and the maximum valueallowed is 1,000. - The size of the response data. A page of search results might return fewerresources than the value specified in the
_countparameter if the size ofthe response is large.
If a search returns more resources than the number of resources that fits on onepage, the response includes a pagination URL in theBundle.link field. Theremight be multiple values returned in this field; the value withBundle.link.relation = next indicates that you can use the correspondingBundle.link.url to retrieve the next page.
The value ofBundle.total indicates the total number of matchingresources. This value is exact if the results fit entirely in one page, butbecomes a rough estimate as the number of results becomes larger than one page.You can obtain an exact total for a search that matches many results byfollowing pagination links repeatedly until the results areexhausted.
For more information on pagination and search totals, seeImplementing pagination and search totals with FHIR search.
You can sort results using the_sort parameter, which accepts acomma-separated list of search parameter names in priority order. You canuse a- prefix to indicate decreasing order. For example, the following querysorts by status ascending, breaking ties by date descending, and breakingany remaining ties by category ascending:
_sort=status,-date,category
_sort syntax that was present in that version of the specification. Eachinstance of_sort takes one search parameter and an optional modifier of:asc or:desc. For example, in DSTU2, to perform the same sort ordering as theprevious example, use:_sort=status&_sort:desc=date&_sort=category._sort is only supported for search parameters of typenumber,data,string,token, andquantity. To sort using other types ofsearch parameters (for example,reference), useFHIR custom searchesto create, for example, astring search parameter on thereference field.
Indexing delay
FHIR resources are indexed asynchronously, so there might be a slight delaybetween the time a resource is created or changed, and the time when the changereflects in search results. The only exception is resource identifier data,which is indexed synchronously as a special index. As a result, searching usingresource identifier is not subject to indexing delay. To use the specialsynchronous index, the search term for identifier should be in the patternidentifier=[system]|[value] oridentifier=[value], and any of the followingsearch result parameters can be used:
_count_include_revinclude_summary_elements
If your query contains any other search parameters, the standard asynchronousindex will be used instead. Note that searching against the special index isoptimized for resolving a small number of matches. The search isn't optimized ifyour identifier search criteria matches a large number (i.e. more than 2,000) ofresources. For a search query that will match a large number of resources, youcan avoiding using the special synchronous index by including an additional_sort parameter in your query. Use_sort=-_lastUpdated if you want to keepthe default sorting order.
Searching across all resource types
Certain search parameters, shown by a leading underscore like_id,apply to all resource types. These all-resource parameters are listed in theFHIR specification for theResource type.
When using these search parameters, you can perform a search across multipleresource types by omitting the resource type from the request path. For example,usingGET .../fhir?_id=1234 instead ofGET .../fhir/Patient?_id=1234 searchesacross all FHIR resources instead of only a Patient resource. You can use the special parameter_typewith this type of request to limit the results to a comma-separatedlist of resource types. For example, the following queryonly returns matching results forObservation andCondition resources:
GET .../fhir?_tag=active&_type=Observation,Condition
Data types
Each search parameter defined by FHIR has a data type, which includes primitivetypes such as the following:
- String
- Number
- Date
Data types also include the following complex types:
- Token
- Reference
- Quantity
Each data type has its own syntax for specifying values. Each data typesupports modifiers that alter how the search is performed.
The following sections show how to use data types.For more details on additional data types, value syntaxes, and modifiers, seeAdvanced FHIR search features.
Number
Searches on integer or floating point values. To change the comparator, prefixthe value with one of the following modifiers:
neltlegtge
For example, use[parameter]=100 for equality, or use[parameter]=ge100 for greater thanor equal to 100.
Date
Searches on any type of date, time, or period. The date parameterformat is the following:
yyyy-mm-ddThh:mm:ss[Z|(+|-)hh:mm]The same prefix modifiers used fornumber apply.
String
Defaults to a prefix search that is insensitive to case,accents, or other diacritical marks.
Note: Punctuation characters split a search into multiple words, and thepunctuation characters themselves are ignored.Token
Searches for an exact string match of a "code". You can scope the searchto the URI of a "system" indicating the value set the code is taken from usingthe following format:
[parameter]=[system]|[code]For example, the following search matches a codeof 10738-3, but only when qualified as a value from a coding system with thespecified URI:
code=http://hl7.org/fhir/ValueSet/observation-codes|10738-3Quantity
Searches for a numeric value using the same prefix modifiers asnumber. You can qualify the search with a specific system and code indicating theunits of the value in following format:
[parameter]=[prefix][number]|[system]|[code]For example, the following query searches forquantity values less than 9.1 that have the specified unit system and code:
value-quantity=lt9.1|http://unitsofmeasure.org|mgReference
Searches for references between resources. You can use the following queriesfor references to resources inside a FHIR store:
[parameter]=[id][parameter]=[type]/[id]
You can use[parameter]=[url] to specify references by URLthat might be outside the FHIR store.
Search parameter handling
By default, the search method applies "lenient" handling, which ignoresparameters that the search does not recognize. The search method performs the search using anyremaining parameters in the request, which might return more resources thanexpected.
The response includes the following:
- A value in
Bundle.linkwith a value ofBundle.link.relation = self - A
Bundle.link.urlof a URL containing only the parameters that weresuccessfully applied to the search. You can inspect this value to determinewhether any parameters were ignored.
You can set the request HTTP header toPrefer: handling=strict on a searchrequest. Setting the header causes the FHIR store to return an error on any unrecognizedparameter.
defaultSearchHandlingStrictchanges this default tostrict for all search requests unless an individualrequest uses the HTTP headerPrefer: handling=lenient to choose lenient.Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-18 UTC.