创建和管理 FHIR 资源

本页面介绍了如何创建、更新、修补、查看和删除 FHIR 资源。

FHIR 资源可以包含有关患者、设备、观察结果之类的数据。如需查看 FHIR 资源的完整列表,请参阅 FHIR 资源索引(DSTU2STU3R4)。

创建 FHIR 资源

您必须先创建一个 FHIR 存储区,然后才能创建 FHIR 资源。

curl、Windows PowerShell 和 Python 示例展示了如何创建以下 FHIR 资源:

  1. 患者(DSTU2STU3R4)资源
  2. 患者的相遇(DSTU2STU3R4)资源
  3. 相遇的观察结果(DSTU2STU3R4)资源

所有其他语言的示例展示了如何创建通用 FHIR 资源。

如需了解详情,请参阅 projects.locations.datasets.fhirStores.fhir.create

curl

要创建“患者”资源,请发出 POST 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 一个包含患者信息的数据 blob
  • 资源类型
  • 访问令牌

以下示例展示了如何使用 curl 来发送创建“患者”资源的 POST 请求。

curl -X POST \
    -H "Authorization: Bearer $(gcloud auth application-default 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/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient"

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "birthDate": "1970-01-01",
  "gender": "female",
  "id": "PATIENT_ID",
  "meta": {
    "lastUpdated": "2020-01-01T00:00:00+00:00",
    "versionId": "VERSION_ID"
  },
  "name": [
    {
      "family": "Smith",
      "given": [
        "Darcy"
      ],
      "use": "official"
    }
  ],
  "resourceType": "Patient"
}

PowerShell

要创建“患者”资源,请发出 POST 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 一个包含患者信息的数据 blob
  • 资源类型
  • 访问令牌

以下示例展示了如何使用 Windows PowerShell 来发送创建患者资源的 POST 请求。

$cred = gcloud auth application-default 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/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient" | ConvertTo-Json

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "birthDate": "1970-01-01",
  "gender": "female",
  "id": "PATIENT_ID",
  "meta": {
    "lastUpdated": "2020-01-01T00:00:00+00:00",
    "versionId": "VERSION_ID"
  },
  "name": [
    {
      "family": "Smith",
      "given": [
        "Darcy"
      ],
      "use": "official"
    }
  ],
  "resourceType": "Patient"
}

Go

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

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

// 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
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.net.URISyntaxException;
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 FhirResourceCreate {
  private static final String FHIR_NAME = "projects/%s/locations/%s/datasets/%s/fhirStores/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void fhirResourceCreate(String fhirStoreName, String resourceType)
      throws IOException, URISyntaxException {
    // String fhirStoreName =
    //    String.format(
    //        FHIR_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-fhir-id");
    // String resourceType = "Patient";

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();
    HttpClient httpClient = HttpClients.createDefault();
    String uri = String.format("%sv1/%s/fhir/%s", client.getRootUrl(), fhirStoreName, resourceType);
    URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());
    StringEntity requestEntity =
        new StringEntity("{\"resourceType\": \"" + resourceType + "\", \"language\": \"en\"}");

    HttpUriRequest request =
        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.
    HttpResponse response = httpClient.execute(request);
    HttpEntity responseEntity = response.getEntity();
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
      System.err.print(
          String.format(
              "Exception creating FHIR resource: %s\n", response.getStatusLine().toString()));
      responseEntity.writeTo(System.err);
      throw new RuntimeException();
    }
    System.out.print("FHIR resource created: ");
    responseEntity.writeTo(System.out);
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // 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)
        .setApplicationName("your-application-name")
        .build();
  }

  private static String getAccessToken() throws IOException {
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    return credential.refreshAccessToken().getTokenValue();
  }
}

Node.js

const {google} = require('googleapis');
const healthcare = google.healthcare('v1');

