FHIR 리소스 만들기 및 관리

이 페이지에서는 FHIR 리소스를 생성, 업데이트, 패치, 조회, 나열, 검색, 삭제하는 방법을 설명합니다.

FHIR 리소스에는 환자, 기기, 관찰 등에 대한 데이터가 포함될 수 있습니다. FHIR 리소스의 전체 목록은 FHIR 리소스 색인(DSTU2 ,STU3 또는 R4)을 참조하세요.

이 페이지의 curl 및 PowerShell 샘플은 R4 FHIR 저장소와 호환되며 DSTU2 또는 STU3 FHIR 저장소를 사용하는 경우 작동되지 않을 수 있습니다. DSTU2 또는 STU3 FHIR 저장소를 사용하는 경우 사용 중인 FHIR 버전에 대한 샘플을 변환하는 방법을 공식 FHIR 문서에서 참조하세요.

Go, 자바, Node.js, Python 샘플은 STU3 FHIR 저장소에서 작동합니다.

FHIR 리소스 만들기

FHIR 리소스를 만들려면 먼저 FHIR 저장소를 만들어야 합니다.

curl, PowerShell, Python 샘플은 다음과 같은 FHIR 리소스를 만드는 방법을 보여줍니다.

  1. 환자(DSTU2, STU3, R4) 리소스
  2. 환자의 Encounter(DSTU2, STU3, R4) 리소스
  3. Encounter의 관찰(DSTU2, STU3, R4) 리소스

다른 모든 언어의 샘플은 일반 FHIR 리소스를 만드는 방법을 보여줍니다.

자세한 내용은 projects.locations.datasets.fhirStores.fhir.create를 참조하세요.

다음 curl 및 PowerShell 샘플은 R4 FHIR 저장소에서 작동합니다. Go, 자바, Node.js, Python 샘플은 STU3 FHIR 저장소에서 작동합니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트의 ID
  • LOCATION: 데이터 세트 위치
  • DATASET_ID: FHIR 저장소의 상위 데이터 세트
  • FHIR_STORE_ID: FHIR 저장소 ID

JSON 요청 본문:

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

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장합니다. 터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

cat > request.json << 'EOF'
{
  "name": [
    {
      "use": "official",
      "family": "Smith",
      "given": [
        "Darcy"
      ]
    }
  ],
  "gender": "female",
  "birthDate": "1970-01-01",
  "resourceType": "Patient"
}
EOF

그런 후 다음 명령어를 실행하여 REST 요청을 전송합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/fhir+json" \
-d @request.json \
"https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient"

PowerShell

요청 본문을 request.json 파일에 저장합니다. 터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

@'
{
  "name": [
    {
      "use": "official",
      "family": "Smith",
      "given": [
        "Darcy"
      ]
    }
  ],
  "gender": "female",
  "birthDate": "1970-01-01",
  "resourceType": "Patient"
}
'@  | Out-File -FilePath request.json -Encoding utf8

