Search FHIR resources

Stay organized with collections Save and categorize content based on your preferences.

Use a GET request or a POST request to search FHIR resources.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample


import (


// searchFhirResourcesGet uses a GET request to search for FHIR resources in a given FHIR store.
func searchFHIRResourcesGet(w io.Writer, projectID, location, datasetID, fhirStoreID, resourceType string) error {
	ctx := context.Background()

	// The Healthcare API endpoint, API version, and request path.
	name := fmt.Sprintf("", projectID, location, datasetID, fhirStoreID, resourceType)

	// DefaultClient returns an HTTP Client that uses the
	// DefaultTokenSource (Application Default Credentials)
	// to obtain authentication credentials.
	client, err := google.DefaultClient(ctx, "")
	if err != nil {

	// NewRequest takes an io.Reader as its third argument,
	// but the GET request to search for FHIR resources does
	// not pass any data in its body.
	req, err := http.NewRequest(http.MethodGet, name, nil)
	if err != nil {
		return fmt.Errorf("NewRequest: %v", err)

	// To set additional parameters for search filtering, append the
	// search terms as query parameters, then assign the encoded
	// query string to the request.
	// For example, to search for a Patient with the family name "Smith",
	// specify a Patient resourceType and then set the following:
	// q := req.URL.Query()
	// q.Add("family:exact", "Smith")
	// req.URL.RawQuery = q.Encode()

	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("Do: %v", err)

	defer resp.Body.Close()

	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("could not read response: %v", err)

	if resp.StatusCode > 299 {
		return fmt.Errorf("search: status %d %s: %s", resp.StatusCode, resp.Status, respBytes)

	fmt.Fprintf(w, "%s", respBytes)

	return nil


import java.util.Collections;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;

public class FhirResourceSearchGet {
  private static final String FHIR_NAME =
  // The endpoint URL for the Healthcare API. Required for HttpClient.
  private static final String API_ENDPOINT = "";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void fhirResourceSearchGet(String resourceName)
      throws IOException, 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.
    HttpClient httpClient = HttpClients.createDefault();
    String uri = String.format("%s/v1/%s", API_ENDPOINT, resourceName);
    URIBuilder uriBuilder = new URIBuilder(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");

    HttpUriRequest request =

    // Execute the request and process the results.
    HttpResponse response = httpClient.execute(request);
    HttpEntity responseEntity = response.getEntity();
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
              "Exception searching GET FHIR resources: %s\n", response.getStatusLine().toString()));
      throw new RuntimeException();
    System.out.println("FHIR resource GET search results: ");

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see
    GoogleCredentials credential =
    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)

  private static String getAccessToken() throws IOException {
    GoogleCredentials credential =

    return credential.refreshAccessToken().getTokenValue();


// Import google-auth-library for authentication.
const {GoogleAuth} = require('google-auth-library');

const searchFhirResourcesGet = async () => {
  const auth = new GoogleAuth({
    scopes: '',
  // 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';
  const url = `${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}`;

  const params = {};
  // 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'};
  const client = await auth.getClient();
  const response = await client.request({url, method: 'GET', params});
  const resources =;
  console.log(`Resources found: ${resources.length}`);
  console.log(JSON.stringify(resources, null, 2));



def search_resources_get(
    Uses the searchResources GET method to search for resources in the given FHIR store.

    before running the sample."""
    # Imports Python's built-in "os" module
    import os

    # Imports the google.auth.transport.requests transport
    from google.auth.transport import requests

    # Imports a module to allow authentication using a service account
    from google.oauth2 import service_account

    # Gets credentials from the environment.
    credentials = service_account.Credentials.from_service_account_file(
    scoped_credentials = credentials.with_scopes(
    # Creates a requests Session object with the credentials.
    session = requests.AuthorizedSession(scoped_credentials)

    # URL to the Cloud Healthcare API endpoint and version
    base_url = ""

    # 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 type
    url = "{}/projects/{}/locations/{}".format(base_url, project_id, location)

    resource_path = "{}/datasets/{}/fhirStores/{}/fhir/{}".format(
        url, dataset_id, fhir_store_id, resource_type

    response = session.get(resource_path)

    resources = response.json()

        "Using GET request, found a total of {} {} resources:".format(
            resources["total"], resource_type
    print(json.dumps(resources, indent=2))

    return resources

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.