Search FHIR resources

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 (


// searchFhirResources uses a POST request to search for FHIR resources in a given FHIR store.
func searchFHIRResourcesPost(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 POST request to search for FHIR resources does
	// not pass any data in its body.
	req, err := http.NewRequest(http.MethodPost, name, nil)

	// 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()

	if err != nil {
		return fmt.Errorf("NewRequest: %v", err)

	// Sets required application/fhir+json header on the request.
	req.Header.Add("Content-Type", "application/fhir+json")

	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 FhirResourceSearchPost {
  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 fhirResourceSearchPost(String resourceName)
      throws IOException, 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.
    HttpClient httpClient = HttpClients.createDefault();
    String uri = String.format("%s/v1/%s/_search", 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");

    // Set a body otherwise HttpClient complains there is no Content-Length set.
    StringEntity requestEntity = new StringEntity("");

    HttpUriRequest request =
            .addHeader("Content-Type", "application/fhir+json")
            .addHeader("Accept-Charset", "utf-8")
            .addHeader("Accept", "application/fhir+json; charset=utf-8")

    // 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 POST FHIR resources: %s\n",
      throw new RuntimeException();
    System.out.println("FHIR resource POST 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 searchFhirResourcesPost = async () => {
  const auth = new GoogleAuth({
    scopes: '',
    // 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';
  const url = `${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/_search`;

  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: 'POST', params});
  const resources =;
  console.log(`Resources found: ${resources.length}`);
  console.log(JSON.stringify(resources, null, 2));



def search_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.

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

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

    resource_path = "{}/Patient/_search?family:exact=Smith".format(fhir_store_path)

    # Sets required application/fhir+json header on the request
    headers = {"Content-Type": "application/fhir+json;charset=utf-8"}

    response =, headers=headers)

    resources = response.json()
        "Using POST request, found a total of {} Patient resources:".format(

    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.