async function createFhirResource() {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });

  // Replace the following body with the data for the resource you want to
  // create.
  const body = {
      "name": [{"use": "official", "family": "Smith", "given": ["Darcy"]}],
      "gender": "female",
      "birthDate": "1970-01-01",
      "resourceType": "Patient",
  };

  google.options({auth, 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 parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}`;

  const request = {parent, type: resourceType, requestBody: body};
  const resource = await healthcare.projects.locations.datasets.fhirStores.fhir.create(
    request
  );
  console.log(`Created FHIR resource with ID ${resource.data.id}`);
  console.log(resource.data);
}

createFhirResource();

Python

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

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

    # Make an authenticated API request
    session = get_session()

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

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

    response = session.post(fhir_store_path, headers=headers, json=body)
    response.raise_for_status()

    resource = response.json()

    print("Created Patient resource with ID {}".format(resource["id"]))

    return response

curl

创建“患者”资源后,请创建“相遇”资源来说明患者与医生之间的交互。以下示例展示了如何使用 curl 来发送创建“相遇”资源的 POST 请求。

PATIENT_ID 字段中,替换您在创建“患者”时服务器返回的响应中的 ID。

curl -X POST \
    -H "Authorization: Bearer $(gcloud auth application-default 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/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Encounter"

如果请求成功,服务器将以 JSON 格式返回响应。如果您正在使用的是 R4 FHIR 存储区,则 reason 会被替换为 reasonCode

{
  "class": {
    "code": "IMP",
    "display": "inpatient encounter",
    "system": "http://hl7.org/fhir/v3/ActCode"
  },
  "id": "ENCOUNTER_ID",
  "meta": {
    "lastUpdated": "2020-01-01T00:00:00+00:00",
    "versionId": "VERSION_ID"
  },
  "reason": [
    {
      "text": "The patient had an abnormal heart rate. She was concerned about this."
    }
  ],
  "resourceType": "Encounter",
  "status": "finished",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  }
}

PowerShell

创建“患者”资源后,请创建“相遇”资源来说明患者与医生之间的交互。以下示例展示了如何使用 Windows PowerShell 来发送创建“相遇”资源的 POST 请求。

PATIENT_ID 字段中,替换您在创建“患者”时服务器返回的响应中的 ID。

$cred = gcloud auth application-default 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/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Encounter" | ConvertTo-Json

如果请求成功,服务器将以 JSON 格式返回响应。如果您正在使用的是 R4 FHIR 存储区,则 reason 会被替换为 reasonCode

{
  "class": {
    "code": "IMP",
    "display": "inpatient encounter",
    "system": "http://hl7.org/fhir/v3/ActCode"
  },
  "id": "ENCOUNTER_ID",
  "meta": {
    "lastUpdated": "2020-01-01T00:00:00+00:00",
    "versionId": "VERSION_ID"
  },
  "reason": [
    {
      "text": "The patient had an abnormal heart rate. She was concerned about this."
    }
  ],
  "resourceType": "Encounter",
  "status": "finished",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  }
}

Python

def create_encounter(
    base_url, project_id, cloud_region, dataset_id, fhir_store_id, patient_id,
):
    """Creates a new Encounter resource in a FHIR store based on a Patient."""
    url = "{}/projects/{}/locations/{}".format(
        base_url, project_id, cloud_region
    )

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

    # Make an authenticated API request
    session = get_session()

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

    body = {
        "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/{}".format(patient_id)},
        "resourceType": "Encounter",
    }

    response = session.post(fhir_store_path, headers=headers, json=body)
    response.raise_for_status()

    resource = response.json()

    print("Created Encounter resource with ID {}".format(resource["id"]))

    return response

curl

创建“相遇”资源后,请创建该相遇的“观察结果”。“观察结果”测量了患者的每分钟心跳数 (BPM)。以下示例展示了如何使用 curl 来发送创建“观察结果”资源的 POST 请求:

  • BPM_VALUE 字段中输入一个值。
  • PATIENT_ID 字段中,替换您在创建“患者”时服务器返回的响应中的 ID。
  • ENCOUNTER_ID 字段中,替换您在创建“相遇”时服务器返回的响应中的 ID。
curl -X POST \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     -H "Content-Type: application/fhir+json; charset=utf-8" \
     --data "{
         \"resourceType\": \"Observation\",
         \"status\": \"final\",
         \"subject\": {
           \"reference\": \"Patient/PATIENT_ID\"
         },
         \"effectiveDateTime\": \"2020-01-01T00:00:00+00:00\",
         \"code\": {
           \"coding\": [
             {
               \"system\": \"http://loinc.org\",
               \"code\": \"8867-4\",
               \"display\": \"Heart rate\"
             }
           ]
         },
         \"valueQuantity\": {
           \"value\": BPM_VALUE,
           \"unit\": \"bpm\"
         },
         \"context\": {
           \"reference\": \"Encounter/ENCOUNTER_ID\"
         }
     }" \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation"

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "code": {
    "coding": [
      {
        "code": "8867-4",
        "display": "Heart rate",
        "system": "http://loinc.org"
      }
    ]
  },
  "context": {
    "reference": "Encounter/ENCOUNTER_ID"
  },
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "meta": {
    "lastUpdated": "2020-01-01T00:00:00+00:00",
    "versionId": "VERSION_ID"
  },
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "valueQuantity": {
    "unit": "bpm",
    "value": BPM_VALUE
  }
}

PowerShell

创建“相遇”资源后,请创建该相遇的“观察结果”。“观察结果”测量了患者的每分钟心跳数 (BPM)。以下示例展示了如何使用 Windows PowerShell 来发送创建“观察结果”资源的 POST 请求。

  • BPM_VALUE 字段中输入一个值。
  • PATIENT_ID 字段中,替换您在创建“患者”时服务器返回的响应中的 ID。
  • ENCOUNTER_ID 字段中,替换您在创建“相遇”时服务器返回的响应中的 ID。
$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

$observation = '{
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "code": {
    "coding": [
      {
        "system": "http://loinc.org",
        "code": "8867-4",
        "display": "Heart rate"
      }
    ]
  },
  "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/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation" | ConvertTo-Json

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "code": {
    "coding": [
      {
        "code": "8867-4",
        "display": "Heart rate",
        "system": "http://loinc.org"
      }
    ]
  },
  "context": {
    "reference": "Encounter/ENCOUNTER_ID"
  },
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "meta": {
    "lastUpdated": "2020-01-01T00:00:00+00:00",
    "versionId": "VERSION_ID"
  },
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "valueQuantity": {
    "unit": "bpm",
    "value": BPM_VALUE
  }
}

Python

def create_observation(
    base_url,
    project_id,
    cloud_region,
    dataset_id,
    fhir_store_id,
    patient_id,
    encounter_id,
):
    """
    Creates a new Observation resource in a FHIR store based on
    an Encounter.
    """
    url = "{}/projects/{}/locations/{}".format(
        base_url, project_id, cloud_region
    )

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

    # Make an authenticated API request
    session = get_session()

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

    body = {
        "resourceType": "Observation",
        "code": {"coding": [{"system": "http://loinc.org", "code": "8867-4", "display": "Heart rate"}]},
        "status": "final",
        "subject": {"reference": "Patient/{}".format(patient_id)},
        "effectiveDateTime": "2019-01-01T00:00:00+00:00",
        "valueQuantity": {"value": 80, "unit": "bpm"},
        "context": {"reference": "Encounter/{}".format(encounter_id)},
    }

    response = session.post(fhir_store_path, headers=headers, json=body)
    response.raise_for_status()

    resource = response.json()

    print("Created Observation resource with ID {}".format(resource["id"]))

    return response

更新 FHIR 资源

以下示例展示了如何调用 projects.locations.datasets.fhirStores.fhir.update 方法来更新 FHIR 资源。该方法实现 FHIR 标准更新交互(DSTU2STU3R4)。

当您更新资源时,该资源的全部内容都会更新。 这与修补资源不同,后者只会更新资源的一部分内容。

如果 FHIR 存储区设置了 enableUpdateCreate,则请求将被视为 upsert 操作(更新或插入),该操作会更新资源(如果资源存在)或者使用该请求中指定的 ID 插入资源(如果资源不存在)。

请求正文必须包含 JSON 编码的 FHIR 资源,而请求标头必须包含 Content-Type: application/fhir+json。该资源必须包含一个 id 元素,其值与请求的 REST 路径中的 ID 值相同。

curl

要更新 FHIR 资源,请发出 PUT 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 资源类型
  • 资源 ID
  • 访问令牌

以下示例展示了如何使用 curl 来发送修改“观察结果”资源的 PUT 请求。“观察结果”测量了患者的每分钟心跳数 (BPM)。

curl -X PUT \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     -H "Content-Type: application/fhir+json; charset=utf-8" \
     --data '{
         "effectiveDateTime": "2020-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/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation/OBSERVATION_ID"

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "meta": {
    "lastUpdated": "2020-01-01T00:00:00+00:00",
    "versionId": "VERSION_ID"
  },
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "valueQuantity": {
    "unit": "bpm",
    "value": BPM_VALUE
  }
}

PowerShell

要更新 FHIR 资源,请发出 PUT 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 资源类型
  • 资源 ID
  • 访问令牌

以下示例展示了如何使用 Windows PowerShell 来发送修改“观察结果”资源的 PUT 请求。“观察结果”测量了患者的每分钟心跳数 (BPM)。

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

$observation = '{
  "effectiveDateTime": "2020-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/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation/OBSERVATION_ID" | ConvertTo-Json

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "meta": {
    "lastUpdated": "2020-01-01T00:00:00+00:00",
    "versionId": "VERSION_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/v1"
)

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

	// The following payload works with a Patient resource and is not
	// intended to work with other types of FHIR resources. If necessary,
	// supply a new payload with data that corresponds to the FHIR resource
	// you are updating.
	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

const {google} = require('googleapis');
const healthcare = google.healthcare('v1');

const updateFhirResource = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({
    auth,
    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 resourceId = '16e8a860-33b3-49be-9b03-de979feed14a';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}`;
  // The following body works with a Patient resource and is not intended
  // to work with other types of FHIR resources. If necessary, supply a new
  // body with data that corresponds to the FHIR resource you are updating.
  const body = {resourceType: resourceType, id: resourceId, active: true};
  const request = {name, requestBody: body};

  const resource = await healthcare.projects.locations.datasets.fhirStores.fhir.update(
    request
  );
  console.log(`Updated ${resourceType} resource:\n`, resource.data);
};

