Creating and managing FHIR resources

This page explains how to create, update, patch, view, and delete FHIR resources.

A FHIR resource can contain data about a patient, a device, an observation, and more. For a full list of FHIR resources, see the FHIR Resource Index.

Creating a FHIR resource

Before you can create FHIR resources, you need to create a FHIR store.

The following samples show how to create FHIR resources. The curl and Windows PowerShell samples show how to create a Patient resource, an Encounter resource for the patient, and then an Observation resource based on the Encounter. For more information, see projects.locations.datasets.fhirStores.fhir.create.

curl command

To create a Patient resource, make a POST request and provide the name of the parent dataset, the name of the FHIR store, a blob of data containing information about the patient, the type of resource, and an access token. The following sample shows how to send a POST request using curl to create a Patient resource.

curl -X POST \
    -H "Authorization: Bearer "$(gcloud auth print-access-token) \
    -H "Content-Type: application/fhir+json; charset=utf-8" \
    --data "{
      \"name\": [
        {
          \"use\": \"official\",
          \"family\": \"Smith\",
          \"given\": [
            \"Darcy\"
          ]
        }
      ],
      \"gender\": \"female\",
      \"birthDate\": \"1970-01-01\",
      \"resourceType\": \"Patient\"
    }" \
    "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "birthDate": "1970-01-01",
  "gender": "female",
  "id": "PATIENT_ID",
  "name": [
    {
      "family": "Smith",
      "given": [
        "Darcy"
      ],
      "use": "official"
    }
  ],
  "resourceType": "Patient"
}

After creating the Patient resource, create an Encounter resource to describe an interaction between the patient and a practitioner. The following sample shows how to send a POST request using curl to create an Encounter resource.

In the PATIENT_ID field, substitute the ID from the response returned by the server when you created the Patient.

curl -X POST \
    -H "Authorization: Bearer "$(gcloud auth print-access-token) \
    -H "Content-Type: application/fhir+json; charset=utf-8" \
    --data "{
      \"status\": \"finished\",
      \"class\": {
        \"system\": \"http://hl7.org/fhir/v3/ActCode\",
        \"code\": \"IMP\",
        \"display\": \"inpatient encounter\"
      },
      \"reason\": [
        {
          \"text\": \"The patient had an abnormal heart rate. She was concerned about this.\"
        }
      ],
      \"subject\": {
        \"reference\": \"Patient/PATIENT_ID\"
      },
      \"resourceType\": \"Encounter\"
    }" \
    "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Encounter"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "class": {
    "code": "IMP",
    "display": "inpatient encounter",
    "system": "http://hl7.org/fhir/v3/ActCode"
  },
  "id": "ENCOUNTER_ID",
  "reason": [
    {
      "text": "The patient had an abnormal heart rate. She was concerned about this."
    }
  ],
  "resourceType": "Encounter",
  "status": "finished",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  }
}

After creating the Encounter resource, create an Observation about the encounter. The Observation provides a measurement of the patient's heartbeats per minute (BPM). The following sample shows how to send a POST request using curl to create an Observation resource.

Enter a value in the BPM_VALUE field. In the PATIENT_ID field, substitute the ID from the response returned by the server when you created the Patient. In the ENCOUNTER_ID field, substitute the ID from the response returned by the server when you created the Encounter.

curl -X POST \
     -H "Authorization: Bearer "$(gcloud auth print-access-token) \
     -H "Content-Type: application/fhir+json; charset=utf-8" \
     --data "{
         \"resourceType\": \"Observation\",
         \"status\": \"final\",
         \"subject\": {
           \"reference\": \"Patient/PATIENT_ID\"
         },
         \"effectiveDateTime\": \"2018-01-01T00:00:00+00:00\",
         \"valueQuantity\": {
           \"value\": BPM_VALUE,
           \"unit\": \"bpm\"
         },
         \"context\": {
           \"reference\": \"Encounter/ENCOUNTER_ID\"
         }
     }" \
     "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "context": {
    "reference": "Encounter/ENCOUNTER_ID"
  },
  "effectiveDateTime": "2018-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "valueQuantity": {
    "unit": "bpm",
    "value": BPM_VALUE
  }
}

PowerShell

To create a Patient resource, make a POST request and provide the name of the parent dataset, the name of the FHIR store, a blob of data containing information about the patient, the type of resource, and an access token. The following sample shows how to send a POST request using Windows PowerShell to create a Patient resource.

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

$patient = '{
  "name": [
    {
      "use": "official",
      "family": "Smith",
      "given": [
        "Darcy"
      ]
    }
  ],
  "gender": "female",
  "birthDate": "1970-01-01",
  "resourceType": "Patient"
}'