그런 후 다음 명령어를 실행하여 REST 요청을 전송합니다.

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/fhir+json" `
-InFile request.json `
-Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.

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: %w", 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: %w", 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: %w", err)
	}
	defer resp.Body.Close()

	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("could not read response: %w", 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.gson.GsonFactory;
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 GsonFactory();
  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/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
  headers: {'Content-Type': 'application/fhir+json'},
});

async function createFhirResource() {
  // 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',
  };

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

# Imports the types Dict and Any for runtime type hints.
from typing import Any, Dict  # noqa: E402

def create_patient(
    project_id: str,
    location: str,
    dataset_id: str,
    fhir_store_id: str,
) -> Dict[str, Any]:
    """Creates a new Patient resource in a FHIR store.

    See
    https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample.
    See
    https://googleapis.github.io/google-api-python-client/docs/dyn/healthcare_v1.projects.locations.datasets.fhirStores.fhir.html#create
    for the Python API reference.

    Args:
      project_id: The project ID or project number of the Cloud project you want
        to use.
      location: The name of the parent dataset's location.
      dataset_id: The name of the parent dataset.
      fhir_store_id: The name of the FHIR store that holds the Patient resource.

    Returns:
      A dict representing the created Patient resource.
    """
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    api_version = "v1"
    service_name = "healthcare"

    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'
    # location = 'us-central1'
    # dataset_id = 'my-dataset'
    # fhir_store_id = 'my-fhir-store'
    fhir_store_parent = (
        f"projects/{project_id}/locations/{location}/datasets/{dataset_id}"
    )
    fhir_store_name = f"{fhir_store_parent}/fhirStores/{fhir_store_id}"

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

    request = (
        client.projects()
        .locations()
        .datasets()
        .fhirStores()
        .fhir()
        .create(parent=fhir_store_name, type="Patient", body=patient_body)
    )
    # Sets required application/fhir+json header on the googleapiclient.http.HttpRequest.
    request.headers["content-type"] = "application/fhir+json;charset=utf-8"
    response = request.execute()

    print(f"Created Patient resource with ID {response['id']}")
    return response

환자 리소스를 만든 후 환자와 전문의 사이의 상호작용을 설명하는 Encounter 리소스를 만듭니다.

PATIENT_ID 필드에서 환자 리소스를 만들 때 서버에서 반환한 응답의 ID를 대체합니다.

다음 curl 및 PowerShell 샘플은 R4 FHIR 저장소에서 작동합니다. Python 샘플은 STU3 FHIR 저장소에서 작동합니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트의 ID
  • LOCATION: 데이터 세트 위치
  • DATASET_ID: FHIR 저장소의 상위 데이터 세트
  • FHIR_STORE_ID: FHIR 저장소 ID
  • PATIENT_ID: 환자 리소스를 만들 때 서버에서 반환한 응답

JSON 요청 본문:

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

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장합니다. 터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

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

그런 후 다음 명령어를 실행하여 REST 요청을 전송합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/fhir+json" \
-d @request.json \
"https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Encounter"

PowerShell

요청 본문을 request.json 파일에 저장합니다. 터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

@'
{
  "status": "finished",
  "class": {
    "system": "http://hl7.org/fhir/v3/ActCode",
    "code": "IMP",
    "display": "inpatient encounter"
  },
  "reasonCode": [
    {
      "text": "The patient had an abnormal heart rate. She was concerned about this."
    }
  ],
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "resourceType": "Encounter"
}
'@  | Out-File -FilePath request.json -Encoding utf8

그런 후 다음 명령어를 실행하여 REST 요청을 전송합니다.

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/fhir+json" `
-InFile request.json `
-Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Encounter" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.

Python

이 샘플을 사용해 보기 전에 Cloud Healthcare API 빠른 시작: 클라이언트 라이브러리 사용Python 설정 안내를 따르세요. 자세한 내용은 Cloud Healthcare API Python API 참고 문서를 확인하세요.

Cloud Healthcare API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

# Imports the types Dict and Any for runtime type hints.
from typing import Any, Dict  # noqa: E402

def create_encounter(
    project_id: str,
    location: str,
    dataset_id: str,
    fhir_store_id: str,
    patient_id: str,
) -> Dict[str, Any]:
    """Creates a new Encounter resource in a FHIR store that references a Patient resource.

    See
    https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample.
    See
    https://googleapis.github.io/google-api-python-client/docs/dyn/healthcare_v1.projects.locations.datasets.fhirStores.fhir.html#create
    for the Python API reference.

    Args:
      project_id: The project ID or project number of the Cloud project you want
        to use.
      location: The name of the parent dataset's location.
      dataset_id: The name of the parent dataset.
      fhir_store_id: The name of the FHIR store.
      patient_id: The "logical id" of the referenced Patient resource. The ID is
        assigned by the server.

    Returns:
      A dict representing the created Encounter resource.
    """
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    api_version = "v1"
    service_name = "healthcare"

    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'
    # location = 'us-central1'
    # dataset_id = 'my-dataset'
    # fhir_store_id = 'my-fhir-store'
    # patient_id = 'b682d-0e-4843-a4a9-78c9ac64'  # replace with the associated Patient resource's ID
    fhir_store_parent = (
        f"projects/{project_id}/locations/{location}/datasets/{dataset_id}"
    )
    fhir_store_name = f"{fhir_store_parent}/fhirStores/{fhir_store_id}"

    encounter_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": f"Patient/{patient_id}"},
        "resourceType": "Encounter",
    }

    request = (
        client.projects()
        .locations()
        .datasets()
        .fhirStores()
        .fhir()
        .create(parent=fhir_store_name, type="Encounter", body=encounter_body)
    )
    # Sets required application/fhir+json header on the googleapiclient.http.HttpRequest.
    request.headers["content-type"] = "application/fhir+json;charset=utf-8"
    response = request.execute()
    print(f"Created Encounter resource with ID {response['id']}")

    return response

Encounter 리소스를 만든 후 Encounter 리소스와 연관된 관찰 리소스를 만듭니다. 관찰 리소스는 환자의 분당 심박수(BPM) 측정값을 제공합니다(bpm80).

다음 curl 및 PowerShell 샘플은 R4 FHIR 저장소에서 작동합니다. Python 샘플은 STU3 FHIR 저장소에서 작동합니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트의 ID
  • LOCATION: 데이터 세트 위치
  • DATASET_ID: FHIR 저장소의 상위 데이터 세트
  • FHIR_STORE_ID: FHIR 저장소 ID
  • PATIENT_ID: 환자 리소스를 만들 때 서버에서 반환된 응답에 있는 ID
  • ENCOUNTER_ID: Encounter 리소스를 만들 때 서버에서 반환된 응답에 있는 ID

JSON 요청 본문:

{
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "identifier": [
    {
      "system": "my-code-system",
      "value": "ABC-12345"
    }
  ],
  "code": {
    "coding": [
      {
        "system": "http://loinc.org",
        "code": "8867-4",
        "display": "Heart rate"
      }
    ]
  },
  "valueQuantity": {
    "value": 80,
    "unit": "bpm"
  },
  "encounter": {
    "reference": "Encounter/ENCOUNTER_ID"
  }
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장합니다. 터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

cat > request.json << 'EOF'
{
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "identifier": [
    {
      "system": "my-code-system",
      "value": "ABC-12345"
    }
  ],
  "code": {
    "coding": [
      {
        "system": "http://loinc.org",
        "code": "8867-4",
        "display": "Heart rate"
      }
    ]
  },
  "valueQuantity": {
    "value": 80,
    "unit": "bpm"
  },
  "encounter": {
    "reference": "Encounter/ENCOUNTER_ID"
  }
}
EOF

그런 후 다음 명령어를 실행하여 REST 요청을 전송합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/fhir+json" \
-d @request.json \
"https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation"

PowerShell

요청 본문을 request.json 파일에 저장합니다. 터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

@'
{
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "identifier": [
    {
      "system": "my-code-system",
      "value": "ABC-12345"
    }
  ],
  "code": {
    "coding": [
      {
        "system": "http://loinc.org",
        "code": "8867-4",
        "display": "Heart rate"
      }
    ]
  },
  "valueQuantity": {
    "value": 80,
    "unit": "bpm"
  },
  "encounter": {
    "reference": "Encounter/ENCOUNTER_ID"
  }
}
'@  | Out-File -FilePath request.json -Encoding utf8

그런 후 다음 명령어를 실행하여 REST 요청을 전송합니다.

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/fhir+json" `
-InFile request.json `
-Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.

Python

이 샘플을 사용해 보기 전에 Cloud Healthcare API 빠른 시작: 클라이언트 라이브러리 사용Python 설정 안내를 따르세요. 자세한 내용은 Cloud Healthcare API Python API 참고 문서를 확인하세요.

Cloud Healthcare API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

# Imports the types Dict and Any for runtime type hints.
from typing import Any, Dict  # noqa: E402

def create_observation(
    project_id: str,
    location: str,
    dataset_id: str,
    fhir_store_id: str,
    patient_id: str,
    encounter_id: str,
) -> Dict[str, Any]:
    """Creates a new Observation resource in a FHIR store that references an Encounter and Patient resource.

    See
    https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample.
    See
    https://googleapis.github.io/google-api-python-client/docs/dyn/healthcare_v1.projects.locations.datasets.fhirStores.fhir.html#create
    for the Python API reference.

    Args:
      project_id: The project ID or project number of the Cloud project you want
        to use.
      location: The name of the parent dataset's location.
      dataset_id: The name of the parent dataset.
      fhir_store_id: The name of the FHIR store.
      patient_id: The "logical id" of the referenced Patient resource. The ID is
        assigned by the server.
      encounter_id: The "logical id" of the referenced Encounter resource. The ID
        is assigned by the server.

    Returns:
      A dict representing the created Observation resource.
    """
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    api_version = "v1"
    service_name = "healthcare"

    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'
    # location = 'us-central1'
    # dataset_id = 'my-dataset'
    # fhir_store_id = 'my-fhir-store'
    # patient_id = 'b682d-0e-4843-a4a9-78c9ac64'  # replace with the associated Patient resource's ID
    # encounter_id = 'a7602f-ffba-470a-a5c1-103f993c6  # replace with the associated Encounter resource's ID
    fhir_store_parent = (
        f"projects/{project_id}/locations/{location}/datasets/{dataset_id}"
    )
    fhir_observation_path = (
        f"{fhir_store_parent}/fhirStores/{fhir_store_id}/fhir/Observation"
    )

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

    request = (
        client.projects()
        .locations()
        .datasets()
        .fhirStores()
        .fhir()
        .create(
            parent=fhir_observation_path,
            type="Observation",
            body=observation_body,
        )
    )
    # Sets required application/fhir+json header on the googleapiclient.http.HttpRequest.
    request.headers["content-type"] = "application/fhir+json;charset=utf-8"
    response = request.execute()
    print(f"Created Observation resource with ID {response['id']}")

    return response

조건부로 FHIR 리소스 만들기

다음 curl 샘플은 projects.locations.datasets.fhirStores.fhir.create 메서드를 사용하여 FHIR 리소스를 조건부로 만드는 방법을 보여줍니다. 이 메서드는 FHIR 조건부 create 상호작용(DSTU2, STU3, R4)을 구현합니다.

조건부 생성을 사용하여 FHIR 리소스가 중복되지 않도록 합니다. 예를 들어 FHIR 서버의 각 환자 리소스에는 의료 레코드 번호(MRN)와 같은 고유 식별자가 있습니다. 새 환자 리소스를 만들고 동일한 MRN이 포함된 환자 리소스가 아직 없는지 확인하려면 조건부로 새 리소스를 만듭니다. Cloud Healthcare API는 검색어와 일치하는 항목이 없는 경우에만 새 리소스를 만듭니다.

서버의 응답은 검색어와 일치하는 리소스 수에 따라 다릅니다.

일치 HTTP 응답 코드 동작
0 200 OK 새 리소스를 만듭니다.
1개 200 OK 새 리소스를 만들지 않습니다.
2개 이상 412 Precondition Failed 새 리소스를 만들지 않고 "search criteria are not selective enough" 오류를 반환합니다.

조건부 create 상호작용 대신 create 상호작용을 사용하려면 요청에 FHIR 검색 쿼리가 포함된 If-None-Exist HTTP 헤더를 지정합니다.

If-None-Exist: FHIR_SEARCH_QUERY

Cloud Healthcare API v1에서 조건부 작업은 FHIR 리소스 유형에 대해 존재할 경우 identifier 검색 매개변수를 배타적으로 사용하여 조건부 검색어와 일치하는 FHIR 리소스를 확인합니다.

REST

다음 샘플은 If-None-Exist: identifier=my-code-system|ABC-12345 HTTP 헤더를 사용하여 관찰 리소스를 만드는 방법을 보여줍니다. Cloud Healthcare API는 identifier=my-code-system|ABC-12345 쿼리와 일치하는 기존 관찰 리소스가 없는 경우에만 리소스를 만듭니다.

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/fhir+json" \
  -H "If-None-Exist: identifier=my-code-system|ABC-12345" \
  -d @request.json \
  "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation"

다음 샘플 출력은 의도적으로 실패 요청을 보여줍니다. 성공적인 요청의 응답을 보려면 FHIR 리소스 만들기를 참조하세요.

여러 관찰 리소스가 쿼리와 일치하면 Cloud Healthcare API는 다음 응답을 반환하고 조건부 만들기 요청은 실패합니다.

{
  "issue": [
    {
      "code": "conflict",
      "details": {
        "text": "ambiguous_query"
      },
      "diagnostics": "search criteria are not selective enough",
      "severity": "error"
    }
  ],
  "resourceType": "OperationOutcome"
}

FHIR 리소스 업데이트

다음 샘플은 projects.locations.datasets.fhirStores.fhir.update 메서드를 사용하여 FHIR 리소스를 업데이트하는 방법을 보여줍니다. 이 메서드는 FHIR 표준 업데이트 상호작용(DSTU2, STU3, R4)을 구현합니다.

리소스를 업데이트하면 리소스의 전체 콘텐츠가 업데이트됩니다. 이는 리소스의 일부만 업데이트하는 리소스 패치와 대조됩니다.

FHIR 저장소에 enableUpdateCreate가 설정되어 있는 경우 요청은 리소스가 있으면 리소스를 업데이트하고 리소스가 없으면 요청을 지정한 ID를 사용하여 삽입하는 upsert(업데이트 또는 삽입)로 처리됩니다.

요청 본문에는 JSON 인코딩 FHIR 리소스가 포함되어야 하며 요청 헤더에는 Content-Type: application/fhir+json이 포함되어야 합니다. 리소스에는 요청의 REST 경로에 있는 ID와 동일한 값을 가진 id 요소가 포함되어야 합니다.

다음 curl 및 PowerShell 샘플은 R4 FHIR 저장소에서 작동합니다. Go, 자바, Node.js, Python 샘플은 STU3 FHIR 저장소에서 작동합니다.

REST

다음 샘플은 관찰 리소스에서 분당 심박수(BPM)를 업데이트하는 방법을 보여줍니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트의 ID
  • LOCATION: 데이터 세트 위치
  • DATASET_ID: FHIR 저장소의 상위 데이터 세트
  • FHIR_STORE_ID: FHIR 저장소 ID
  • OBSERVATION_ID: 관찰 리소스 ID
  • PATIENT_ID: 환자 리소스 ID
  • ENCOUNTER_ID: Encounter 리소스 ID
  • BPM_VALUE: 업데이트된 관찰 리소스에 있는 분당 심박수(BPM) 값

JSON 요청 본문:

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

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장합니다. 터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

cat > request.json << 'EOF'
{
  "resourceType": "Observation",
  "id": "OBSERVATION_ID",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "identifier": [
    {
      "system": "my-code-system",
      "value": "ABC-12345"
    }
  ],
  "code": {
    "coding": [
      {
        "system": "http://loinc.org",
        "code": "8867-4",
        "display": "Heart rate"
      }
    ]
  },
  "valueQuantity": {
    "value": BPM_VALUE,
    "unit": "bpm"
  },
  "encounter": {
    "reference": "Encounter/ENCOUNTER_ID"
  }
}
EOF

그런 후 다음 명령어를 실행하여 REST 요청을 전송합니다.

curl -X PUT \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation/OBSERVATION_ID"

PowerShell

요청 본문을 request.json 파일에 저장합니다. 터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

@'
{
  "resourceType": "Observation",
  "id": "OBSERVATION_ID",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "identifier": [
    {
      "system": "my-code-system",
      "value": "ABC-12345"
    }
  ],
  "code": {
    "coding": [
      {
        "system": "http://loinc.org",
        "code": "8867-4",
        "display": "Heart rate"
      }
    ]
  },
  "valueQuantity": {
    "value": BPM_VALUE,
    "unit": "bpm"
  },
  "encounter": {
    "reference": "Encounter/ENCOUNTER_ID"
  }
}
'@  | Out-File -FilePath request.json -Encoding utf8

그런 후 다음 명령어를 실행하여 REST 요청을 전송합니다.

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

Invoke-WebRequest `
-Method PUT `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation/OBSERVATION_ID" | Select-Object -Expand Content

API 탐색기

요청 본문을 복사하고 메서드 참조 페이지를 엽니다. 페이지 오른쪽에 API 탐색기 패널이 열립니다. 이 도구를 사용하여 요청을 보낼 수 있습니다. 요청 본문을 이 도구에 붙여넣고 다른 필수 필드를 입력한 후 실행을 클릭합니다.

다음과 비슷한 JSON 응답이 표시됩니다.

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: %w", 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: %w", 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: %w", err)
	}
	defer resp.Body.Close()

	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("could not read response: %w", 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/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
  headers: {'Content-Type': 'application/fhir+json'},
});

const updateFhirResource = async () => {
  // 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

# Imports the types Dict and Any for runtime type hints.
from typing import Any, Dict  # noqa: E402

def update_resource(
    project_id: str,
    location: str,
    dataset_id: str,
    fhir_store_id: str,
    resource_type: str,
    resource_id: str,
) -> Dict[str, Any]:
    """Updates the entire contents of a FHIR resource.

    Creates a new current version if the resource already exists, or creates
    a new resource with an initial version if no resource already exists with
    the provided ID.

    See
    https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample.
    See
    https://googleapis.github.io/google-api-python-client/docs/dyn/healthcare_v1.projects.locations.datasets.fhirStores.fhir.html#update
    for the Python API reference.

    Args:
      project_id: The project ID or project number of the Cloud project you want
        to use.
      location: The name of the parent dataset's location.
      dataset_id: The name of the parent dataset.
      fhir_store_id: The name of the FHIR store.
      resource_type: The type of the FHIR resource.
      resource_id: The "logical id" of the resource. The ID is assigned by the
        server.

    Returns:
      A dict representing the updated FHIR resource.
    """
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    api_version = "v1"
    service_name = "healthcare"

    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'
    # location = 'us-central1'
    # dataset_id = 'my-dataset'
    # fhir_store_id = 'my-fhir-store'
    # resource_type = 'Patient'
    # resource_id = 'b682d-0e-4843-a4a9-78c9ac64'
    fhir_store_parent = (
        f"projects/{project_id}/locations/{location}/datasets/{dataset_id}"
    )
    fhir_resource_path = f"{fhir_store_parent}/fhirStores/{fhir_store_id}/fhir/{resource_type}/{resource_id}"

    # The following sample body works with a Patient resource and isn't 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.
    patient_body = {
        "resourceType": resource_type,
        "active": True,
        "id": resource_id,
    }

    request = (
        client.projects()
        .locations()
        .datasets()
        .fhirStores()
        .fhir()
        .update(name=fhir_resource_path, body=patient_body)
    )
    # Sets required application/fhir+json header on the googleapiclient.http.HttpRequest.
    request.headers["content-type"] = "application/fhir+json;charset=utf-8"
    response = request.execute()

    print(
        f"Updated {resource_type} resource with ID {resource_id}:\n"
        f" {json.dumps(response, indent=2)}"
    )

    return response

FHIR 리소스 조건부 업데이트

다음 샘플은 ID로 리소스를 식별하는 대신 projects.locations.datasets.fhirStores.fhir.conditionalUpdate 메서드를 호출하여 검색어와 일치하는 FHIR 리소스를 업데이트하는 방법을 보여줍니다. 이 메서드는 FHIR 표준 조건부 업데이트 상호작용(DSTU2, STU3, R4)을 구현합니다.

조건부 업데이트는 한 번에 하나의 FHIR 리소스에만 적용할 수 있습니다.

서버에서 반환된 응답은 검색 기준을 기준으로 일치하는 항목 수에 따라 달라집니다.

  • 1개 일치: 리소스가 성공적으로 업데이트되거나 오류가 반환됩니다.
  • 1개 초과 일치: 요청이 412 Precondition Failed 오류를 반환합니다.
  • id와 일치하는 제로 일치: 검색 기준이 제로 일치를 확인하고 제공된 요청 본문에 id가 포함되며 FHIR 저장소에서 enableUpdateCreatetrue로 설정하면 FHIR 리소스가 요청 본문의 id를 사용하여 생성됩니다.
  • id가 없는 제로 일치: 검색 기준이 제로 일치를 확인하고 제공된 요청 본문에 id가 없는 경우 FHIR 리소스가 projects.locations.datasets.fhirStores.fhir.create를 사용하여 리소스를 만든 경우와 유사한 서버 할당 ID를 사용하여 리소스를 만듭니다.

요청 본문에는 JSON 인코딩 FHIR 리소스가 포함되어야 하며 요청 헤더에는 Content-Type: application/fhir+json이 포함되어야 합니다.

Cloud Healthcare API v1에서 조건부 작업은 FHIR 리소스 유형에 대해 존재할 경우 identifier 검색 매개변수를 배타적으로 사용하여 조건부 검색어와 일치하는 FHIR 리소스를 확인합니다.

REST

다음 샘플은 curl 및 PowerShell을 사용하는 PUT 요청을 보내 관찰 식별자(my-code-systemABC-12345)를 사용하는 관찰 리소스를 수정하는 방법을 보여줍니다. 관찰은 환자의 분당 심박수(BPM) 측정값을 제공합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트의 ID
  • LOCATION: 데이터 세트 위치
  • DATASET_ID: FHIR 저장소의 상위 데이터 세트
  • FHIR_STORE_ID: FHIR 저장소 ID
  • PATIENT_ID: 환자 리소스 ID
  • ENCOUNTER_ID: Encounter 리소스 ID
  • BPM_VALUE: 관찰 리소스에 있는 분당 심박수(BPM) 값

JSON 요청 본문:

{
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "identifier": [
    {
      "system": "my-code-system",
      "value": "ABC-12345"
    }
  ],
  "code": {
    "coding": [
      {
        "system": "http://loinc.org",
        "code": "8867-4",
        "display": "Heart rate"
      }
    ]
  },
  "valueQuantity": {
    "value": BPM_VALUE,
    "unit": "bpm"
  },
  "encounter": {
    "reference": "Encounter/ENCOUNTER_ID"
  }
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장합니다. 터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

cat > request.json << 'EOF'
{
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "identifier": [
    {
      "system": "my-code-system",
      "value": "ABC-12345"
    }
  ],
  "code": {
    "coding": [
      {
        "system": "http://loinc.org",
        "code": "8867-4",
        "display": "Heart rate"
      }
    ]
  },
  "valueQuantity": {
    "value": BPM_VALUE,
    "unit": "bpm"
  },
  "encounter": {
    "reference": "Encounter/ENCOUNTER_ID"
  }
}
EOF

그런 후 다음 명령어를 실행하여 REST 요청을 전송합니다.

curl -X PUT \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation?identifier=my-code-system|ABC-12345"

PowerShell

요청 본문을 request.json 파일에 저장합니다. 터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

@'
{
  "resourceType": "Observation",
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "identifier": [
    {
      "system": "my-code-system",
      "value": "ABC-12345"
    }
  ],
  "code": {
    "coding": [
      {
        "system": "http://loinc.org",
        "code": "8867-4",
        "display": "Heart rate"
      }
    ]
  },
  "valueQuantity": {
    "value": BPM_VALUE,
    "unit": "bpm"
  },
  "encounter": {
    "reference": "Encounter/ENCOUNTER_ID"
  }
}
'@  | Out-File -FilePath request.json -Encoding utf8

그런 후 다음 명령어를 실행하여 REST 요청을 전송합니다.

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

Invoke-WebRequest `
-Method PUT `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation?identifier=my-code-system|ABC-12345" | Select-Object -Expand Content

API 탐색기

요청 본문을 복사하고 메서드 참조 페이지를 엽니다. 페이지 오른쪽에 API 탐색기 패널이 열립니다. 이 도구를 사용하여 요청을 보낼 수 있습니다. 요청 본문을 이 도구에 붙여넣고 다른 필수 필드를 입력한 후 실행을 클릭합니다.

다음과 비슷한 JSON 응답이 표시됩니다.

FHIR 리소스 패치

다음 샘플은 projects.locations.datasets.fhirStores.fhir.patch 메서드를 호출하여 FHIR 리소스를 패치하는 방법을 보여줍니다. 이 메서드는 FHIR 표준 패치 상호작용(DSTU2, STU3, R4)을 구현합니다.

리소스를 패치할 때는 JSON 패치 문서에 지정된 작업을 적용하여 리소스의 일부를 업데이트합니다.

요청에는 JSON 패치 문서가 포함되어야 하며 요청 헤더에는 Content-Type: application/json-patch+json이 포함되어야 합니다.

다음 샘플은 관찰 리소스를 패치하는 방법을 보여줍니다. 환자의 분당 심박수(BPM) 관찰은 replace 패치 작업을 사용하여 업데이트됩니다.

다음 curl 및 PowerShell 샘플은 R4 FHIR 저장소에서 작동합니다. Go, 자바, Node.js, Python 샘플은 STU3 FHIR 저장소에서 작동합니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트의 ID
  • LOCATION: 데이터 세트 위치
  • DATASET_ID: FHIR 저장소의 상위 데이터 세트
  • FHIR_STORE_ID: FHIR 저장소 ID
  • OBSERVATION_ID: 관찰 리소스 ID
  • BPM_VALUE: 패치된 관찰 리소스에 있는 분당 심박수(BPM) 값

JSON 요청 본문:

[
  {
    "op": "replace",
    "path": "/valueQuantity/value",
    "value": BPM_VALUE
  }
]

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장합니다. 터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

cat > request.json << 'EOF'
[
  {
    "op": "replace",
    "path": "/valueQuantity/value",
    "value": BPM_VALUE
  }
]
EOF

그런 후 다음 명령어를 실행하여 REST 요청을 전송합니다.

curl -X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json-patch+json" \
-d @request.json \
"https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation/OBSERVATION_ID"

PowerShell

요청 본문을 request.json 파일에 저장합니다. 터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

@'
[
  {
    "op": "replace",
    "path": "/valueQuantity/value",
    "value": BPM_VALUE
  }
]
'@  | Out-File -FilePath request.json -Encoding utf8

그런 후 다음 명령어를 실행하여 REST 요청을 전송합니다.

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

Invoke-WebRequest `
-Method PATCH `
-Headers $headers `
-ContentType: "application/json-patch+json" `
-InFile request.json `
-Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation/OBSERVATION_ID" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.

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: %w", 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: %w", 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: %w", err)
	}
	defer resp.Body.Close()

	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("could not read response: %w", 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.gson.GsonFactory;
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 GsonFactory();
  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/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
  headers: {'Content-Type': 'application/json-patch+json'},
});