updateFhirResource();

Python

def update_resource(
    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()

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

    # The body shown works with a Patient resource and is not guaranteed
    # to work with other types of FHIR resources. If necessary,
    # supply a new body with data that corresponds to the resource you
    # are updating.
    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("Updated {} resource:".format(resource["resourceType"]))
    print(json.dumps(resource, indent=2))

    return resource

有条件地更新 FHIR 资源

以下示例展示了如何调用 projects.locations.datasets.fhirStores.fhir.conditionalUpdate 方法来更新与搜索查询匹配的 FHIR 资源,而不是按资源 ID 来标识资源。该方法实现 FHIR 标准有条件地更新交互(DSTU2STU3R4)。

一项资源一次只能应用一个有条件地更新。

服务器返回的响应取决于与搜索条件的匹配项数量:

  • 一个匹配项:资源已成功更新或返回错误。
  • 多个匹配项:请求返回 412 Precondition Failed 错误。
  • 具有 id 的零匹配:如果搜索条件识别零匹配,提供的资源正文包含 id,且 FHIR 存储区设定了 enableUpdateCreate,则系统将使用服务器分配的 ID 创建资源,过程类似于使用 projects.locations.datasets.fhirStores.fhir.create 创建资源。忽略 id
  • 没有 id 的零匹配:如果搜索条件识别零匹配,且提供的资源正文不包含 id,则系统将使用服务器分配的 ID 创建资源,过程类似于使用 projects.locations.datasets.fhirStores.fhir.create 创建资源。

请求正文必须包含 JSON 编码的 FHIR 资源,而请求标头必须包含 Content-Type: application/fhir+json

curl

要更新与搜索查询匹配的 FHIR 资源,请发出 PUT 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 您要搜索的资源类型
  • 包含您要搜索的信息的查询字符串
  • 访问令牌

以下示例展示了如何使用 curl 发送 PUT 请求,以使用“观察结果”的标识符(my-code-system 中的 ABC-12345)修改“观察结果”资源。“观察结果”测量了患者的每分钟心跳数 (BPM)。

curl -X PUT \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     -H "Content-Type: application/fhir+json; charset=utf-8" \
     --data '{
         "effectiveDateTime": "2020-01-01T00:00:00+00:00",
         "resourceType": "Observation",
         "identifier": [
             {
                 "system": "my-code-system",
                 "value": "ABC-12345"
             }
         ],
         "status": "final",
         "subject": {
             "reference": "Patient/PATIENT_ID"
         },
         "valueQuantity": {
             "unit": "bpm",
             "value": BPM_VALUE
         }
     }' \
     "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation?identifier=my-code-system|ABC-12345"

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "meta": {
    "lastUpdated": "2020-01-01T00:00:00+00:00",
    "versionId": "VERSION_ID"
  },
  "resourceType": "Observation",
  "identifier": [
    {
      "system": "my-code-system",
      "value": "ABC-12345"
    }
  ],
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "valueQuantity": {
    "unit": "bpm",
    "value": BPM_VALUE
  }
}

PowerShell

要更新与搜索查询匹配的 FHIR 资源,请发出 PUT 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 您要搜索的资源类型
  • 包含您要搜索的信息的查询字符串
  • 访问令牌

以下示例展示了如何使用 Windows PowerShell 发送 PUT 请求,以使用“观察结果”的标识符(my-code-system 中的 ABC-12345)修改“观察结果”资源。“观察结果”测量了患者的每分钟心跳数 (BPM)。

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

$observation = '{
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "resourceType": "Observation",
  "identifier": [
      {
          "system": "my-code-system",
          "value": "ABC-12345"
      }
  ],
  "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/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation?identifier=my-code-system|ABC-12345" | ConvertTo-Json

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "meta": {
    "lastUpdated": "2020-01-01T00:00:00+00:00",
    "versionId": "VERSION_ID"
  },
  "resourceType": "Observation",
  "identifier": [
    {
      "system": "my-code-system",
      "value": "ABC-12345"
    }
  ],
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "valueQuantity": {
    "unit": "bpm",
    "value": BPM_VALUE
  }
}

Go

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

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

// queryParamOpt is a googleapi.Option (https://godoc.org/google.golang.org/api/googleapi#CallOption)
// that adds query parameters to an API call.
type queryParamOpt struct {
	key, value string
}

func (qp queryParamOpt) Get() (string, string) { return qp.key, qp.value }

// ConditionalUpdateFHIRResource conditionally updates an FHIR resource.
func ConditionalUpdateFHIRResource(w io.Writer, projectID, location, datasetID, fhirStoreID, resourceType string, active bool) error {
	// projectID := "my-project"
	// location := "us-central1"
	// datasetID := "my-dataset"
	// fhirStoreID := "my-fhir-store"
	// resourceType := "Patient"
	// active := true

	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

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

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

	call := fhirService.ConditionalUpdate(parent, resourceType, bytes.NewReader(jsonPayload))

	call.Header().Set("Content-Type", "application/fhir+json")

	// Refine your search by appending tags to the request in the form of query
	// parameters. This searches for resources updated in the last 48 hours.
	twoDaysAgo := time.Now().Add(-48 * time.Hour).Format("2006-01-02")
	lastUpdated := queryParamOpt{key: "_lastUpdated", value: "gt" + twoDaysAgo}

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

	return nil
}

Python

def conditional_update_resource(
    service_account_json,
    base_url,
    project_id,
    cloud_region,
    dataset_id,
    fhir_store_id,
    patient_id,
    encounter_id,
):
    """
    If a resource is found based on the search criteria specified in
    the query parameters, updates the entire contents of that resource.
    """
    url = "{}/projects/{}/locations/{}".format(base_url, project_id, cloud_region)

    # The search query in this request updates all Observations
    # using the Observation's identifier (ABC-12345 in my-code-system)
    # so that their 'status' is 'cancelled'.
    resource_path = "{}/datasets/{}/fhirStores/{}/fhir/Observation".format(
        url, dataset_id, fhir_store_id
    )

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

    body = {
        "effectiveDateTime": "2019-01-01T00:00:00+00:00",
        "resourceType": "Observation",
        "context": {"reference": "Encounter/{}".format(encounter_id)},
        "identifier": [{"system": "my-code-system", "value": "ABC-12345"}],
        "status": "cancelled",
        "subject": {"reference": "Patient/{}".format(patient_id)},
        "valueQuantity": {"unit": "bpm", "value": 80},
    }

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

    params = {"identifier": "my-code-system|ABC-12345"}

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

    response.raise_for_status()
    resource = response.json()

    print(
        "Conditionally updated Observations with the identifier "
        "'my-code-system|ABC-12345' to have a 'status' of "
        "'cancelled'."
    )
    print(json.dumps(resource, indent=2))

    return resource