Invoke-RestMethod `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/fhir+json; charset=utf-8" `
  -Body $patient `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient" | ConvertTo-Json

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "birthDate": "1970-01-01",
  "gender": "female",
  "id": "PATIENT_ID",
  "name": [
    {
      "family": "Smith",
      "given": [
        "Darcy"
      ],
      "use": "official"
    }
  ],
  "resourceType": "Patient"
}

After creating the Patient resource, create an Encounter resource to describe an interaction between the patient and a practitioner. The following sample shows how to send a POST request using Windows PowerShell to create an Encounter resource.

In the PATIENT_ID field, substitute the ID from the response returned by the server when you created the Patient.

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

$encounter = '{
  "status": "finished",
  "class": {
    "system": "http://hl7.org/fhir/v3/ActCode",
    "code": "IMP",
    "display": "inpatient encounter"
  },
  "reason": [
    {
      "text": "The patient had an abnormal heart rate. She was concerned about this."
    }
  ],
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "resourceType": "Encounter"
}'

Invoke-RestMethod `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/fhir+json; charset=utf-8" `
  -Body $encounter `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Encounter" | ConvertTo-Json

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "class": {
    "code": "IMP",
    "display": "inpatient encounter",
    "system": "http://hl7.org/fhir/v3/ActCode"
  },
  "id": "ENCOUNTER_ID",
  "reason": [
    {
      "text": "The patient had an abnormal heart rate. She was concerned about this."
    }
  ],
  "resourceType": "Encounter",
  "status": "finished",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  }
}

After creating the Encounter resource, create an Observation about the encounter. The Observation provides a measurement of the patient's heartbeats per minute (BPM).The following sample shows how to send a POST request using Windows PowerShell to create an Observation resource.

Enter a value in the BPM_VALUE field. In the PATIENT_ID field, substitute the ID from the response returned by the server when you created the Patient. In the ENCOUNTER_ID field, substitute the ID from the response returned by the server when you created the Encounter.

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

$observation = '{
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "effectiveDateTime": "2018-01-01T00:00:00+00:00",
  "valueQuantity": {
    "value": BPM_VALUE,
    "unit": "bpm"
  },
  "context": {
    "reference": "Encounter/ENCOUNTER_ID"
  }
}'

Invoke-RestMethod `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/fhir+json; charset=utf-8" `
  -Body $observation `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation" | ConvertTo-Json

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "context": {
    "reference": "Encounter/ENCOUNTER_ID"
  },
  "effectiveDateTime": "2018-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "valueQuantity": {
    "unit": "bpm",
    "value": BPM_VALUE
  }
}

Go

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"

	healthcare "google.golang.org/api/healthcare/v1beta1"
)

// createFHIRResource creates an FHIR resource.
func createFHIRResource(w io.Writer, projectID, location, datasetID, fhirStoreID, resourceType string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", err)
	}

	fhirService := healthcareService.Projects.Locations.Datasets.FhirStores.Fhir

	payload := map[string]interface{}{
		"resourceType": resourceType,
		"language":     "FR",
	}
	jsonPayload, err := json.Marshal(payload)
	if err != nil {
		return fmt.Errorf("json.Encode: %v", err)
	}

	parent := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/fhirStores/%s", projectID, location, datasetID, fhirStoreID)

	call := fhirService.Create(parent, resourceType, bytes.NewReader(jsonPayload))
	call.Header().Set("Content-Type", "application/fhir+json;charset=utf-8")
	resp, err := call.Do()
	if err != nil {
		return fmt.Errorf("Create: %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("Create: status %d %s: %s", resp.StatusCode, resp.Status, respBytes)
	}
	fmt.Fprintf(w, "%s", respBytes)

	return nil
}

Node.js

function createResource(
  token,
  projectId,
  cloudRegion,
  datasetId,
  fhirStoreId,
  resourceType
) {
  // Token retrieved in callback
  // getToken(serviceAccountJson, function(cb) {...});
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  const parentName = `${BASE_URL}/projects/${projectId}/locations/${cloudRegion}`;

  const resourcePath = `${parentName}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}`;

  const postData = {
    resourceType: resourceType,
  };

  const options = {
    url: resourcePath,
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/fhir+json; charset=utf-8',
    },
    body: postData,
    json: true,
    method: 'POST',
  };

  request(options)
    .then(resource => {
      console.log(`Created resource ${resourceType} with ID ${resource.id}.`);
    })
    .catch(err => {
      console.error(err);
    });
}

Python

def create_resource(
        service_account_json,
        base_url,
        project_id,
        cloud_region,
        dataset_id,
        fhir_store_id,
        resource_type):
    """Creates a new resource in a FHIR store."""
    url = '{}/projects/{}/locations/{}'.format(base_url, project_id,
                                               cloud_region)

    fhir_store_path = '{}/datasets/{}/fhirStores/{}/fhir/{}'.format(
        url, dataset_id, fhir_store_id, resource_type)

    # Make an authenticated API request
    session = get_session(service_account_json)

    headers = {
        'Content-Type': 'application/fhir+json;charset=utf-8'
    }

    payload = {
        'language': 'en',
        'resourceType': resource_type
    }

    try:
        response = session.post(fhir_store_path, headers=headers, json=payload)
        response.raise_for_status()

        resource = response.json()

        print(
            'Created Resource: {} with ID {}'.format(
                resource_type,
                resource['id']))

        return response
    except HttpError as err:
        print(err)
        return ""

Updating and patching a FHIR resource

The following samples show how to update a FHIR resource. For more information, see projects.locations.datasets.fhirStores.fhir.update.

curl command

To update a FHIR resource, make a PUT request and provide the name of the parent dataset, the name of the FHIR store, the type of resource, the resource ID, and an access token. The following sample shows how to send a PUT request using curl to edit an Observation resource. The Observation provides a measurement of a patient's heartbeats per minute (BPM).

curl -X PUT \
     -H "Authorization: Bearer "$(gcloud auth print-access-token) \
     -H "Content-Type: application/fhir+json; charset=utf-8" \
     --data '{
         "effectiveDateTime": "2018-01-01T00:00:00+00:00",
         "id": "OBSERVATION_ID",
         "resourceType": "Observation",
         "status": "final",
         "subject": {
             "reference": "Patient/PATIENT_ID"
         },
         "valueQuantity": {
             "unit": "bpm",
             "value": BPM_VALUE
         }
     }' \
     "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation/OBSERVATION_ID"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
    "effectiveDateTime": "2018-01-01T00:00:00+00:00",
    "id": "OBSERVATION_ID",
    "resourceType": "Observation",
    "status": "final",
    "subject": {
        "reference": "Patient/PATIENT_ID"
    },
    "valueQuantity": {
        "unit": "bpm",
        "value": BPM_VALUE
    }
}

PowerShell

To update a FHIR resource, make a PUT request and provide the name of the parent dataset, the name of the FHIR store, the type of resource, the resource ID, and an access token. The following sample shows how to send a PUT request using Windows PowerShell to edit an Observation resource. The Observation provides a measurement of a patient's heartbeats per minute (BPM).

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

$observation = '{
  "effectiveDateTime": "2018-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "valueQuantity": {
    "unit": "bpm",
    "value": BPM_VALUE
  }
}'

Invoke-RestMethod `
  -Method Put `
  -Headers $headers `
  -ContentType: "application/fhir+json; charset=utf-8" `
  -Body $observation `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation/OBSERVATION_ID" | ConvertTo-Json

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "effectiveDateTime": "2018-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "valueQuantity": {
    "unit": "bpm",
    "value": BPM_VALUE
  }
}

Go

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"

	healthcare "google.golang.org/api/healthcare/v1beta1"
)