async function patchFhirResource() {
  // TODO(developer): replace patchOptions with your desired JSON patch body
  const patchOptions = [{op: 'replace', path: '/active', value: false}];

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

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

patchFhirResource();

Python

# Imports the types Dict and Any for runtime type hints.
from typing import Any, Dict  # noqa: E402

def patch_resource(
    project_id: str,
    location: str,
    dataset_id: str,
    fhir_store_id: str,
    resource_type: str,
    resource_id: str,
) -> Dict[str, Any]:
    """Updates part of an existing FHIR resource by applying the operations specified in a [JSON Patch](http://jsonpatch.com/) document.

    See
    https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample.
    See
    https://googleapis.github.io/google-api-python-client/docs/dyn/healthcare_v1.projects.locations.datasets.fhirStores.fhir.html#patch
    for the Python API reference.

    Args:
      project_id: The project ID or project number of the Cloud project you want
        to use.
      location: The name of the parent dataset's location.
      dataset_id: The name of the parent dataset.
      fhir_store_id: The name of the FHIR store.
      resource_type: The type of the FHIR resource.
      resource_id: The "logical id" of the resource. The ID is assigned by the
        server.

    Returns:
      A dict representing the patched FHIR resource.
    """
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    api_version = "v1"
    service_name = "healthcare"

    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'
    # location = 'us-central1'
    # dataset_id = 'my-dataset'
    # fhir_store_id = 'my-fhir-store'
    # resource_type = 'Patient'
    # resource_id = 'b682d-0e-4843-a4a9-78c9ac64'
    fhir_store_parent = (
        f"projects/{project_id}/locations/{location}/datasets/{dataset_id}"
    )
    fhir_resource_path = f"{fhir_store_parent}/fhirStores/{fhir_store_id}/fhir/{resource_type}/{resource_id}"

    # The following sample body works with a Patient resource and isn't 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.
    patient_body = [{"op": "replace", "path": "/active", "value": False}]

    request = (
        client.projects()
        .locations()
        .datasets()
        .fhirStores()
        .fhir()
        .patch(name=fhir_resource_path, body=patient_body)
    )

    # Sets required application/json-patch+json header.
    # See https://tools.ietf.org/html/rfc6902 for more information.
    request.headers["content-type"] = "application/json-patch+json"

    response = request.execute()

    print(
        f"Patched {resource_type} resource with ID {resource_id}:\n"
        f" {json.dumps(response, indent=2)}"
    )

    return response

FHIR 번들에서 PATCH 요청 실행

FHIR 번들에 PATCH 요청을 지정할 수 있습니다(FHIR R4만 해당). FHIR 번들에서 PATCH 요청을 실행하면 FHIR 리소스마다 개별 패치 요청을 실행할 필요 없이 여러 FHIR 리소스를 한 번에 패치할 수 있습니다.

번들에서 PATCH 요청을 수행하려면 요청의 resource 객체에 다음 정보를 지정합니다.

  • Binary으로 설정된 resourceType 필드
  • application/json-patch+json으로 설정된 contentType 필드
  • base64로 인코딩된 패치 본문

resource 객체가 다음과 같이 표시되는지 확인합니다.

"resource": {
  "resourceType": "Binary",
  "contentType": "application/json-patch+json",
  "data": "WyB7ICJvcCI6ICJyZXBsYWNlIiwgInBhdGgiOiAiL2JpcnRoRGF0ZSIsICJ2YWx1ZSI6ICIxOTkwLTAxLTAxIiB9IF0K"
}

다음에서는 data 필드에서 base64로 인코딩된 패치 본문을 보여줍니다.

[
  {
    "op": "replace",
    "path": "/birthdate",
    "value": "1990-01-01"
  }
]

다음 샘플은 번들에서 PATCH 요청을 사용하여 FHIR 리소스 만들기에서 생성한 환자 리소스를 패치하여 birthDate 값이 1990-01-01이 되도록하는 하는 방법을 보여줍니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID
  • LOCATION: 상위 데이터 세트의 위치
  • DATASET_ID: FHIR 저장소의 상위 데이터 세트
  • FHIR_STORE_ID: FHIR 저장소 ID
  • PATIENT_ID: 기존 환자 리소스의 ID

JSON 요청 본문:

{
  "type": "transaction",
  "resourceType": "Bundle",
  "entry": [
    {
      "request": {
        "method": "PATCH",
        "url": "Patient/PATIENT_ID"
      },
      "resource": {
        "resourceType": "Binary",
        "contentType": "application/json-patch+json",
        "data": "WyB7ICJvcCI6ICJyZXBsYWNlIiwgInBhdGgiOiAiL2JpcnRoRGF0ZSIsICJ2YWx1ZSI6ICIxOTkwLTAxLTAxIiB9IF0K"
      }
    }
  ]
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장합니다. 터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

cat > request.json << 'EOF'
{
  "type": "transaction",
  "resourceType": "Bundle",
  "entry": [
    {
      "request": {
        "method": "PATCH",
        "url": "Patient/PATIENT_ID"
      },
      "resource": {
        "resourceType": "Binary",
        "contentType": "application/json-patch+json",
        "data": "WyB7ICJvcCI6ICJyZXBsYWNlIiwgInBhdGgiOiAiL2JpcnRoRGF0ZSIsICJ2YWx1ZSI6ICIxOTkwLTAxLTAxIiB9IF0K"
      }
    }
  ]
}
EOF

그런 후 다음 명령어를 실행하여 REST 요청을 전송합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/fhir+json" \
-d @request.json \
"https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir"

PowerShell

요청 본문을 request.json 파일에 저장합니다. 터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

@'
{
  "type": "transaction",
  "resourceType": "Bundle",
  "entry": [
    {
      "request": {
        "method": "PATCH",
        "url": "Patient/PATIENT_ID"
      },
      "resource": {
        "resourceType": "Binary",
        "contentType": "application/json-patch+json",
        "data": "WyB7ICJvcCI6ICJyZXBsYWNlIiwgInBhdGgiOiAiL2JpcnRoRGF0ZSIsICJ2YWx1ZSI6ICIxOTkwLTAxLTAxIiB9IF0K"
      }
    }
  ]
}
'@  | Out-File -FilePath request.json -Encoding utf8

그런 후 다음 명령어를 실행하여 REST 요청을 전송합니다.

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/fhir+json" `
-InFile request.json `
-Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.

FHIR 리소스 조건부 패치

다음 샘플은 ID로 리소스를 식별하는 대신 projects.locations.datasets.fhirStores.fhir.conditionalPatch 메서드를 호출하여 검색어와 일치하는 FHIR 리소스를 패치하는 방법을 보여줍니다. 이 메서드는 FHIR 표준 조건부 패치 상호작용(DSTU2, STU3, R4)을 구현합니다.

조건부 패치는 한 번에 하나의 리소스에만 적용할 수 있습니다. 검색 기준에 일치하는 항목이 한 개를 초과하면 요청에서 412 Precondition Failed 오류를 반환합니다.

Cloud Healthcare API v1에서 조건부 작업은 FHIR 리소스 유형에 대해 존재할 경우 identifier 검색 매개변수를 배타적으로 사용하여 조건부 검색어와 일치하는 FHIR 리소스를 확인합니다.

REST

다음 샘플은 관찰 식별자가 my-code-system에서 ABC-12345인 경우 curl 및 PowerShell을 사용해 PATCH 요청을 전송하여 관찰 리소스를 수정하는 방법을 보여줍니다. 환자의 분당 심박수(BPM) 관찰은 replace 패치 작업을 사용하여 업데이트됩니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트의 ID
  • LOCATION: 데이터 세트 위치
  • DATASET_ID: FHIR 저장소의 상위 데이터 세트
  • FHIR_STORE_ID: FHIR 저장소 ID
  • BPM_VALUE: 관찰 리소스에 있는 분당 심박수(BPM) 값

JSON 요청 본문:

[
  {
    "op": "replace",
    "path": "/valueQuantity/value",
    "value": BPM_VALUE
  }
]

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장합니다. 터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

cat > request.json << 'EOF'
[
  {
    "op": "replace",
    "path": "/valueQuantity/value",
    "value": BPM_VALUE
  }
]
EOF

그런 후 다음 명령어를 실행하여 REST 요청을 전송합니다.

curl -X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json-patch+json" \
-d @request.json \
"https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation?identifier=my-code-system|ABC-12345"

PowerShell

요청 본문을 request.json 파일에 저장합니다. 터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

@'
[
  {
    "op": "replace",
    "path": "/valueQuantity/value",
    "value": BPM_VALUE
  }
]
'@  | Out-File -FilePath request.json -Encoding utf8

그런 후 다음 명령어를 실행하여 REST 요청을 전송합니다.

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

Invoke-WebRequest `
-Method PATCH `
-Headers $headers `
-ContentType: "application/json-patch+json" `
-InFile request.json `
-Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation?identifier=my-code-system|ABC-12345" | Select-Object -Expand Content

API 탐색기

요청 본문을 복사하고 메서드 참조 페이지를 엽니다. 페이지 오른쪽에 API 탐색기 패널이 열립니다. 이 도구를 사용하여 요청을 보낼 수 있습니다. 요청 본문을 이 도구에 붙여넣고 다른 필수 필드를 입력한 후 실행을 클릭합니다.

다음과 비슷한 JSON 응답이 표시됩니다.

FHIR 리소스 가져오기

다음 샘플은 projects.locations.datasets.fhirStores.fhir.read 메서드를 사용하여 FHIR 리소스의 콘텐츠를 가져오는 방법을 보여줍니다.

다음 curl 및 PowerShell 샘플은 R4 FHIR 저장소에서 작동합니다. Go, 자바, Node.js, Python 샘플은 STU3 FHIR 저장소에서 작동합니다.

콘솔

FHIR 리소스의 콘텐츠를 가져오려면 다음 단계별 안내를 따르세요.

  1. Google Cloud 콘솔에서 FHIR 뷰어 페이지로 이동합니다.

    FHIR 뷰어로 이동

  2. FHIR 저장소 드롭다운 목록에서 데이터 세트를 선택한 다음 데이터 세트의 FHIR 저장소를 선택합니다.

  3. 리소스 유형 목록을 필터링하려면 표시할 리소스 유형을 검색하세요.

  4. 리소스 유형 필드를 클릭합니다.

  5. 표시되는 속성 드롭다운 목록에서 리소스 유형을 선택합니다.

  6. 리소스 유형을 입력합니다.

  7. 다른 리소스 유형을 검색하려면 표시되는 연산자 드롭다운 목록에서 OR을 선택한 후 다른 리소스 유형을 입력하세요.

  8. 리소스 유형 목록에서 콘텐츠를 가져올 리소스의 리소스 유형을 선택합니다.

  9. 표시되는 리소스 테이블에서 리소스를 선택하거나 검색합니다.

REST

다음 샘플은 이전 섹션에서 만든 관찰 리소스의 세부정보를 가져오는 방법을 보여줍니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트의 ID
  • LOCATION: 데이터 세트 위치
  • DATASET_ID: FHIR 저장소의 상위 데이터 세트
  • FHIR_STORE_ID: FHIR 저장소 ID
  • OBSERVATION_ID: 관찰 리소스 ID

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

다음 명령어를 실행합니다.

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

PowerShell

다음 명령어를 실행합니다.

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

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

API 탐색기

메서드 참조 페이지를 엽니다. 페이지 오른쪽에 API 탐색기 패널이 열립니다. 이 도구를 사용하여 요청을 보낼 수 있습니다. 모든 필수 필드를 입력하고 실행을 클릭합니다.

다음과 비슷한 JSON 응답이 표시됩니다.

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: %w", 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: %w", err)
	}

	defer resp.Body.Close()

	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("could not read response: %w", 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.gson.GsonFactory;
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 GsonFactory();
  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/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const getFhirResource = async () => {
  // 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

# Imports the types Dict and Any for runtime type hints.
from typing import Any, Dict  # noqa: E402

def get_resource(
    project_id: str,
    location: str,
    dataset_id: str,
    fhir_store_id: str,
    resource_type: str,
    resource_id: str,
) -> Dict[str, Any]:
    """Gets the contents of a FHIR resource.

    See
    https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample.
    See
    https://googleapis.github.io/google-api-python-client/docs/dyn/healthcare_v1.projects.locations.datasets.fhirStores.fhir.html#read
    for the Python API reference.

    Args:
      project_id: The project ID or project number of the Cloud project you want
        to use.
      location: The name of the parent dataset's location.
      dataset_id: The name of the parent dataset.
      fhir_store_id: The name of the FHIR store.
      resource_type: The type of FHIR resource.
      resource_id: The "logical id" of the resource you want to get the contents
        of. The ID is assigned by the server.

    Returns:
      A dict representing the FHIR resource.
    """
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    api_version = "v1"
    service_name = "healthcare"

    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'
    # location = 'us-central1'
    # dataset_id = 'my-dataset'
    # fhir_store_id = 'my-fhir-store'
    # resource_type = 'Patient'
    # resource_id = 'b682d-0e-4843-a4a9-78c9ac64'
    fhir_store_parent = (
        f"projects/{project_id}/locations/{location}/datasets/{dataset_id}"
    )
    fhir_resource_path = f"{fhir_store_parent}/fhirStores/{fhir_store_id}/fhir/{resource_type}/{resource_id}"

    request = (
        client.projects()
        .locations()
        .datasets()
        .fhirStores()
        .fhir()
        .read(name=fhir_resource_path)
    )
    response = request.execute()
    print(
        f"Got contents of {resource_type} resource with ID {resource_id}:\n",
        json.dumps(response, indent=2),
    )

    return response

모든 환자 구획 리소스 가져오기

다음 샘플은 특정 환자 구획(DSTU2, STU3, R4)과 관련된 모든 리소스를 가져오는 방법을 보여줍니다. 자세한 내용은 projects.locations.datasets.fhirStores.fhir.Patient-everything을 참조하세요.

다음 curl 및 PowerShell 샘플은 R4 FHIR 저장소에서 작동합니다. Go, 자바, Node.js, Python 샘플은 STU3 FHIR 저장소에서 작동합니다.

curl

환자 구획의 리소스를 가져오려면 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/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",
        "reasonCode": [
          {
            "text": "The patient had an abnormal heart rate. She was concerned about this."
          }
        ],
        "resourceType": "Encounter",
        "status": "finished",
        "subject": {
          "reference": "Patient/PATIENT_ID"
        }
      }
    },
    {
      "resource": {
        "encounter": {
          "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
  • 액세스 토큰

다음 샘플은 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",
        "reasonCode": [
          {
            "text": "The patient had an abnormal heart rate. She was concerned about this."
          }
        ],
        "resourceType": "Encounter",
        "status": "finished",
        "subject": {
          "reference": "Patient/PATIENT_ID"
        }
      }
    },
    {
      "resource": {
        "encounter": {
          "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: %w", 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: %w", err)
	}

	defer resp.Body.Close()

	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("could not read response: %w", 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.gson.GsonFactory;
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 GsonFactory();
  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/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const getPatientEverything = async () => {
  // 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(
    project_id,
    location,
    dataset_id,
    fhir_store_id,
    resource_id,
):
    """Gets all the resources in the patient compartment.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample."""
    # Imports Python's built-in "os" module
    import os

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

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

    # Gets credentials from the environment.
    credentials = service_account.Credentials.from_service_account_file(
        os.environ["GOOGLE_APPLICATION_CREDENTIALS"]
    )
    scoped_credentials = credentials.with_scopes(
        ["https://www.googleapis.com/auth/cloud-platform"]
    )
    # Creates a requests Session object with the credentials.
    session = requests.AuthorizedSession(scoped_credentials)

    # URL to the Cloud Healthcare API endpoint and version
    base_url = "https://healthcare.googleapis.com/v1"

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'  # replace with your GCP project ID
    # location = 'us-central1'  # replace with the parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the parent dataset's ID
    # fhir_store_id = 'my-fhir-store' # replace with the FHIR store ID
    # resource_id = 'b682d-0e-4843-a4a9-78c9ac64'  # replace with the Patient resource's ID
    url = f"{base_url}/projects/{project_id}/locations/{location}"

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

    # Sets required application/fhir+json header on the request
    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 및 PowerShell 샘플은 R4 FHIR 저장소에서 작동합니다.

curl

지정된 유형의 환자 구획에 있는 지정된 날짜 이후의 리소스를 가져오려면 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/Patient/PATIENT_ID/\$everything?_type=RESOURCE_TYPES&_since=DATE"

요청이 성공하면 서버는 지정된 기준과 일치하는 모든 리소스를 JSON 형식으로 반환합니다.

PowerShell

지정된 유형의 환자 구획에 있는 지정된 날짜 이후의 리소스를 가져오려면 GET 요청을 실행하고 다음 정보를 지정합니다.

  • 상위 데이터 세트의 이름
  • FHIR 저장소의 이름
  • 환자의 ID
  • 쉼표로 구분된 리소스 유형 목록과 시작 날짜가 포함된 쿼리 문자열
  • 액세스 토큰

다음 샘플은 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 및 PowerShell 샘플은 R4 FHIR 저장소에서 작동합니다. Go, 자바, Node.js, Python 샘플은 STU3 FHIR 저장소에서 작동합니다.

curl

다음 샘플은 관찰 리소스의 모든 버전을 나열하는 방법을 보여줍니다. 관찰은 환자의 분당 심박수(BPM)를 변경하기 위해 처음 만든 후 한 번 업데이트되었습니다.

현재 버전 및 삭제된 버전을 포함하여 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/RESOURCE_TYPE/RESOURCE_ID/_history"

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다. 이 예시에서는 관찰의 두 가지 버전을 반환합니다. 첫 번째 버전에서 환자의 심박수는 75BPM이었습니다. 두 번째 버전에서 환자의 심박수는 85BPM이었습니다.

{
  "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": {
        "encounter": {
          "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
  • 액세스 토큰

다음 샘플은 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 형식으로 응답을 반환합니다. 이 예시에서는 관찰의 두 가지 버전을 반환합니다. 첫 번째 버전에서 환자의 심박수는 75BPM이었습니다. 두 번째 버전에서 환자의 심박수는 85BPM이었습니다.

{
  "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": {
        "encounter": {
          "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: %w", 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: %w", err)
	}

	defer resp.Body.Close()

	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("could not read response: %w", 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.gson.GsonFactory;
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 FhirResourceListHistory {
  private static final String FHIR_NAME =
      "projects/%s/locations/%s/datasets/%s/fhirStores/%s/fhir/%s/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void fhirResourceListHistory(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/_history", client.getRootUrl(), resourceName);
    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 history 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/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const listFhirResourceHistory = async () => {
  // 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

# Imports the types Dict and Any for runtime type hints.
from typing import Any, Dict  # noqa: E402

def list_resource_history(
    project_id: str,
    location: str,
    dataset_id: str,
    fhir_store_id: str,
    resource_type: str,
    resource_id: str,
) -> Dict[str, Any]:
    """Gets the history of a resource.

    See
    https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample.
    See
    https://googleapis.github.io/google-api-python-client/docs/dyn/healthcare_v1.projects.locations.datasets.fhirStores.fhir.html#history
    for the Python API reference.

    Args:
      project_id: The project ID or project number of the Cloud project you want
        to use.
      location: The name of the parent dataset's location.
      dataset_id: The name of the parent dataset.
      fhir_store_id: The name of the FHIR store.
      resource_type: The type of FHIR resource.
      resource_id: The "logical id" of the resource whose history you want to
        list. The ID is assigned by the server.

    Returns:
      A dict representing the FHIR resource.
    """
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    api_version = "v1"
    service_name = "healthcare"

    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'
    # location = 'us-central1'
    # dataset_id = 'my-dataset'
    # fhir_store_id = 'my-fhir-store'
    # resource_type = 'Patient'
    # resource_id = 'b682d-0e-4843-a4a9-78c9ac64'
    fhir_store_parent = (
        f"projects/{project_id}/locations/{location}/datasets/{dataset_id}"
    )
    fhir_resource_path = f"{fhir_store_parent}/fhirStores/{fhir_store_id}/fhir/{resource_type}/{resource_id}"

    request = (
        client.projects()
        .locations()
        .datasets()
        .fhirStores()
        .fhir()
        .history(name=fhir_resource_path)
    )
    response = request.execute()
    print(
        f"History for {resource_type} resource with ID {resource_id}:\n"
        f" {json.dumps(response, indent=2)}"
    )
    return response

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": {
        "encounter": {
          "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 및 PowerShell 샘플은 R4 FHIR 저장소에서 작동합니다. Go, Node.js, Python 샘플은 STU3 FHIR 저장소에서 작동합니다.

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/RESOURCE_TYPE/RESOURCE_ID/_history/RESOURCE_VERSION"

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다. 이 예시에서는 환자 심박수가 75BPM인 첫 번째 관찰 버전이 반환됩니다.

{
  "encounter": {
    "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
  • 리소스 버전
  • 액세스 토큰

다음 샘플은 curl을 사용하는 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/RESOURCE_VERSION/_history" | Select-Object -Expand Content

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다. 이 예시에서는 환자 심박수가 75BPM인 첫 번째 관찰 버전이 반환됩니다.

{
  "encounter": {
    "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: %w", 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: %w", err)
	}

	defer resp.Body.Close()

	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("could not read response: %w", 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
}

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.gson.GsonFactory;
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 GsonFactory();
  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/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const getFhirResourceHistory = async () => {
  // 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

# Imports the types Dict and Any for runtime type hints.
from typing import Any, Dict  # noqa: E402

def get_resource_history(
    project_id: str,
    location: str,
    dataset_id: str,
    fhir_store_id: str,
    resource_type: str,
    resource_id: str,
    version_id: str,
) -> Dict[str, Any]:
    """Gets the contents of a version (current or historical) of a FHIR resource by version ID.

    See
    https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample.
    See
    https://googleapis.github.io/google-api-python-client/docs/dyn/healthcare_v1.projects.locations.datasets.fhirStores.fhir.html#vread
    for the Python API reference.

    Args:
      project_id: The project ID or project number of the Cloud project you want
        to use.
      location: The name of the parent dataset's location.
      dataset_id: The name of the parent dataset.
      fhir_store_id: The name of the FHIR store.
      resource_type: The type of FHIR resource.
      resource_id: The "logical id" of the resource whose details you want to view
        at a particular version. The ID is assigned by the server.
      version_id: The ID of the version. Changes whenever the FHIR resource is
        modified.

    Returns:
      A dict representing the FHIR resource at the specified version.
    """
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    api_version = "v1"
    service_name = "healthcare"

    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'
    # location = 'us-central1'
    # dataset_id = 'my-dataset'
    # fhir_store_id = 'my-fhir-store'
    # resource_type = 'Patient'
    # resource_id = 'b682d-0e-4843-a4a9-78c9ac64'
    # version_id = 'MTY4NDQ1MDc3MDU2ODgyNzAwMA'
    fhir_store_parent = (
        f"projects/{project_id}/locations/{location}/datasets/{dataset_id}"
    )
    fhir_resource_path = f"{fhir_store_parent}/fhirStores/{fhir_store_id}/fhir/{resource_type}/{resource_id}/_history/{version_id}"

    request = (
        client.projects()
        .locations()
        .datasets()
        .fhirStores()
        .fhir()
        .vread(name=fhir_resource_path)
    )
    response = request.execute()
    print(
        f"Got contents of {resource_type} resource with ID {resource_id} at"
        f" version {version_id}:\n {json.dumps(response, indent=2)}"
    )

    return response

FHIR 리소스 삭제하기

다음 샘플은 projects.locations.datasets.fhirStores.fhir.delete 메서드를 호출하여 관찰 FHIR 리소스를 삭제하는 방법을 보여줍니다.

작업의 성공 또는 실패 여부와 관계없이 서버는 200 OK HTTP 상태 코드를 반환합니다. 리소스가 성공적으로 삭제되었는지 확인하려면 리소스를 검색하거나 가져와서 리소스가 있는지 확인합니다.

다음 curl 및 PowerShell 샘플은 R4 FHIR 저장소에서 작동합니다. Go, 자바, Node.js, Python 샘플은 STU3 FHIR 저장소에서 작동합니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트의 ID
  • LOCATION: 데이터 세트 위치
  • DATASET_ID: FHIR 저장소의 상위 데이터 세트
  • FHIR_STORE_ID: FHIR 저장소 ID
  • OBSERVATION_ID: 관찰 리소스 ID

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

다음 명령어를 실행합니다.

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

PowerShell

다음 명령어를 실행합니다.

$cred = gcloud auth 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/Observation/OBSERVATION_ID" | Select-Object -Expand Content

API 탐색기

메서드 참조 페이지를 엽니다. 페이지 오른쪽에 API 탐색기 패널이 열립니다. 이 도구를 사용하여 요청을 보낼 수 있습니다. 모든 필수 필드를 입력하고 실행을 클릭합니다.

다음과 비슷한 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: %w", 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: %w", 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.gson.GsonFactory;
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 GsonFactory();
  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/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const deleteFhirResource = async () => {
  // 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(
    project_id: str,
    location: str,
    dataset_id: str,
    fhir_store_id: str,
    resource_type: str,
    resource_id: str,
) -> dict:
    """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.

    See
    https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample.
    See
    https://googleapis.github.io/google-api-python-client/docs/dyn/healthcare_v1.projects.locations.datasets.fhirStores.fhir.html#delete
    for the Python API reference.
    Args:
      project_id: The project ID or project number of the Cloud project you want
        to use.
      location: The name of the parent dataset's location.
      dataset_id: The name of the parent dataset.
      fhir_store_id: The name of the FHIR store.
      resource_type: The type of the FHIR resource.
      resource_id: The "logical id" of the FHIR resource you want to delete. The
        ID is assigned by the server.

    Returns:
      An empty dict.
    """
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    api_version = "v1"
    service_name = "healthcare"

    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'
    # location = 'us-central1'
    # dataset_id = 'my-dataset'
    # fhir_store_id = 'my-fhir-store'
    # resource_type = 'Patient'
    # resource_id = 'b682d-0e-4843-a4a9-78c9ac64'
    fhir_store_parent = (
        f"projects/{project_id}/locations/{location}/datasets/{dataset_id}"
    )
    fhir_resource_path = f"{fhir_store_parent}/fhirStores/{fhir_store_id}/fhir/{resource_type}/{resource_id}"

    request = (
        client.projects()
        .locations()
        .datasets()
        .fhirStores()
        .fhir()
        .delete(name=fhir_resource_path)
    )
    response = request.execute()
    print(f"Deleted {resource_type} resource with ID {resource_id}.")

    return response

FHIR 리소스 조건부 삭제

Cloud Healthcare API v1에서 조건부 작업은 FHIR 리소스 유형에 대해 존재할 경우 identifier 검색 매개변수를 배타적으로 사용하여 조건부 검색어와 일치하는 FHIR 리소스를 확인합니다.

FHIR 리소스는 리소스의 identifier.systemmy-code-system이고 identifier.valueABC-12345인 경우에만 ?identifier=my-code-system|ABC-12345 쿼리와 일치합니다. FHIR 리소스가 쿼리와 일치하면 Cloud Healthcare API가 리소스를 삭제합니다.

쿼리가 identifier 검색 매개변수를 사용하고 여러 FHIR 리소스와 일치하면 Cloud Healthcare API는 "412 - Condition not selective enough" 오류를 반환합니다. 리소스를 개별적으로 삭제하려면 다음 단계를 따르세요.

  1. 각 리소스를 검색하여 고유한 서버 할당 ID를 가져옵니다.
  2. ID를 사용하여 각 리소스를 개별적으로 삭제합니다.

다음 샘플은 ID로 FHIR 리소스를 식별하는 대신 검색어와 일치하는 FHIR 리소스를 조건부로 삭제하는 방법을 보여줍니다. 검색어는 관찰 식별자(my-code-systemABC-12345)를 사용하여 관찰 리소스를 일치시키고 삭제합니다.

REST

projects.locations.datasets.fhirStores.fhir.conditionalDelete 메서드를 사용합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트의 ID
  • LOCATION: 데이터 세트 위치
  • DATASET_ID: FHIR 저장소의 상위 데이터 세트
  • FHIR_STORE_ID: FHIR 저장소 ID

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

다음 명령어를 실행합니다.

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/Observation?identifier=my-code-system|ABC-12345"

PowerShell

다음 명령어를 실행합니다.

$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/Observation?identifier=my-code-system|ABC-12345" | Select-Object -Expand Content

API 탐색기

메서드 참조 페이지를 엽니다. 페이지 오른쪽에 API 탐색기 패널이 열립니다. 이 도구를 사용하여 요청을 보낼 수 있습니다. 모든 필수 필드를 입력하고 실행을 클릭합니다.

성공 상태 코드(2xx)와 빈 응답을 받게 됩니다.

FHIR 리소스의 이전 버전 삭제하기

다음 샘플은 FHIR 리소스의 모든 이전 버전을 삭제하는 방법을 보여줍니다. 자세한 내용은 projects.locations.datasets.fhirStores.fhir.Resource-purge를 참조하세요.

projects.locations.datasets.fhirStores.fhir.Resource-purge 메서드 호출은 roles/healthcare.fhirStoreAdmin 역할을 가진 사용자(호출자)로 제한됩니다. roles/healthcare.fhirResourceEditor 역할을 가진 사용자는 이 메서드를 호출할 수 없습니다. 호출자가 FHIR 리소스의 이전 버전을 삭제하도록 허용하려면 다음 중 하나를 수행합니다.

이 샘플은 FHIR 리소스 만들기에서 만든 리소스를 사용하며 관찰 리소스의 이전 버전을 삭제하는 방법을 보여줍니다.

다음 curl 및 PowerShell 샘플은 R4 FHIR 저장소에서 작동합니다. Go, 자바, Node.js, Python 샘플은 STU3 FHIR 저장소에서 작동합니다.

curl

FHIR 리소스의 모든 이전 버전을 삭제하려면 DELETE 요청을 수행하고 다음 정보를 지정합니다.

  • 상위 데이터 세트의 이름
  • FHIR 저장소의 이름
  • 리소스 유형 및 ID
  • 액세스 토큰

다음 샘플은 curl을 사용하는 DELETE 요청을 보여줍니다.

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
  • 액세스 토큰

다음 샘플은 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: %w", 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: %w", 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.gson.GsonFactory;
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/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  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", "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/$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 (excluding current 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/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const deleteFhirResourcePurge = async () => {
  // 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(
    project_id: str,
    location: str,
    dataset_id: str,
    fhir_store_id: str,
    resource_type: str,
    resource_id: str,
) -> dict:
    """Deletes all versions of a FHIR resource (excluding the current version).

    See
    https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample.
    See
    https://googleapis.github.io/google-api-python-client/docs/dyn/healthcare_v1.projects.locations.datasets.fhirStores.fhir.html#Resource_purge
    for the Python API reference.

    Args:
      project_id: The project ID or project number of the Cloud project you want
        to use.
      location: The name of the parent dataset's location.
      dataset_id: The name of the parent dataset.
      fhir_store_id: The name of the FHIR store.
      resource_type: The type of the FHIR resource.
      resource_id: The "logical id" of the resource. The ID is assigned by the
        server.

    Returns:
      An empty dict.
    """
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    api_version = "v1"
    service_name = "healthcare"

    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'
    # location = 'us-central1'
    # dataset_id = 'my-dataset'
    # fhir_store_id = 'my-fhir-store'
    # resource_type = 'Patient'
    # resource_id = 'b682d-0e-4843-a4a9-78c9ac64'
    fhir_store_parent = (
        f"projects/{project_id}/locations/{location}/datasets/{dataset_id}"
    )
    fhir_resource_path = f"{fhir_store_parent}/fhirStores/{fhir_store_id}/fhir/{resource_type}/{resource_id}"

    request = (
        client.projects()
        .locations()
        .datasets()
        .fhirStores()
        .fhir()
        .Resource_purge(name=fhir_resource_path)
    )
    response = request.execute()
    print(
        f"Deleted all versions of {resource_type} resource with ID"
        f" {resource_id} (excluding current version)."
    )
    return response