修补 FHIR 资源

以下示例展示了如何调用 projects.locations.datasets.fhirStores.fhir.patch 方法来修补 FHIR 资源。该方法实现 FHIR 标准修补交互(DSTU2STU3R4)。

修补资源时,通过应用JSON 补丁文档中指定的操作来更新资源的一部分。

请求必须包含 JSON 补丁文档,而请求标头必须包含 Content-Type: application/json-patch+json

curl

要修补 FHIR 资源,请发出 PATCH 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 资源类型
  • 资源 ID
  • 访问令牌

以下示例展示了如何使用 curl 来发送修改“观察结果”资源的 PATCH 请求。使用 replace 补丁操作更新“观察结果”:患者的每分钟心跳数 (BPM)。

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

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "meta": {
    "lastUpdated": "2020-01-01T00:00:00+00:00",
    "versionId": "VERSION_ID"
  },
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "valueQuantity": {
    "unit": "bpm",
    "value": BPM_VALUE
  }
}

PowerShell

要修补 FHIR 资源,请发出 PATCH 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 资源类型
  • 资源 ID
  • 访问令牌

以下示例展示了如何使用 Windows PowerShell 来发送修改“观察结果”资源的 PATCH 请求。使用 replace 补丁操作更新“观察结果”:患者的每分钟心跳数 (BPM)。

$cred = gcloud auth application-default 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/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation/OBSERVATION_ID" | ConvertTo-Json

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "meta": {
    "lastUpdated": "2020-01-01T00:00:00+00:00",
    "versionId": "VERSION_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/v1"
)

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

	// The following payload works with a Patient resource and is not intended to work with
	// other types of FHIR resources. If necessary, supply a new payload with data that
	// corresponds to the FHIR resource you are patching.
	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
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.net.URISyntaxException;
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 FhirResourcePatch {
  private static final String FHIR_NAME =
      "projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/%s/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void fhirResourcePatch(String resourceName, String data)
      throws IOException, URISyntaxException {
    // String resourceName =
    //    String.format(
    //        FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "resource-type",
    // "resource-id");
    // The following data works with a Patient resource and is not intended to work with
    // other types of FHIR resources. If necessary, supply new values for data that
    // correspond to the FHIR resource you are patching.
    // String data = "[{\"op\": \"replace\", \"path\": \"/active\", \"value\": false}]";

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    HttpClient httpClient = HttpClients.createDefault();
    String uri = String.format("%sv1/%s", client.getRootUrl(), resourceName);
    URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());
    StringEntity requestEntity = new StringEntity(data);

    HttpUriRequest request =
        RequestBuilder.patch(uriBuilder.build())
            .setEntity(requestEntity)
            .addHeader("Content-Type", "application/json-patch+json")
            .addHeader("Accept-Charset", "utf-8")
            .addHeader("Accept", "application/fhir+json; charset=utf-8")
            .build();

    // Execute the request and process the results.
    HttpResponse response = httpClient.execute(request);
    HttpEntity responseEntity = response.getEntity();
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
      System.err.print(
          String.format(
              "Exception patching FHIR resource: %s\n", response.getStatusLine().toString()));
      responseEntity.writeTo(System.err);
      throw new RuntimeException();
    }
    System.out.println("FHIR resource patched: ");
    responseEntity.writeTo(System.out);
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // 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)
        .setApplicationName("your-application-name")
        .build();
  }

  private static String getAccessToken() throws IOException {
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    return credential.refreshAccessToken().getTokenValue();
  }
}

Node.js

const {google} = require('googleapis');
const healthcare = google.healthcare('v1');