// updateFHIRResource updates an FHIR resource to be active or not.
func updateFHIRResource(w io.Writer, projectID, location, datasetID, fhirStoreID, resourceType, fhirResourceID string, active bool) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", err)
	}

	fhirService := healthcareService.Projects.Locations.Datasets.FhirStores.Fhir

	payload := map[string]interface{}{
		"resourceType": resourceType,
		"id":           fhirResourceID,
		"active":       active,
	}
	jsonPayload, err := json.Marshal(payload)
	if err != nil {
		return fmt.Errorf("json.Encode: %v", err)
	}

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/%s/%s", projectID, location, datasetID, fhirStoreID, resourceType, fhirResourceID)

	call := fhirService.Update(name, bytes.NewReader(jsonPayload))
	call.Header().Set("Content-Type", "application/fhir+json;charset=utf-8")
	resp, err := call.Do()
	if err != nil {
		return fmt.Errorf("Update: %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("Update: status %d %s: %s", resp.StatusCode, resp.Status, respBytes)
	}
	fmt.Fprintf(w, "%s", respBytes)

	return nil
}

Node.js

function updateResource(
  token,
  projectId,
  cloudRegion,
  datasetId,
  fhirStoreId,
  resourceType,
  resourceId
) {
  // Token retrieved in callback
  // getToken(serviceAccountJson, function(cb) {...});
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  // const resourceId = 'd64a85ae-da1b-4a10-0eb8-cfaf55bdbe3f';
  const parentName = `${BASE_URL}/projects/${projectId}/locations/${cloudRegion}`;

  const resourcePath = `${parentName}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}`;

  const patientData = {
    resourceType: resourceType,
    id: resourceId,
    active: true,
  };

  const options = {
    url: resourcePath,
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/fhir+json; charset=utf-8',
    },
    body: patientData,
    json: true,
    method: 'PUT',
  };

  request(options)
    .then(() => {
      console.log(`Updated ${resourceType} with ID ${resourceId}`);
    })
    .catch(err => {
      console.error(err);
    });
}

Python

def update_resource(
        service_account_json,
        base_url,
        project_id,
        cloud_region,
        dataset_id,
        fhir_store_id,
        resource_type,
        resource_id):
    """Updates an existing resource."""
    url = '{}/projects/{}/locations/{}'.format(base_url,
                                               project_id, cloud_region)

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

    # Make an authenticated API request
    session = get_session(service_account_json)

    headers = {
        'Content-Type': 'application/fhir+json;charset=utf-8'
    }

    body = {
        'resourceType': resource_type,
        'active': True,
        'id': resource_id,
    }

    response = session.put(resource_path, headers=headers, json=body)
    response.raise_for_status()

    resource = response.json()

    print(json.dumps(resource, indent=2))

    return resource

The following samples show how to patch a FHIR resource. For more information, see projects.locations.datasets.fhirStores.fhir.patch.

curl command

To patch a FHIR resource, make a PATCH request and provide the name of the parent dataset, the name of the FHIR store, the type of resource, the resource ID, and an access token. The following sample shows how to send a PATCH request using curl to edit an Observation resource. The Observation of a patient's heartbeats per minute (BPM) is updated using the replace patch operation.

curl -X PATCH \
     -H "Authorization: Bearer "$(gcloud auth print-access-token) \
     -H "Content-Type: application/json-patch+json" \
     --data '[
       {
         "op": "replace",
         "path": "/valueQuantity/value",
         "value": BPM_VALUE
       }
     ]' \
     "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation/OBSERVATION_ID"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "effectiveDateTime": "2018-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "valueQuantity": {
    "unit": "bpm",
    "value": BPM_VALUE
  }
}

PowerShell

To patch a FHIR resource, make a PATCH request and provide the name of the parent dataset, the name of the FHIR store, the type of resource, the resource ID, and an access token. The following sample shows how to send a PATCH request using Windows PowerShell to edit an Observation resource. The Observation of a patient's heartbeats per minute (BPM) is updated using the replace patch operation.

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

$patch = '[
  {
    "op": "replace",
    "path": "/valueQuantity/value",
    "value": BPM_VALUE
  }
]'

Invoke-RestMethod `
  -Method Patch `
  -Headers $headers `
  -ContentType: "application/json-patch+json" `
  -Body $patch `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation/OBSERVATION_ID" | ConvertTo-Json

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "effectiveDateTime": "2018-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "valueQuantity": {
    "unit": "bpm",
    "value": BPM_VALUE
  }
}

Go

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"

	healthcare "google.golang.org/api/healthcare/v1beta1"
)

// patchFHIRResource patches an FHIR resource to be active or not.
func patchFHIRResource(w io.Writer, projectID, location, datasetID, fhirStoreID, resourceType, fhirResourceID string, active bool) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", err)
	}

	fhirService := healthcareService.Projects.Locations.Datasets.FhirStores.Fhir

	payload := []map[string]interface{}{
		{
			"op":    "replace",
			"path":  "/active",
			"value": active,
		},
	}
	jsonPayload, err := json.Marshal(payload)
	if err != nil {
		return fmt.Errorf("json.Encode: %v", err)
	}

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/%s/%s", projectID, location, datasetID, fhirStoreID, resourceType, fhirResourceID)

	call := fhirService.Patch(name, bytes.NewReader(jsonPayload))
	call.Header().Set("Content-Type", "application/json-patch+json")
	resp, err := call.Do()
	if err != nil {
		return fmt.Errorf("Patch: %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("Patch: status %d %s: %s", resp.StatusCode, resp.Status, respBytes)
	}
	fmt.Fprintf(w, "%s", respBytes)

	return nil
}

Node.js

function patchResource(
  token,
  projectId,
  cloudRegion,
  datasetId,
  fhirStoreId,
  resourceType,
  resourceId
) {
  // Token retrieved in callback
  // getToken(serviceAccountJson, function(cb) {...});
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  // const resourceId = 'd64a85ae-da1b-4a10-0eb8-cfaf55bdbe3f';
  const parentName = `${BASE_URL}/projects/${projectId}/locations/${cloudRegion}`;

  const resourcePath = `${parentName}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}`;

  const patchOperations = [{op: 'replace', path: '/active', value: false}];

  const options = {
    url: resourcePath,
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json-patch+json',
    },
    body: patchOperations,
    json: true,
    method: 'PATCH',
  };

  request(options)
    .then(() => {
      console.log(`Patched ${resourceType} with ID ${resourceId}`);
    })
    .catch(err => {
      console.log('ERROR:', err.message);
    });
}

Python

def patch_resource(
        service_account_json,
        base_url,
        project_id,
        cloud_region,
        dataset_id,
        fhir_store_id,
        resource_type,
        resource_id):
    """Updates part of an existing resource.."""
    url = '{}/projects/{}/locations/{}'.format(base_url,
                                               project_id, cloud_region)

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

    # Make an authenticated API request
    session = get_session(service_account_json)

    headers = {
        'Content-Type': 'application/json-patch+json'
    }

    body = json.dumps([
        {
            'op': 'replace',
            'path': '/active',
            'value': False
        }
    ])

    response = session.patch(resource_path, headers=headers, data=body)
    response.raise_for_status()

    resource = response.json()

    print(json.dumps(resource, indent=2))

    return resource

Getting a FHIR resource

The following samples show how to get the contents of a FHIR resource. For more information, see projects.locations.datasets.fhirStores.fhir.read.

curl command

To get the contents of a FHIR resource, make a GET request and provide the name of the parent dataset, the name of the FHIR store, the resource type and ID, and an access token. The following sample shows a GET request with curl on the Observation created in the previous section.

curl -X GET \
     -H "Authorization: Bearer "$(gcloud auth print-access-token) \
     "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation/RESOURCE_ID"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "context": {
    "reference": "Encounter/ENCOUNTER_ID"
  },
  "effectiveDateTime": "2018-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "valueQuantity": {
    "unit": "bpm",
    "value": BPM_VALUE
  }
}

PowerShell

To get the contents of a FHIR resource, make a GET request and provide the name of the parent dataset, the name of the FHIR store, the resource type and ID, and an access token. The following sample shows a GET request with Windows PowerShell on the Observation created in the previous section.

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-RestMethod `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation/RESOURCE_ID" | ConvertTo-Json

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "context": {
    "reference": "Encounter/ENCOUNTER_ID"
  },
  "effectiveDateTime": "2018-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "valueQuantity": {
    "unit": "bpm",
    "value": BPM_VALUE
  }
}