async function patchFhirResource() {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  // TODO(developer): replace patchOptions with your desired JSON patch body
  const patchOptions = [{op: 'replace', path: '/active', value: false}];
  google.options({auth, headers: {'Content-Type': 'application/json-patch+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 resourceId = '16e8a860-33b3-49be-9b03-de979feed14a';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}`;
  const request = {
    name,
    requestBody: patchOptions
  };

  const resource = await healthcare.projects.locations.datasets.fhirStores.fhir.patch(
    request,
  );
  console.log(`Patched ${resourceType} resource`);
}

patchFhirResource();

Python

def patch_resource(
    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()

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

    # The body shown works with a Patient resource and is not guaranteed
    # to work with other types of FHIR resources. If necessary,
    # supply a new body with data that corresponds to the resource you
    # are patching.
    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("Patched {} resource:".format(resource["resourceType"]))
    print(json.dumps(resource, indent=2))

    return resource

有条件地修补 FHIR 资源

以下示例展示了如何调用 projects.locations.datasets.fhirStores.fhir.conditionalPatch 方法来修补与搜索查询匹配的 FHIR 资源,而不是按资源 ID 来标识资源。该方法实现 FHIR 标准有条件地修补交互(DSTU2STU3R4)。

一项资源一次只能应用一个有条件地修补。如果搜索条件识别多个匹配项,则请求会返回 412 Precondition Failed 错误。

curl

要修补与搜索查询匹配的 FHIR 资源,请发出 PATCH 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 您要搜索的资源类型
  • 包含您要搜索的信息的查询字符串
  • 访问令牌

以下示例展示了如何使用 curl 发送 PATCH 请求以修改“观察结果”资源(如果“观察结果”的对象为“Patient123”)。使用 replace 补丁操作更新“观察结果”:患者的每分钟心跳数 (BPM)。

curl -X PATCH \
     -H "Authorization: Bearer $(gcloud auth application-default 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/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation?subject=Patient123"

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "meta": {
    "lastUpdated": "2020-01-01T00:00:00+00:00",
    "versionId": "VERSION_ID"
  },
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "valueQuantity": {
    "unit": "bpm",
    "value": BPM_VALUE
  }
}

PowerShell

要修补与搜索查询匹配的 FHIR 资源,请发出 PATCH 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 您要搜索的资源类型
  • 包含您要搜索的信息的查询字符串
  • 访问令牌

以下示例展示了如何使用 Windows PowerShell 发送 PATCH 请求以修改“观察结果”资源(如果“观察结果”的对象为“Patient123”)。使用 replace 补丁操作更新“观察结果”:患者的每分钟心跳数 (BPM)。

$cred = gcloud auth application-default 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/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation?subject=Patient123" | ConvertTo-Json

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "meta": {
    "lastUpdated": "2020-01-01T00:00:00+00:00",
    "versionId": "VERSION_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"
	"time"

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

// queryParamOpt is a googleapi.Option (https://godoc.org/google.golang.org/api/googleapi#CallOption)
// that adds query parameters to an API call.
type queryParamOpt struct {
	key, value string
}

func (qp queryParamOpt) Get() (string, string) { return qp.key, qp.value }

// ConditionalPatchFHIRResource conditionally patches an FHIR resource.
func ConditionalPatchFHIRResource(w io.Writer, projectID, location, datasetID, fhirStoreID, resourceType string, active bool) error {
	// projectID := "my-project"
	// location := "us-central1"
	// datasetID := "my-dataset"
	// fhirStoreID := "my-fhir-store"
	// resourceType := "Patient"
	// active := true

	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

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

	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)
	}

	call := fhirService.ConditionalPatch(parent, resourceType, bytes.NewReader(jsonPayload))

	call.Header().Set("Content-Type", "application/json-patch+json")

	// Refine your search by appending tags to the request in the form of query
	// parameters. This searches for resources updated in the last 48 hours.
	twoDaysAgo := time.Now().Add(-48 * time.Hour).Format("2006-01-02")
	lastUpdated := queryParamOpt{key: "_lastUpdated", value: "gt" + twoDaysAgo}

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

	return nil
}

Python

def conditional_patch_resource(
    service_account_json, base_url, project_id, cloud_region, dataset_id, fhir_store_id
):
    """
    If a resource is found based on the search criteria specified in
    the query parameters, updates part of that resource by
    applying the operations specified in a JSON Patch document.
    """
    url = "{}/projects/{}/locations/{}".format(base_url, project_id, cloud_region)

    # The search query in this request updates all Observations
    # if the subject of the Observation is a particular patient.
    resource_path = "{}/datasets/{}/fhirStores/{}/fhir/Observation".format(
        url, dataset_id, fhir_store_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": "/valueQuantity/value",
                # Sets the BPM for all matching Observations to 80. This
                # is the portion of the request being patched.
                "value": 80,
            }
        ]
    )

    # The search query is passed in as a query string parameter.
    params = {"identifier": "my-code-system|ABC-12345"}

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

    print(response.url)

    resource = response.json()

    print(
        "Conditionally patched all Observations with the "
        "identifier 'my-code-system|ABC-12345' to use a BPM of 80."
    )
    print(json.dumps(resource, indent=2))

    return resource

获得 FHIR 资源

以下示例展示了如何获取 FHIR 资源的内容。如需了解详情,请参阅 projects.locations.datasets.fhirStores.fhir.read

curl

要获取 FHIR 资源的内容,请发出 GET 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 资源类型和 ID
  • 访问令牌

以下示例展示了使用 curl 对上一部分中创建的“观察结果”发出的 GET 请求。

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

如果请求成功,服务器将以 JSON 格式返回响应:

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

PowerShell

要获取 FHIR 资源的内容,请发出 GET 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 资源类型和 ID
  • 访问令牌

以下示例展示了使用 Windows PowerShell 对上一部分中创建的“观察结果”发出的 GET 请求。

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

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

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "context": {
    "reference": "Encounter/ENCOUNTER_ID"
  },
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "meta": {
    "lastUpdated": "2020-01-01T00:00:00+00:00",
    "versionId": "VERSION_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/v1"
)

// 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
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.net.URISyntaxException;
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.impl.client.HttpClients;

public class FhirResourceGet {
  private static final String FHIR_NAME =
      "projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/%s/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void fhirResourceGet(String resourceName) throws IOException, URISyntaxException {
    // String resourceName =
    //    String.format(
    //        FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "resource-type",
    //  "resource-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();
    HttpClient httpClient = HttpClients.createDefault();
    String uri = String.format("%sv1/%s", client.getRootUrl(), resourceName);
    URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());

    HttpUriRequest request = RequestBuilder.get().setUri(uriBuilder.build()).build();

    // Execute the request and process the results.
    HttpResponse response = httpClient.execute(request);
    HttpEntity responseEntity = response.getEntity();
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
      String errorMessage =
          String.format(
              "Exception retrieving FHIR resource: %s\n", response.getStatusLine().toString());
      System.err.print(errorMessage);
      responseEntity.writeTo(System.err);
      throw new RuntimeException(errorMessage);
    }
    System.out.println("FHIR resource retrieved: ");
    responseEntity.writeTo(System.out);
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // 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)
        .setApplicationName("your-application-name")
        .build();
  }

  private static String getAccessToken() throws IOException {
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    return credential.refreshAccessToken().getTokenValue();
  }
}

Node.js

const {google} = require('googleapis');
const healthcare = google.healthcare('v1');

const getFhirResource = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // 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 resourceId = '16e8a860-33b3-49be-9b03-de979feed14a';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}`;
  const request = {name};

  const resource = await healthcare.projects.locations.datasets.fhirStores.fhir.read(
    request
  );
  console.log(`Got ${resourceType} resource:\n`, resource.data);
};

getFhirResource();

Python

def get_resource(
    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()

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

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

    resource = response.json()

    print("Got {} resource:".format(resource["resourceType"]))
    print(json.dumps(resource, indent=2))

    return resource

获取所有患者隔离区资源

以下示例展示了如何获取与特定患者隔离区(DSTU2STU3R4)关联的所有资源。如需了解详情,请参阅 projects.locations.datasets.fhirStores.fhir.Patient-everything

curl

要获取患者隔离区中的资源,请发出 GET 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 患者的 ID
  • 访问令牌

以下示例展示了使用 curlGET 请求。

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

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "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": "2020-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

要获取患者隔离区中的资源,请发出 GET 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 患者的 ID
  • 访问令牌

以下示例展示了使用 Windows PowerShell 的 GET 请求:

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

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

如果请求成功,服务器将以 JSON 格式返回响应:

{
  "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": "2020-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/v1"
)

// 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
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.net.URISyntaxException;
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.impl.client.HttpClients;

public class FhirResourceGetPatientEverything {
  private static final String FHIR_NAME =
      "projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/Patient/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void fhirResourceGetPatientEverything(String resourceName)
      throws IOException, URISyntaxException {
    // String resourceName =
    //    String.format(
    //        FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "patient-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    HttpClient httpClient = HttpClients.createDefault();
    String uri = String.format("%sv1/%s/$everything", client.getRootUrl(), resourceName);
    URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());

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

    // Execute the request and process the results.
    HttpResponse response = httpClient.execute(request);
    HttpEntity responseEntity = response.getEntity();
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
      System.err.print(
          String.format(
              "Exception getting patient everythingresource: %s\n",
              response.getStatusLine().toString()));
      responseEntity.writeTo(System.err);
      throw new RuntimeException();
    }
    System.out.println("Patient compartment results: ");
    responseEntity.writeTo(System.out);
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // 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)
        .setApplicationName("your-application-name")
        .build();
  }

  private static String getAccessToken() throws IOException {
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    return credential.refreshAccessToken().getTokenValue();
  }
}

Node.js

const {google} = require('googleapis');
const healthcare = google.healthcare('v1');

const getPatientEverything = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // 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 patientId = '16e8a860-33b3-49be-9b03-de979feed14a';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/Patient/${patientId}`;
  const request = {name};

  const patientEverything = await healthcare.projects.locations.datasets.fhirStores.fhir.PatientEverything(
    request
  );
  console.log(
    `Got all resources in patient ${patientId} compartment:\n`,
    JSON.stringify(patientEverything)
  );
};

getPatientEverything();

Python

def get_patient_everything(
    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()

    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

获取按类型或日期过滤的患者隔离区资源

以下示例展示了如何获取与按一组类型过滤以及自指定日期和时间开始的特定患者隔离区 (R4) 关联的所有资源。如需了解详情,请参阅 projects.locations.datasets.fhirStores.fhir.Patient-everything

curl

要获取指定类型以及自指定日期开始的患者隔离区中的资源,请发出 GET 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 患者的 ID
  • 包含以逗号分隔的资源类型列表和开始日期的查询字符串
  • 访问令牌

以下示例展示了使用 curlGET 请求。

curl -X GET \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/PATIENT_ID/\$everything?_type=RESOURCE_TYPES&_since=DATE"

如果请求成功,服务器将以 JSON 格式返回符合指定条件的资源:

PowerShell

要获取指定类型以及自指定日期开始的患者隔离区中的资源,请发出 GET 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 患者的 ID
  • 包含以逗号分隔的资源类型列表和开始日期的查询字符串
  • 访问令牌

以下示例展示了使用 Windows PowerShell 的 GET 请求:

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

Invoke-RestMethod `
  -Method Get `
  -Headers $headers `
  -Uri 'https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/RESOURCE_ID/$everything?_type=RESOURCE_TYPES&_since=DATE' | ConvertTo-Json

如果请求成功,服务器将以 JSON 格式返回符合指定条件的资源:

列出 FHIR 资源版本

以下示例展示了如何列出 FHIR 资源的所有历史版本。如需了解详情,请参阅 projects.locations.datasets.fhirStores.fhir.history

这些示例使用创建 FHIR 资源中创建的资源,并展示如何列出“观察结果”资源的版本。

curl

以下示例展示了如何列出“观察结果”资源的所有版本。观察结果在最初创建后更新了一次,以更改患者的每分钟心跳数 (BPM)。

要列出 FHIR 资源的所有版本(包括当前版本和所有已删除的版本),请发出 GET 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 资源类型和 ID
  • 访问令牌

以下示例展示了使用 curlGET 请求。

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

如果请求成功,服务器将以 JSON 格式返回响应。在此示例中,它会返回两个版本的观察结果。在第一个版本中,患者的心率是 75 BPM。在第二个版本中,患者的心率是 85 BPM。

{
  "entry": [
    {
      "resource": {
        "effectiveDateTime": "2020-01-01T00:00:00+00:00",
        "id": "OBSERVATION_ID",
        "meta": {
          "lastUpdated": "2020-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": "2020-01-01T00:00:00+00:00",
        "id": "OBSERVATION_ID",
        "meta": {
          "lastUpdated": "2020-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

以下示例展示了如何列出“观察结果”资源的所有版本。观察结果在最初创建后更新了一次,以更改患者的每分钟心跳数 (BPM)。

要列出 FHIR 资源的所有版本(包括当前版本和所有已删除的版本),请发出 GET 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 资源类型和 ID
  • 访问令牌

以下示例展示了使用 Windows PowerShell 的 GET 请求。

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

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

如果请求成功,服务器将以 JSON 格式返回响应。在此示例中,它会返回两个版本的观察结果。在第一个版本中,患者的心率是 75 BPM。在第二个版本中,患者的心率是 85 BPM。

{
  "entry": [
    {
      "resource": {
        "effectiveDateTime": "2020-01-01T00:00:00+00:00",
        "id": "OBSERVATION_ID",
        "meta": {
          "lastUpdated": "2020-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": "2020-01-01T00:00:00+00:00",
        "id": "OBSERVATION_ID",
        "meta": {
          "lastUpdated": "2020-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"
}

Go

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

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

// 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
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.net.URISyntaxException;
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.impl.client.HttpClients;

public class FhirResourceGetHistory {
  private static final String FHIR_NAME =
      "projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/%s/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void fhirResourceGetHistory(String resourceName, String versionId)
      throws IOException, URISyntaxException {
    // String resourceName =
    //    String.format(
    //        FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "resource-type",
    // "resource-id");
    // String versionId = "version-uuid"

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    HttpClient httpClient = HttpClients.createDefault();
    String uri = String.format("%sv1/%s/_history/%s", client.getRootUrl(), resourceName, versionId);
    URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());

    HttpUriRequest request =
        RequestBuilder.get()
            .setUri(uriBuilder.build())
            .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.
    HttpResponse response = httpClient.execute(request);
    HttpEntity responseEntity = response.getEntity();
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
      System.err.print(
          String.format(
              "Exception retrieving FHIR history: %s\n", response.getStatusLine().toString()));
      responseEntity.writeTo(System.err);
      throw new RuntimeException();
    }
    System.out.println("FHIR resource retrieved from version: ");
    responseEntity.writeTo(System.out);
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // 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)
        .setApplicationName("your-application-name")
        .build();
  }

  private static String getAccessToken() throws IOException {
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    return credential.refreshAccessToken().getTokenValue();
  }
}

Node.js

const {google} = require('googleapis');
const healthcare = google.healthcare('v1');

const listFhirResourceHistory = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // 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 resourceId = '16e8a860-33b3-49be-9b03-de979feed14a';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}/_history`;
  const request = {name};

  const resource = await healthcare.projects.locations.datasets.fhirStores.fhir.read(
    request
  );
  console.log(JSON.stringify(resource.data, null, 2));
};

listFhirResourceHistory();

Python