Go

import (
	"context"
	"fmt"
	"io"
	"io/ioutil"

	healthcare "google.golang.org/api/healthcare/v1beta1"
)

// getFHIRResource gets an FHIR resource.
func getFHIRResource(w io.Writer, projectID, location, datasetID, fhirStoreID, resourceType, fhirResourceID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", err)
	}

	fhirService := healthcareService.Projects.Locations.Datasets.FhirStores.Fhir

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/%s/%s", projectID, location, datasetID, fhirStoreID, resourceType, fhirResourceID)

	call := fhirService.Read(name)
	call.Header().Set("Content-Type", "application/fhir+json;charset=utf-8")
	resp, err := call.Do()
	if err != nil {
		return fmt.Errorf("Read: %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("Read: status %d %s: %s", resp.StatusCode, resp.Status, respBytes)
	}
	fmt.Fprintf(w, "%s", respBytes)

	return nil
}

Node.js

function getResource(
  token,
  projectId,
  cloudRegion,
  datasetId,
  fhirStoreId,
  resourceType,
  resourceId
) {
  // Token retrieved in callback
  // getToken(serviceAccountJson, function(cb) {...});
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  // const resourceId = 'd64a85ae-da1b-4a10-0eb8-cfaf55bdbe3f';
  const parentName = `${BASE_URL}/projects/${projectId}/locations/${cloudRegion}`;

  const resourcePath = `${parentName}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}`;

  const options = {
    url: resourcePath,
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/fhir+json; charset=utf-8',
    },
    json: true,
  };

  request(options)
    .then(results => {
      console.log(
        `Got ${resourceType} resource:\n${JSON.stringify(results, null, 2)}`
      );
    })
    .catch(err => {
      console.error(err);
    });
}

Python

def get_resource(
        service_account_json,
        base_url,
        project_id,
        cloud_region,
        dataset_id,
        fhir_store_id,
        resource_type,
        resource_id):
    """Gets a FHIR resource."""
    url = '{}/projects/{}/locations/{}'.format(base_url,
                                               project_id, cloud_region)

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

    # Make an authenticated API request
    session = get_session(service_account_json)

    headers = {
        'Content-Type': 'application/fhir+json;charset=utf-8'
    }

    response = session.get(resource_path, headers=headers)
    response.raise_for_status()

    resource = response.json()

    print(json.dumps(resource, indent=2))

    return resource

Getting all patient compartment resources

The following samples show how to get all resources associated with a particular patient compartment. For more information, see projects.locations.datasets.fhirStores.fhir.Patient-everything.

curl command

To get the resources in a patient compartment, make a GET request and provide the name of the parent dataset, the name of the FHIR store, the patient's ID, and an access token. The following sample shows a GET request with curl.

curl -X GET \
     -H "Authorization: Bearer "$(gcloud auth print-access-token) \
     "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/PATIENT_ID/\$everything"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "entry": [
    {
      "resource": {
        "birthDate": "1970-01-01",
        "gender": "female",
        "id": "PATIENT_ID",
        "name": [
          {
            "family": "Smith",
            "given": [
              "Darcy"
            ],
            "use": "official"
          }
        ],
        "resourceType": "Patient"
      }
    },
    {
      "resource": {
        "class": {
          "code": "IMP",
          "display": "inpatient encounter",
          "system": "http://hl7.org/fhir/v3/ActCode"
        },
        "id": "ENCOUNTER_ID",
        "reason": [
          {
            "text": "The patient had an abnormal heart rate. She was concerned about this."
          }
        ],
        "resourceType": "Encounter",
        "status": "finished",
        "subject": {
          "reference": "Patient/PATIENT_ID"
        }
      }
    },
    {
      "resource": {
        "context": {
          "reference": "Encounter/ENCOUNTER_ID"
        },
        "effectiveDateTime": "2018-01-01T00:00:00+00:00",
        "id": "OBSERVATION_ID",
        "resourceType": "Observation",
        "status": "final",
        "subject": {
          "reference": "Patient/PATIENT_ID"
        },
        "valueQuantity": {
          "unit": "bpm",
          "value": BPM_VALUE
        }
      }
    }
  ],
  "resourceType": "Bundle",
  "type": "searchset"
}

PowerShell

To get the resources in a patient compartment, make a GET request and provide the name of the parent dataset, the name of the FHIR store, the patient's ID, and an access token. The following sample shows a GET request with Windows PowerShell.

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-RestMethod `
  -Method Get `
  -Headers $headers `
  -Uri 'https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/RESOURCE_ID/$everything' | ConvertTo-Json

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "entry": [
    {
      "resource": {
        "birthDate": "1970-01-01",
        "gender": "female",
        "id": "PATIENT_ID",
        "name": [
          {
            "family": "Smith",
            "given": [
              "Darcy"
            ],
            "use": "official"
          }
        ],
        "resourceType": "Patient"
      }
    },
    {
      "resource": {
        "class": {
          "code": "IMP",
          "display": "inpatient encounter",
          "system": "http://hl7.org/fhir/v3/ActCode"
        },
        "id": "ENCOUNTER_ID",
        "reason": [
          {
            "text": "The patient had an abnormal heart rate. She was concerned about this."
          }
        ],
        "resourceType": "Encounter",
        "status": "finished",
        "subject": {
          "reference": "Patient/PATIENT_ID"
        }
      }
    },
    {
      "resource": {
        "context": {
          "reference": "Encounter/ENCOUNTER_ID"
        },
        "effectiveDateTime": "2018-01-01T00:00:00+00:00",
        "id": "OBSERVATION_ID",
        "resourceType": "Observation",
        "status": "final",
        "subject": {
          "reference": "Patient/PATIENT_ID"
        },
        "valueQuantity": {
          "unit": "bpm",
          "value": BPM_VALUE
        }
      }
    }
  ],
  "resourceType": "Bundle",
  "type": "searchset"
}

Go

import (
	"context"
	"fmt"
	"io"
	"io/ioutil"

	healthcare "google.golang.org/api/healthcare/v1beta1"
)

// fhirGetPatientEverything gets all resources associated with a particular
// patient compartment.
func fhirGetPatientEverything(w io.Writer, projectID, location, datasetID, fhirStoreID, fhirResourceID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", err)
	}
	fhirService := healthcareService.Projects.Locations.Datasets.FhirStores.Fhir
	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/Patient/%s", projectID, location, datasetID, fhirStoreID, fhirResourceID)

	resp, err := fhirService.PatientEverything(name).Do()
	if err != nil {
		return fmt.Errorf("PatientEverything: %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("PatientEverything: status %d %s: %s", resp.StatusCode, resp.Status, respBytes)
	}
	fmt.Fprintf(w, "%s", respBytes)

	return nil
}

Node.js

function getPatientEverything(
  token,
  projectId,
  cloudRegion,
  datasetId,
  fhirStoreId,
  resourceId
) {
  // Token retrieved in callback
  // getToken(serviceAccountJson, function(cb) {...});
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceId = 'd64a85ae-da1b-4a10-0eb8-cfaf55bdbe3f';
  const parentName = `${BASE_URL}/projects/${projectId}/locations/${cloudRegion}`;

  const fhirStorePath = `${parentName}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/Patient/${resourceId}/$everything`;

  const options = {
    url: fhirStorePath,
    headers: {
      authorization: `Bearer ${token}`,
    },
    json: true,
  };

  request(options)
    .then(results => {
      console.log(`Got all resources in patient ${resourceId} compartment:`);
      console.log(results);
    })
    .catch(err => {
      console.error(err);
    });
}

Python

def get_patient_everything(
        service_account_json,
        base_url,
        project_id,
        cloud_region,
        dataset_id,
        fhir_store_id,
        resource_id):
    """Gets all the resources in the patient compartment."""
    url = '{}/projects/{}/locations/{}'.format(base_url,
                                               project_id, cloud_region)

    resource_path = '{}/datasets/{}/fhirStores/{}/fhir/{}/{}'.format(
        url, dataset_id, fhir_store_id, 'Patient', resource_id)
    resource_path += '/$everything'

    # Make an authenticated API request
    session = get_session(service_account_json)

    headers = {
        'Content-Type': 'application/fhir+json;charset=utf-8'
    }

    response = session.get(resource_path, headers=headers)
    response.raise_for_status()

    resource = response.json()

    print(json.dumps(resource, indent=2))

    return resource

Searching for FHIR resources

The projects.locations.datasets.fhirStores.fhir.search method allows searching for resources in a given FHIR store. It can be called in different ways using POST or GET requests.

Using the search method via POST

The following samples show how to search for resources in a given FHIR store using the projects.locations.datasets.fhirStores.fhir.search method via POST.

curl command

To search for resources in a FHIR store, make a POST request and provide 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 are searching for, and an access token. The following sample shows a POST request using curl to search for all patients with the last name "Smith."

curl -X POST \
    --data "" \
    -H "Authorization: Bearer "$(gcloud auth print-access-token) \
    -H "Content-Type: application/fhir+json; charset=utf-8" \
    "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/_search?family:exact=Smith"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format. In this example, it returns a single patient and the patient's data:

200 OK
{
  "entry": [
    {
      "fullUrl": "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/PATIENT_ID",
      "resource": {
        "birthDate": "1970-01-01",
        "gender": "female",
        "id": "PATIENT_ID",
        "meta": {
          "lastUpdated": "2018-01-01T00:00:00+00:00",
          "versionId": "VERSION_ID"
        },
        "name": [
          {
            "family": "Smith",
            "given": [
              "Darcy"
            ]
          }
        ],
        "resourceType": "Patient"
      },
      "search": {
        "mode": "match"
      }
    }
  ],
  "link": [
    {
      "url": "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/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 a POST request and provide 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 are searching for, and an access token. The following sample shows a POST request using Windows PowerShell to search for all patients with the last name "Smith."

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-RestMethod `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/fhir+json; charset=utf-8" `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/_search?family:exact=Smith" | ConvertTo-Json

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "entry": [
    {
      "fullUrl": "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/PATIENT_ID",
      "resource": {
        "birthDate": "1970-01-01",
        "gender": "female",
        "id": "PATIENT_ID",
        "meta": {
          "lastUpdated": "2018-01-01T00:00:00+00:00",
          "versionId": "VERSION_ID"
        },
        "name": [
          {
            "family": "Smith",
            "given": [
              "Darcy"
            ]
          }
        ],
        "resourceType": "Patient"
      },
      "search": {
        "mode": "match"
      }
    }
  ],
  "link": [
    {
      "url": "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/?family%3Aexact=Smith"
    }
  ],
  "resourceType": "Bundle",
  "total": 1,
  "type": "searchset"
}