def list_resource_history(
    base_url,
    project_id,
    cloud_region,
    dataset_id,
    fhir_store_id,
    resource_type,
    resource_id,
):
    """Gets the history of a 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()

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

    response = session.get(resource_path + "/_history", headers=headers)
    response.raise_for_status()

    resource = response.json()

    print(
        "History for {} resource:".format(
            resource["entry"][0]["resource"]["resourceType"]
        )
    )
    print(json.dumps(resource, indent=2))

    return resource

检索 FHIR 资源版本

以下示例展示了如何检索资源的特定版本。 如需了解详情,请参阅 projects.locations.datasets.fhirStores.fhir.vread

下面着重强调列出 FHIR 资源版本中的“观察结果”资源的版本 ID:

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

以下示例使用创建 FHIR 资源中创建的资源,并展示如何查看“观察结果”资源。

curl

要获取 FHIR 资源的特定版本,请发出 GET 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 资源类型和 ID
  • 资源版本
  • 访问令牌

以下示例展示了使用 curlGET 请求。

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

如果请求成功,服务器将以 JSON 格式返回响应。在此示例中,服务器会返回第一个版本的观察结果,其中患者的心率是 75 BPM。

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

PowerShell

要获取 FHIR 资源的特定版本,请发出 GET 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 资源类型和 ID
  • 资源版本
  • 访问令牌

以下示例展示了使用 curlGET 请求。

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

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

如果请求成功,服务器将以 JSON 格式返回响应。在此示例中,服务器会返回第一个版本的观察结果,其中患者的心率是 75 BPM。

{
  "context": {
    "reference": "Encounter/ENCOUNTER_ID"
  },
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "id": "OBSERVATION_ID",
  "meta": {
    "lastUpdated": "2020-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/v1"
)

// getFHIRResourceHistory gets an FHIR resource history.
func getFHIRResourceHistory(w io.Writer, projectID, location, datasetID, fhirStoreID, resourceType, fhirResourceID, versionID 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/_history/%s", projectID, location, datasetID, fhirStoreID, resourceType, fhirResourceID, versionID)

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

	return nil
}

Node.js

const {google} = require('googleapis');
const healthcare = google.healthcare('v1');

const getFhirResourceHistory = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // 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 resourceId = '16e8a860-33b3-49be-9b03-de979feed14a';
  // const versionId = 'MTU2NPg3NDgyNDAxMDc4OTAwMA';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}/_history/${versionId}`;
  const request = {name};

  const resource = await healthcare.projects.locations.datasets.fhirStores.fhir.vread(
    request
  );
  console.log(JSON.stringify(resource.data, null, 2));
};

getFhirResourceHistory();

Python

def get_resource_history(
    base_url,
    project_id,
    cloud_region,
    dataset_id,
    fhir_store_id,
    resource_type,
    resource_id,
    version_id,
):
    """Gets a version 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
    )
    resource_path += "/_history/{}".format(version_id)

    # Make an authenticated API request
    session = get_session()

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

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

    resource = response.json()

    print("Got history for {} resource:".format(resource_type))
    print(json.dumps(resource, indent=2))

    return resource

删除 FHIR 资源

以下示例展示了如何调用 projects.locations.datasets.fhirStores.fhir.delete 方法来删除 FHIR 资源。

无论操作是否成功,服务器都会返回 200 OK HTTP 状态代码。要检查是否已成功删除资源,请搜索获取该资源并查看它是否存在。

curl

要删除 FHIR 资源,请发出 DELETE 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 访问令牌

以下示例展示了使用 curlDELETE 请求。

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

如果请求成功,服务器将以 JSON 格式返回空响应正文:

{}

PowerShell

要删除 FHIR 资源,请发出 DELETE 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 资源类型和 ID
  • 访问令牌

以下示例显示了使用 Windows PowerShell 的 DELETE 请求。

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

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

如果请求成功,服务器将以 JSON 格式返回空响应正文:

{}

Go

import (
	"context"
	"fmt"
	"io"

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

// deleteFHIRResource deletes an FHIR resource.
// Regardless of whether the operation succeeds or
// fails, the server returns a 200 OK HTTP status code. To check that the
// resource was successfully deleted, search for or get the resource and
// see if it exists.
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
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.net.URISyntaxException;
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.impl.client.HttpClients;

public class FhirResourceDelete {
  private static final String FHIR_NAME =
      "projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/%s/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void fhirResourceDelete(String resourceName)
      throws IOException, URISyntaxException {
    // String resourceName =
    //    String.format(
    //        FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "resource-type",
    // "resource-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    HttpClient httpClient = HttpClients.createDefault();
    String uri = String.format("%sv1/%s", client.getRootUrl(), resourceName);
    URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());

    HttpUriRequest request =
        RequestBuilder.delete()
            .setUri(uriBuilder.build())
            .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.
    // Regardless of whether the operation succeeds or
    // fails, the server returns a 200 OK HTTP status code. To check that the
    // resource was successfully deleted, search for or get the resource and
    // see if it exists.
    HttpResponse response = httpClient.execute(request);
    HttpEntity responseEntity = response.getEntity();
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
      String errorMessage =
          String.format(
              "Exception deleting FHIR resource: %s\n", response.getStatusLine().toString());
      System.err.print(errorMessage);
      responseEntity.writeTo(System.err);
      throw new RuntimeException(errorMessage);
    }
    System.out.println("FHIR resource deleted.");
    responseEntity.writeTo(System.out);
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // 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)
        .setApplicationName("your-application-name")
        .build();
  }

  private static String getAccessToken() throws IOException {
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    return credential.refreshAccessToken().getTokenValue();
  }
}

Node.js

const {google} = require('googleapis');
const healthcare = google.healthcare('v1');

const deleteFhirResource = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // 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 resourceId = '9a664e07-79a4-4c2e-04ed-e996c75484e1;
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}`;
  const request = {name};

  // Regardless of whether the operation succeeds or
  // fails, the server returns a 200 OK HTTP status code. To check that the
  // resource was successfully deleted, search for or get the resource and
  // see if it exists.
  await healthcare.projects.locations.datasets.fhirStores.fhir.delete(
    request
  );
  console.log(`Deleted FHIR resource`);
};

deleteFhirResource();

Python

def delete_resource(
    base_url,
    project_id,
    cloud_region,
    dataset_id,
    fhir_store_id,
    resource_type,
    resource_id,
):
    """
    Deletes a FHIR resource.

    Regardless of whether the operation succeeds or
    fails, the server returns a 200 OK HTTP status code. To check that the
    resource was successfully deleted, search for or get the resource and
    see if it exists.
    """
    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()

    response = session.delete(resource_path)
    print("Deleted {} resource with ID {}.".format(resource_type, resource_id))

    return response

有条件地删除 FHIR 资源

以下示例展示了如何调用 projects.locations.datasets.fhirStores.fhir.conditionalDelete 方法来删除与搜索查询匹配的 FHIR 资源,而不是按资源 ID 来标识资源。

不同于有条件地修补有条件地更新资源,如果从搜索条件返回多个匹配项,则有条件地删除方法可以应用于多个资源。

无论操作是否成功,服务器都会返回 200 OK HTTP 状态代码。为确保已成功删除资源,请搜索获取该资源并查看它是否存在。

curl

要删除与搜索查询匹配的 FHIR 资源,请发出 DELETE 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 您要搜索的资源类型
  • 包含您要搜索的信息的查询字符串
  • 访问令牌

以下示例展示了一个 DELETE 请求,该请求使用 curl 删除 statuscancelledSTU3R4)的观察结果。

curl -X DELETE \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation?status=cancelled"

如果请求成功,服务器将以 JSON 格式返回空响应正文:

{}

PowerShell

要删除与搜索查询匹配的 FHIR 资源,请发出 DELETE 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 您要搜索的资源类型
  • 包含您要搜索的信息的查询字符串
  • 访问令牌

以下示例展示了一个 DELETE 请求,该请求使用 Windows PowerShell 删除 statuscancelledSTU3R4)的所有观察结果。

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

Invoke-WebRequest `
  -Method Delete `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation?status=cancelled" | Select-Object -Expand Content

如果请求成功,服务器将以 JSON 格式返回空响应正文:

{}

Go

import (
	"context"
	"fmt"
	"io"
	"time"

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

// queryParamOpt is a googleapi.Option (https://godoc.org/google.golang.org/api/googleapi#CallOption)
// that adds query parameters to an API call.
type queryParamOpt struct {
	key, value string
}

func (qp queryParamOpt) Get() (string, string) { return qp.key, qp.value }

// ConditionalDeleteFHIRResource conditionally deletes an FHIR resource.
func ConditionalDeleteFHIRResource(w io.Writer, projectID, location, datasetID, fhirStoreID, resourceType string) error {
	// projectID := "my-project"
	// location := "us-central1"
	// datasetID := "my-dataset"
	// fhirStoreID := "my-fhir-store"
	// resourceType := "Patient"

	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

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

	call := fhirService.ConditionalDelete(parent, resourceType)

	// Refine your search by appending tags to the request in the form of query
	// parameters. This searches for resources updated in the last 48 hours.
	twoDaysAgo := time.Now().Add(-48 * time.Hour).Format("2006-01-02")
	lastUpdated := queryParamOpt{key: "_lastUpdated", value: "gt" + twoDaysAgo}

	if _, err := call.Do(lastUpdated); err != nil {
		return fmt.Errorf("ConditionalDelete: %v", err)
	}

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

	return nil
}

Python

def conditional_delete_resource(
    service_account_json, base_url, project_id, cloud_region, dataset_id, fhir_store_id
):
    """Deletes FHIR resources that match a search query."""
    url = "{}/projects/{}/locations/{}".format(base_url, project_id, cloud_region)

    # The search query in this request deletes all Observations
    # with a status of 'cancelled'.
    resource_path = "{}/datasets/{}/fhirStores/{}/fhir/Observation".format(
        url, dataset_id, fhir_store_id
    )
    # The search query is passed in as a query string parameter.
    params = {"status": "cancelled"}

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

    response = session.delete(resource_path, params=params)
    print(response.url)
    if response.status_code != 404:  # Don't consider missing to be error
        response.raise_for_status()

    print("Conditionally deleted all Observations with status='cancelled'.")

    return response

删除 FHIR 资源的历史版本

以下示例展示了如何删除 FHIR 资源的所有历史版本。如需了解详情,请参阅 projects.locations.datasets.fhirStores.fhir.Resource-purge

只有具有 roles/healthcare.fhirStoreAdmin 角色的用户(调用者)才能调用 projects.locations.datasets.fhirStores.fhir.Resource-purge 方法;具有 roles/healthcare.fhirResourceEditor 角色的用户无法调用该方法。要允许调用者删除 FHIR 资源的历史版本,请执行以下任一操作:

这些示例使用创建 FHIR 资源中创建的资源,并展示如何删除“观察结果”资源的历史版本。

curl

要删除 FHIR 资源的所有历史版本,请发出 DELETE 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 资源类型和 ID
  • 访问令牌

以下示例展示了使用 curlDELETE 请求。

curl -X DELETE \
     -H "Authorization: Bearer $(gcloud auth application-default print-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/RESOURCE_TYPE/RESOURCE_ID/$purge"

如果请求成功,服务器将以 JSON 格式返回空响应正文:

{}

PowerShell

要删除 FHIR 资源的所有历史版本,请发出 DELETE 请求并指定以下信息:

  • 父数据集的名称
  • FHIR 存储区的名称
  • 资源类型和 ID
  • 访问令牌

以下示例显示了使用 Windows PowerShell 的 DELETE 请求。

$cred = gcloud auth application-default 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/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/RESOURCE_TYPE/RESOURCE_ID/$purge" | ConvertTo-Json

如果请求成功,服务器将以 JSON 格式返回空响应正文:

{}

Go

import (
	"context"
	"fmt"
	"io"

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

// 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
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.net.URISyntaxException;
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.impl.client.HttpClients;

public class FhirResourceDeletePurge {
  private static final String FHIR_NAME =
      "projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void fhirResourceDeletePurge(String resourceName)
      throws IOException, URISyntaxException {
    // String resourceName =
    //    String.format(
    //        FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "fhir-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    HttpClient httpClient = HttpClients.createDefault();
    String uri = String.format("%sv1/%s/$purge", client.getRootUrl(), resourceName);
    URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());

    HttpUriRequest request =
        RequestBuilder.delete()
            .setUri(uriBuilder.build())
            .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.
    HttpResponse response = httpClient.execute(request);
    HttpEntity responseEntity = response.getEntity();
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
      String errorMessage =
          String.format(
              "Exception purging FHIR resource: %s\n", response.getStatusLine().toString());
      System.err.print(errorMessage);
      responseEntity.writeTo(System.err);
      throw new RuntimeException(errorMessage);
    }
    System.out.println("FHIR resource history purged.");
    responseEntity.writeTo(System.out);
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // 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)
        .setApplicationName("your-application-name")
        .build();
  }

  private static String getAccessToken() throws IOException {
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    return credential.refreshAccessToken().getTokenValue();
  }
}

Node.js

const {google} = require('googleapis');
const healthcare = google.healthcare('v1');

const deleteFhirResourcePurge = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // 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 resourceId = '9a664e07-79a4-4c2e-04ed-e996c75484e1;
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}`;
  const request = {name};

  await healthcare.projects.locations.datasets.fhirStores.fhir.ResourcePurge(
    request
  );
  console.log(`Deleted all historical versions of resource`);
};

deleteFhirResourcePurge();

Python

def delete_resource_purge(
    base_url,
    project_id,
    cloud_region,
    dataset_id,
    fhir_store_id,
    resource_type,
    resource_id,
):
    """Deletes versions of a resource (excluding current version)."""
    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
    )
    resource_path += "/$purge"

    # Make an authenticated API request
    session = get_session()

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

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

    if response.status_code < 400:
        print(
            "Deleted versions of {} resource "
            "(excluding current version).".format(resource_type)
        )

    return response