Node.js

function searchResourcesPost(
  token,
  projectId,
  cloudRegion,
  datasetId,
  fhirStoreId,
  resourceType
) {
  // Token retrieved in callback
  // getToken(serviceAccountJson, function(cb) {...});
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  const parentName = `${BASE_URL}/projects/${projectId}/locations/${cloudRegion}`;

  const resourcesPath = `${parentName}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/_search`;

  const options = {
    url: resourcesPath,
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/fhir+json; charset=utf-8',
    },
    json: true,
    method: 'POST',
  };

  request(options)
    .then(results => {
      console.log(JSON.stringify(results, null, 2));
    })
    .catch(err => {
      console.error(err);
    });
}

Python

def search_resources_post(
        service_account_json,
        base_url,
        project_id,
        cloud_region,
        dataset_id,
        fhir_store_id,
        resource_type):
    """Searches resources in the given FHIR store using the
    _search POST method."""
    url = '{}/projects/{}/locations/{}'.format(base_url,
                                               project_id, cloud_region)

    resource_path = '{}/datasets/{}/fhirStores/{}/resources/{}/_search'.format(
        url, dataset_id, fhir_store_id, resource_type)

    # Make an authenticated API request
    session = get_session(service_account_json)

    headers = {
        'Content-Type': 'application/fhir+json;charset=utf-8'
    }

    response = session.post(resource_path, headers=headers)
    response.raise_for_status()

    resources = response.json()

    print(json.dumps(resources, indent=2))

    return resources

Using the search method via GET

The following samples show how to search for resources in a given FHIR store using the projects.locations.datasets.fhirStores.fhir.search method via GET.

curl command

To search for resources in a FHIR store, make a GET request and provide 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 are searching for, and an access token. The following sample shows a GET request using curl to search for all patients with the last name "Smith."

curl -X GET \
     -H "Authorization: Bearer "$(gcloud auth print-access-token) \
     "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient?family:exact=Smith"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format. In this example, it returns a single patient and the patient's data:

200 OK
{
  "entry": [
    {
      "fullUrl": "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/PATIENT_ID",
      "resource": {
        "birthDate": "1970-01-01",
        "gender": "female",
        "id": "PATIENT_ID",
        "meta": {
          "lastUpdated": "2018-01-01T00:00:00+00:00",
          "versionId": "VERSION_ID"
        },
        "name": [
          {
            "family": "Smith",
            "given": [
              "Darcy"
            ]
          }
        ],
        "resourceType": "Patient"
      },
      "search": {
        "mode": "match"
      }
    }
  ],
  "link": [
    {
      "url": "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/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 a GET request and provide 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 are searching for, and an access token. The following sample shows a GET request using Windows PowerShell to search for all patients with the last name "Smith."

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-RestMethod `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/RESOURCE_TYPE?family:exact=Smith" | ConvertTo-Json

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "entry": [
    {
      "fullUrl": "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/PATIENT_ID",
      "resource": {
        "birthDate": "1970-01-01",
        "gender": "female",
        "id": "PATIENT_ID",
        "meta": {
          "lastUpdated": "2018-01-01T00:00:00+00:00",
          "versionId": "VERSION_ID"
        },
        "name": [
          {
            "family": "Smith",
            "given": [
              "Darcy"
            ]
          }
        ],
        "resourceType": "Patient"
      },
      "search": {
        "mode": "match"
      }
    }
  ],
  "link": [
    {
      "url": "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/?family%3Aexact=Smith"
    }
  ],
  "resourceType": "Bundle",
  "total": 1,
  "type": "searchset"
}

Node.js

function searchResourcesGet(
  token,
  projectId,
  cloudRegion,
  datasetId,
  fhirStoreId,
  resourceType
) {
  // Token retrieved in callback
  // getToken(serviceAccountJson, function(cb) {...});
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  const parentName = `${BASE_URL}/projects/${projectId}/locations/${cloudRegion}`;

  const resourcesPath = `${parentName}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}`;

  const options = {
    url: resourcesPath,
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/fhir+json; charset=utf-8',
    },
    json: true,
  };

  request(options)
    .then(results => {
      console.log(JSON.stringify(results, null, 2));
    })
    .catch(err => {
      console.error(err);
    });
}

Python

def search_resources_get(
        service_account_json,
        base_url,
        project_id,
        cloud_region,
        dataset_id,
        fhir_store_id,
        resource_type):
    """Searches resources in the given FHIR store using the
    searchResources GET method."""
    url = '{}/projects/{}/locations/{}'.format(base_url,
                                               project_id, cloud_region)

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

    # Make an authenticated API request
    session = get_session(service_account_json)

    headers = {
        'Content-Type': 'application/fhir+json;charset=utf-8'
    }

    response = session.get(resource_path, headers=headers)
    response.raise_for_status()

    resources = response.json()

    print(json.dumps(resources, indent=2))

    return resources

Listing FHIR resource versions

The following samples show how to list all historical versions of a FHIR resource. For more information, see projects.locations.datasets.fhirStores.fhir.history.

The samples use the resources created in Creating a FHIR resource and show how to list the versions of an Observation resource.

curl command

The following sample shows how to list all versions of an Observation resource. The Observation has been updated one time after its original creation to change the patient's heartbeats per minute (BPM).

To list all versions of a FHIR resource, including the current version and any deleted versions, make a GET request and provide the name of the parent dataset, the name of the FHIR store, the resource type and ID, and an access token. The following sample shows a GET request using curl.

curl -X GET \
     -H "Authorization: Bearer "$(gcloud auth print-access-token) \
     "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/RESOURCE_TYPE/RESOURCE_ID/_history"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format. In this example, it returns two versions of the Observation. In the first version, the patient's BPM was 75. In the second version, the patient's BPM was 85.

200 OK
{
  "entry": [
    {
      "resource": {
        "effectiveDateTime": "2018-01-01T00:00:00+00:00",
        "id": "OBSERVATION_ID",
        "meta": {
          "lastUpdated": "2018-01-02T00:00:00+00:00",
          "versionId": "MTU0MTE5MDk5Mzk2ODcyODAwMA"
        },
        "resourceType": "Observation",
        "status": "final",
        "subject": {
          "reference": "Patient/PATIENT_ID"
        },
        "valueQuantity": {
          "unit": "bpm",
          "value": 85
        }
      }
    },
    {
      "resource": {
        "context": {
          "reference": "Encounter/ENCOUNTER_ID"
        },
        "effectiveDateTime": "2018-01-01T00:00:00+00:00",
        "id": "OBSERVATION_ID",
        "meta": {
          "lastUpdated": "2018-01-01T00:00:00+00:00",
          "versionId": "MTU0MTE5MDg4MTY0MzQ3MjAwMA"
        },
        "resourceType": "Observation",
        "status": "final",
        "subject": {
          "reference": "Patient/PATIENT_ID"
        },
        "valueQuantity": {
          "unit": "bpm",
          "value": 75
        }
      }
    }
  ],
  "resourceType": "Bundle",
  "type": "history"
}

PowerShell

The following sample shows how to list all versions of an Observation resource. The Observation has been updated one time after its original creation to change the patient's heartbeats per minute (BPM).

To list all versions of a FHIR resource, including the current version and any deleted versions, make a GET request and provide the name of the parent dataset, the name of the FHIR store, the resource type and ID, and an access token. The following sample shows a GET request using Windows PowerShell.

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-RestMethod `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/RESOURCE_TYPE/RESOURCE_ID/_history" | Select-Object -Expand Content

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format. In this example, it returns two versions of the Observation. In the first version, the patient's BPM was 75. In the second version, the patient's BPM was 85.

200 OK
{
  "entry": [
    {
      "resource": {
        "effectiveDateTime": "2018-01-01T00:00:00+00:00",
        "id": "OBSERVATION_ID",
        "meta": {
          "lastUpdated": "2018-01-02T00:00:00+00:00",
          "versionId": "MTU0MTE5MDk5Mzk2ODcyODAwMA"
        },
        "resourceType": "Observation",
        "status": "final",
        "subject": {
          "reference": "Patient/PATIENT_ID"
        },
        "valueQuantity": {
          "unit": "bpm",
          "value": 85
        }
      }
    },
    {
      "resource": {
        "context": {
          "reference": "Encounter/ENCOUNTER_ID"
        },
        "effectiveDateTime": "2018-01-01T00:00:00+00:00",
        "id": "OBSERVATION_ID",
        "meta": {
          "lastUpdated": "2018-01-01T00:00:00+00:00",
          "versionId": "MTU0MTE5MDg4MTY0MzQ3MjAwMA"
        },
        "resourceType": "Observation",
        "status": "final",
        "subject": {
          "reference": "Patient/PATIENT_ID"
        },
        "valueQuantity": {
          "unit": "bpm",
          "value": 75
        }
      }
    }
  ],
  "resourceType": "Bundle",
  "type": "history"
}

Retrieving a FHIR resource version

The following samples show how to retrieve a specific version of a resource. For more information, see projects.locations.datasets.fhirStores.fhir.vread.

The version IDs for the Observation resource from Listing FHIR resource versions are highlighted below:

{
  "entry": [
    {
      "resource": {
        "effectiveDateTime": "2018-01-01T00:00:00+00:00",
        "id": "OBSERVATION_ID",
        "meta": {
          "lastUpdated": "2018-01-02T00:00:00+00:00",
          "versionId": "MTU0MTE5MDk5Mzk2ODcyODAwMA"
        },
...
    {
      "resource": {
        "context": {
          "reference": "Encounter/ENCOUNTER_ID"
        },
        "effectiveDateTime": "2018-01-01T00:00:00+00:00",
        "id": "OBSERVATION_ID",
        "meta": {
          "lastUpdated": "2018-01-01T00:00:00+00:00",
          "versionId": "MTU0MTE5MDg4MTY0MzQ3MjAwMA"
        },
...
}

The following samples use the resources created in Creating a FHIR resource and show how to view an Observation resource.

curl command

To get a specific version of a FHIR resource, make a GET request and provide the name of the parent dataset, the name of the FHIR store, the resource type and ID, the resource version, and an access token. The following sample shows a GET request using curl.

curl -X GET \
     -H "Authorization: Bearer "$(gcloud auth print-access-token) \
     "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/RESOURCE_TYPE/RESOURCE_ID/_history/RESOURCE_VERSION"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format. In this example, the first version of the Observation, where the patient's BPM was 75, is returned.

200 OK
{
  "context": {
    "reference": "Encounter/ENCOUNTER_ID"
  },
  "effectiveDateTime": "2018-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "meta": {
    "lastUpdated": "2018-01-01T00:00:00+00:00",
    "versionId": "MTU0MTE5MDg4MTY0MzQ3MjAwMA"
  },
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "valueQuantity": {
    "unit": "bpm",
    "value": 75
  }
}

PowerShell

To get a specific version of a FHIR resource, make a GET request and provide the name of the parent dataset, the name of the FHIR store, the resource type and ID, the resource version, and an access token. The following sample shows a GET request using curl.

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-RestMethod `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/RESOURCE_TYPE/RESOURCE_ID/RESOURCE_VERSION/_history" | Select-Object -Expand Content

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format. In this example, the first version of the Observation, where the patient's BPM was 75, is returned.

200 OK
{
  "context": {
    "reference": "Encounter/ENCOUNTER_ID"
  },
  "effectiveDateTime": "2018-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "meta": {
    "lastUpdated": "2018-01-01T00:00:00+00:00",
    "versionId": "MTU0MTE5MDg4MTY0MzQ3MjAwMA"
  },
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "valueQuantity": {
    "unit": "bpm",
    "value": 75
  }
}

Go

import (
	"context"
	"fmt"
	"io"
	"io/ioutil"

	healthcare "google.golang.org/api/healthcare/v1beta1"
)

// listFHIRResourceHistory lists an FHIR resource's history.
func listFHIRResourceHistory(w io.Writer, projectID, location, datasetID, fhirStoreID, resourceType, fhirResourceID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", err)
	}

	fhirService := healthcareService.Projects.Locations.Datasets.FhirStores.Fhir

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/%s/%s", projectID, location, datasetID, fhirStoreID, resourceType, fhirResourceID)

	resp, err := fhirService.History(name).Do()
	if err != nil {
		return fmt.Errorf("History: %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("History: status %d %s: %s", resp.StatusCode, resp.Status, respBytes)
	}
	fmt.Fprintf(w, "%s", respBytes)

	return nil
}

Deleting a FHIR resource

The following samples show how to delete a FHIR resource. For more information, see projects.locations.datasets.fhirStores.fhir.delete.

curl command

To delete a FHIR resource, make a DELETE request and provide the name of the parent dataset, the name of the FHIR store, and an access token. The following sample shows a DELETE request using curl.

curl -X DELETE \
     -H "Authorization: Bearer "$(gcloud auth print-access-token) \
     "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/RESOURCE_TYPE/RESOURCE_ID"

If the request is successful, the server returns a 200 OK HTTP status code and the empty response body in JSON format:

200 OK
{}

PowerShell

To delete a FHIR resource, make a DELETE request and provide the name of the parent dataset, the name of the FHIR store, the resource type and ID, and an access token. The following sample shows a DELETE request using Windows PowerShell.

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Delete `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/RESOURCE_TYPE/RESOURCE_ID" | Select-Object -Expand Content

If the request is successful, the server returns a 200 OK HTTP status code and the empty response body in JSON format:

200 OK
{}

Go

import (
	"context"
	"fmt"
	"io"

	healthcare "google.golang.org/api/healthcare/v1beta1"
)

// deleteFHIRResource deletes an FHIR resource.
func deleteFHIRResource(w io.Writer, projectID, location, datasetID, fhirStoreID, resourceType, fhirResourceID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", err)
	}

	fhirService := healthcareService.Projects.Locations.Datasets.FhirStores.Fhir

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/%s/%s", projectID, location, datasetID, fhirStoreID, resourceType, fhirResourceID)

	if _, err := fhirService.Delete(name).Do(); err != nil {
		return fmt.Errorf("Delete: %v", err)
	}

	fmt.Fprintf(w, "Deleted %q", name)

	return nil
}

Node.js

function deleteResource(
  token,
  projectId,
  cloudRegion,
  datasetId,
  fhirStoreId,
  resourceType,
  resourceId
) {
  // Token retrieved in callback
  // getToken(serviceAccountJson, function(cb) {...});
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  // const resourceId = 'd64a85ae-da1b-4a10-0eb8-cfaf55bdbe3f';
  const parentName = `${BASE_URL}/projects/${projectId}/locations/${cloudRegion}`;

  const resourcePath = `${parentName}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}`;

  const options = {
    url: resourcePath,
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/fhir+json; charset=utf-8',
    },
    json: true,
    method: 'DELETE',
  };

  request(options)
    .then(() => {
      console.log(`Deleted ${resourceType} with ID ${resourceId}.`);
    })
    .catch(err => {
      console.error(err);
    });
}

Python

def delete_resource(
        service_account_json,
        base_url,
        project_id,
        cloud_region,
        dataset_id,
        fhir_store_id,
        resource_type,
        resource_id):
    """Deletes a FHIR resource or returns NOT_FOUND if it doesn't exist."""
    url = '{}/projects/{}/locations/{}'.format(base_url,
                                               project_id, cloud_region)

    resource_path = '{}/datasets/{}/fhirStores/{}/resources/{}/{}'.format(
        url, dataset_id, fhir_store_id, resource_type, resource_id)

    # Make an authenticated API request
    session = get_session(service_account_json)

    headers = {
        'Content-Type': 'application/fhir+json;charset=utf-8'
    }

    try:
        response = session.delete(resource_path, headers=headers)
        if response.status_code != 404:  # Don't consider missing to be error
            response.raise_for_status()
        print(response)
        print('Deleted Resource: {}'.format(resource_id))
        return response
    except HttpError:
        print('Error, Resource not deleted')
        return ""

Deleting historical versions of a FHIR resource

The following samples show how to delete all historical versions of a FHIR resource. For more information, see projects.locations.datasets.fhirStores.fhir.Resource-purge.

Note that calling the projects.locations.datasets.fhirStores.fhir.Resource-purge method is limited to users (callers) with the roles/healthcare.fhirStoreAdmin role; users with the roles/healthcare.fhirResourceEditor role cannot call the method. To delete historical versions of a FHIR resource, either:

The samples use the resources created in Creating a FHIR resource and show how to delete the historical versions of an Observation resource.

curl command

To delete all historical versions of a FHIR resource, make a DELETE request and provide the name of the parent dataset, the name of the FHIR store, the resource type and ID, and an access token. The following sample shows a DELETE request using curl.

curl -X DELETE \
     -H "Authorization: Bearer "$(gcloud auth print-access-token) \
     -H "Content-Type: application/fhir+json; charset=utf-8" \
     "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/RESOURCE_TYPE/RESOURCE_ID/$purge"

If the request is successful, the server returns a 200 OK HTTP status code and the empty response body in JSON format:

200 OK
{}

PowerShell

To delete all historical versions of a FHIR resource, make a DELETE request and provide the name of the parent dataset, the name of the FHIR store, the resource type and ID, and an access token. The following sample shows a DELETE request using Windows PowerShell.

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-RestMethod `
  -Method Delete `
  -Headers $headers `
  -ContentType: "application/fhir+json; charset=utf-8" `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/RESOURCE_TYPE/RESOURCE_ID/$purge" | ConvertTo-Json

If the request is successful, the server returns a 200 OK HTTP status code and the empty response body in JSON format:

200 OK
{}

Go

import (
	"context"
	"fmt"
	"io"

	healthcare "google.golang.org/api/healthcare/v1beta1"
)

// purgeFHIRResource purges an FHIR resources.
func purgeFHIRResource(w io.Writer, projectID, location, datasetID, fhirStoreID, resourceType, fhirResourceID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", err)
	}

	fhirService := healthcareService.Projects.Locations.Datasets.FhirStores.Fhir

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/%s/%s", projectID, location, datasetID, fhirStoreID, resourceType, fhirResourceID)

	if _, err := fhirService.ResourcePurge(name).Do(); err != nil {
		return fmt.Errorf("ResourcePurge: %v", err)
	}

	fmt.Fprintf(w, "Resource Purged: %q", name)

	return nil
}

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Healthcare API