FHIR 리소스 만들기 및 관리

이 페이지에서는 FHIR 리소스를 생성, 업데이트, 패치, 보기, 삭제하는 방법을 설명합니다.

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

FHIR 리소스 만들기

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

curl, Windows 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

환자 리소스를 만들려면 POST 요청을 수행하고 다음 정보를 지정합니다.

  • 상위 데이터 세트의 이름
  • FHIR 저장소의 이름
  • 환자에 대한 정보가 포함된 데이터 blob
  • 리소스 유형
  • 액세스 토큰

다음 샘플은 curl을 사용하는 POST 요청을 보내 환자 리소스를 만드는 방법을 보여줍니다.

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

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다.

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

PowerShell

환자 리소스를 만들려면 POST 요청을 수행하고 다음 정보를 지정합니다.

  • 상위 데이터 세트의 이름
  • FHIR 저장소의 이름
  • 환자에 대한 정보가 포함된 데이터 blob
  • 리소스 유형
  • 액세스 토큰

다음 샘플은 Windows PowerShell을 사용하는 POST 요청을 보내 환자 리소스를 만드는 방법을 보여줍니다.

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

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

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

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다.

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

Go

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

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

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

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

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

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

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

	call := fhirService.Create(parent, resourceType, bytes.NewReader(jsonPayload))
	call.Header().Set("Content-Type", "application/fhir+json;charset=utf-8")
	resp, err := call.Do()
	if err != nil {
		return fmt.Errorf("Create: %v", err)
	}
	defer resp.Body.Close()

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

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

	return nil
}

자바

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collections;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;

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

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

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

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

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

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

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }

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

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

Node.js

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

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

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

  google.options({auth, headers: {'Content-Type': 'application/fhir+json'}});

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}`;

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

createFhirResource();

Python

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

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

    # Make an authenticated API request
    session = get_session()

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

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

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

    resource = response.json()

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

    return response

curl

환자 리소스를 만든 후 환자와 전문의 사이의 상호작용을 설명하는 Encounter 리소스를 만듭니다. 다음 샘플은 curl을 사용하는 POST 요청을 보내 Encounter 리소스를 만드는 방법을 보여줍니다.

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

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

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다. R4 FHIR 저장소를 사용하는 경우 reasonreasonCode로 바뀝니다.

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

PowerShell

환자 리소스를 만든 후 환자와 전문의 사이의 상호작용을 설명하는 Encounter 리소스를 만듭니다. 다음 샘플은 Windows PowerShell을 사용하는 POST 요청을 보내 Encounter 리소스를 만드는 방법을 보여줍니다.

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

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

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

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

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다. R4 FHIR 저장소를 사용하는 경우 reasonreasonCode로 바뀝니다.

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

Python

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

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

    # Make an authenticated API request
    session = get_session()

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

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

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

    resource = response.json()

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

    return response

curl

Encounter 리소스를 만든 후에는 Encounter에 대한 관찰을 만듭니다. 관찰은 환자의 분당 심박수(BPM) 측정값을 제공합니다. 다음 샘플은 curl을 사용하는 POST 요청을 보내 관찰 리소스를 만드는 방법을 보여줍니다.

  • BPM_VALUE 필드에 값을 입력합니다.
  • PATIENT_ID 필드에서 환자를 만들 때 서버에서 반환한 응답의 ID를 대체합니다.
  • ENCOUNTER_ID 필드에서 Encounter를 만들 때 서버가 반환한 응답의 ID를 대체합니다.
curl -X POST \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     -H "Content-Type: application/fhir+json; charset=utf-8" \
     --data "{
         \"resourceType\": \"Observation\",
         \"status\": \"final\",
         \"subject\": {
           \"reference\": \"Patient/PATIENT_ID\"
         },
         \"effectiveDateTime\": \"2020-01-01T00:00:00+00:00\",
         \"code\": {
           \"coding\": [
             {
               \"system\": \"http://loinc.org\",
               \"code\": \"8867-4\",
               \"display\": \"Heart rate\"
             }
           ]
         },
         \"valueQuantity\": {
           \"value\": BPM_VALUE,
           \"unit\": \"bpm\"
         },
         \"context\": {
           \"reference\": \"Encounter/ENCOUNTER_ID\"
         }
     }" \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation"

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다.

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

PowerShell

Encounter 리소스를 만든 후에는 Encounter에 대한 관찰을 만듭니다. 관찰은 환자의 분당 심박수(BPM) 측정값을 제공합니다. 다음 샘플은 Windows PowerShell을 사용하여 POST 요청을 보내 관찰 리소스를 만드는 방법을 보여줍니다.

  • BPM_VALUE 필드에 값을 입력합니다.
  • PATIENT_ID 필드에서 환자를 만들 때 서버에서 반환한 응답의 ID를 대체합니다.
  • ENCOUNTER_ID 필드에서 Encounter를 만들 때 서버가 반환한 응답의 ID를 대체합니다.
$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

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

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

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다.

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

Python

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

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

    # Make an authenticated API request
    session = get_session()

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

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

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

    resource = response.json()

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

    return response

FHIR 리소스 업데이트하기

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

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

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

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

curl

FHIR 리소스를 업데이트하려면 PUT 요청을 수행하고 다음 정보를 지정합니다.

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

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

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

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다.

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

PowerShell

FHIR 리소스를 업데이트하려면 PUT 요청을 수행하고 다음 정보를 지정합니다.

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

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

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

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

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

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다.

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

Go

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

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

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

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

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

	// The following payload works with a Patient resource and is not
	// intended to work with other types of FHIR resources. If necessary,
	// supply a new payload with data that corresponds to the FHIR resource
	// you are updating.
	payload := map[string]interface{}{
		"resourceType": resourceType,
		"id":           fhirResourceID,
		"active":       active,
	}
	jsonPayload, err := json.Marshal(payload)
	if err != nil {
		return fmt.Errorf("json.Encode: %v", err)
	}

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

	call := fhirService.Update(name, bytes.NewReader(jsonPayload))
	call.Header().Set("Content-Type", "application/fhir+json;charset=utf-8")
	resp, err := call.Do()
	if err != nil {
		return fmt.Errorf("Update: %v", err)
	}
	defer resp.Body.Close()

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

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

	return nil
}

Node.js

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

const updateFhirResource = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({
    auth,
    headers: {'Content-Type': 'application/fhir+json'},
  });

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  // const resourceId = '16e8a860-33b3-49be-9b03-de979feed14a';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}`;
  // The following body works with a Patient resource and is not intended
  // to work with other types of FHIR resources. If necessary, supply a new
  // body with data that corresponds to the FHIR resource you are updating.
  const body = {resourceType: resourceType, id: resourceId, active: true};
  const request = {name, requestBody: body};

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

updateFhirResource();

Python

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

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

    # Make an authenticated API request
    session = get_session()

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

    # The body shown works with a Patient resource and is not guaranteed
    # to work with other types of FHIR resources. If necessary,
    # supply a new body with data that corresponds to the resource you
    # are updating.
    body = {"resourceType": resource_type, "active": True, "id": resource_id}

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

    resource = response.json()

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

    return resource

FHIR 리소스 조건부 업데이트

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

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

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

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

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

curl

검색어와 일치하는 FHIR 리소스를 업데이트하려면 PUT 요청을 수행하고 다음 정보를 지정합니다.

  • 상위 데이터 세트의 이름
  • FHIR 저장소의 이름
  • 검색할 리소스 유형
  • 검색할 정보가 포함된 쿼리 문자열
  • 액세스 토큰

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

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

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다.

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

PowerShell

검색어와 일치하는 FHIR 리소스를 업데이트하려면 PUT 요청을 수행하고 다음 정보를 지정합니다.

  • 상위 데이터 세트의 이름
  • FHIR 저장소의 이름
  • 검색할 리소스 유형
  • 검색할 정보가 포함된 쿼리 문자열
  • 액세스 토큰

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

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

$observation = '{
  "effectiveDateTime": "2020-01-01T00:00:00+00:00",
  "resourceType": "Observation",
  "identifier": [
      {
          "system": "my-code-system",
          "value": "ABC-12345"
      }
  ],
  "status": "final",
  "subject": {
    "reference": "Patient/PATIENT_ID"
  },
  "valueQuantity": {
    "unit": "bpm",
    "value": BPM_VALUE
  }
}'

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

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다.

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

Go

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

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

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

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

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

	ctx := context.Background()

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

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

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

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

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

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

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

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

	defer resp.Body.Close()

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

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

	return nil
}

Python

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

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

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

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

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

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

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

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

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

    return resource

FHIR 리소스 패치

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

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

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

curl

FHIR 리소스를 패치하려면 PATCH 요청을 수행하고 다음 정보를 지정합니다.

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

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

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

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다.

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

PowerShell

FHIR 리소스를 패치하려면 PATCH 요청을 수행하고 다음 정보를 지정합니다.

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

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

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

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

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

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다.

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

Go

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

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

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

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

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

	// The following payload works with a Patient resource and is not intended to work with
	// other types of FHIR resources. If necessary, supply a new payload with data that
	// corresponds to the FHIR resource you are patching.
	payload := []map[string]interface{}{
		{
			"op":    "replace",
			"path":  "/active",
			"value": active,
		},
	}
	jsonPayload, err := json.Marshal(payload)
	if err != nil {
		return fmt.Errorf("json.Encode: %v", err)
	}

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

	call := fhirService.Patch(name, bytes.NewReader(jsonPayload))
	call.Header().Set("Content-Type", "application/json-patch+json")
	resp, err := call.Do()
	if err != nil {
		return fmt.Errorf("Patch: %v", err)
	}
	defer resp.Body.Close()

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

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

	return nil
}

자바

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collections;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;

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

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

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

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

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

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

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

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }

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

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

Node.js

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

async function patchFhirResource() {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  // TODO(developer): replace patchOptions with your desired JSON patch body
  const patchOptions = [{op: 'replace', path: '/active', value: false}];
  google.options({auth, headers: {'Content-Type': 'application/json-patch+json'}});

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  // const resourceId = '16e8a860-33b3-49be-9b03-de979feed14a';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}`;
  const request = {
    name,
    requestBody: patchOptions
  };

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

patchFhirResource();

Python

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

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

    # Make an authenticated API request
    session = get_session()

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

    # The body shown works with a Patient resource and is not guaranteed
    # to work with other types of FHIR resources. If necessary,
    # supply a new body with data that corresponds to the resource you
    # are patching.
    body = json.dumps([{"op": "replace", "path": "/active", "value": False}])

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

    resource = response.json()

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

    return resource

FHIR 리소스 조건부 패치

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

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

curl

검색어와 일치하는 FHIR 리소스를 패치하려면 PATCH 요청을 수행하고 다음 정보를 지정합니다.

  • 상위 데이터 세트의 이름
  • FHIR 저장소의 이름
  • 검색할 리소스 유형
  • 검색할 정보가 포함된 쿼리 문자열
  • 액세스 토큰

다음 샘플은 관찰 대상이 'Patient123'인 경우 curl을 사용하는 PATCH 요청을 보내 관찰 리소스를 수정하는 방법을 보여줍니다. 환자의 분당 심박수(BPM) 관찰은 replace 패치 작업을 사용하여 업데이트됩니다.

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

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다.

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

PowerShell

검색어와 일치하는 FHIR 리소스를 패치하려면 PATCH 요청을 수행하고 다음 정보를 지정합니다.

  • 상위 데이터 세트의 이름
  • FHIR 저장소의 이름
  • 검색할 리소스 유형
  • 검색할 정보가 포함된 쿼리 문자열
  • 액세스 토큰

다음 샘플은 관찰 대상이 'Patient123'인 경우 Windows PowerShell을 사용하는 PATCH 요청을 보내 관찰 리소스를 수정하는 방법을 보여줍니다. 환자의 분당 심박수(BPM) 관찰은 replace 패치 작업을 사용하여 업데이트됩니다.

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

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

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

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다.

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

Go


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

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

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

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

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

	ctx := context.Background()

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

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

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

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

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

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

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

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

	defer resp.Body.Close()

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

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

	return nil
}

Python

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

    # The search query in this request updates all Observations
    # if the subject of the Observation is a particular patient.
    resource_path = "{}/datasets/{}/fhirStores/{}/fhir/Observation".format(
        url, dataset_id, fhir_store_id
    )

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

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

    body = json.dumps(
        [
            {
                "op": "replace",
                "path": "/valueQuantity/value",
                # Sets the BPM for all matching Observations to 80. This
                # is the portion of the request being patched.
                "value": 80,
            }
        ]
    )

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

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

    print(response.url)

    resource = response.json()

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

    return resource

FHIR 리소스 가져오기

다음 샘플은 FHIR 리소스의 콘텐츠를 가져오는 방법을 보여줍니다. 자세한 내용은 projects.locations.datasets.fhirStores.fhir.read를 참조하세요.

curl

FHIR 리소스의 콘텐츠를 가져오려면 GET 요청을 수행하고 다음 정보를 지정합니다.

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

다음 샘플은 이전 섹션에서 만든 관찰에서 curl을 사용하는 GET 요청을 보여줍니다.

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

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다.

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

PowerShell

FHIR 리소스의 콘텐츠를 가져오려면 GET 요청을 수행하고 다음 정보를 지정합니다.

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

다음 샘플은 이전 섹션에서 만든 관찰에서 Windows PowerShell을 사용하여 GET 요청을 보여줍니다.

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

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

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다.

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

Go

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

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

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

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

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

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

	call := fhirService.Read(name)
	call.Header().Set("Content-Type", "application/fhir+json;charset=utf-8")
	resp, err := call.Do()
	if err != nil {
		return fmt.Errorf("Read: %v", err)
	}

	defer resp.Body.Close()

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

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

	return nil
}

자바

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collections;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;

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

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

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

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

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

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

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }

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

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

Node.js

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

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

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  // const resourceId = '16e8a860-33b3-49be-9b03-de979feed14a';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}`;
  const request = {name};

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

getFhirResource();

Python

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

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

    # Make an authenticated API request
    session = get_session()

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

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

    resource = response.json()

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

    return resource

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

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

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",
        "reason": [
          {
            "text": "The patient had an abnormal heart rate. She was concerned about this."
          }
        ],
        "resourceType": "Encounter",
        "status": "finished",
        "subject": {
          "reference": "Patient/PATIENT_ID"
        }
      }
    },
    {
      "resource": {
        "context": {
          "reference": "Encounter/ENCOUNTER_ID"
        },
        "effectiveDateTime": "2020-01-01T00:00:00+00:00",
        "id": "OBSERVATION_ID",
        "resourceType": "Observation",
        "status": "final",
        "subject": {
          "reference": "Patient/PATIENT_ID"
        },
        "valueQuantity": {
          "unit": "bpm",
          "value": BPM_VALUE
        }
      }
    }
  ],
  "resourceType": "Bundle",
  "type": "searchset"
}

PowerShell

환자 구획의 리소스를 가져오려면 GET 요청을 수행하고 다음 정보를 지정합니다.

  • 상위 데이터 세트의 이름
  • FHIR 저장소의 이름
  • 환자의 ID
  • 액세스 토큰

다음 샘플은 Windows PowerShell을 사용한 GET 요청을 보여줍니다.

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

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

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다.

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

Go

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

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

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

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

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

	defer resp.Body.Close()

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

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

	return nil
}

자바

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collections;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;

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

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

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

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

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

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

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

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }

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

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

Node.js

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

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

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const patientId = '16e8a860-33b3-49be-9b03-de979feed14a';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/Patient/${patientId}`;
  const request = {name};

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

getPatientEverything();

Python

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

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

    # Make an authenticated API request
    session = get_session()

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

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

    resource = response.json()

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

    return resource

유형 또는 날짜별로 필터링된 환자 구획 리소스 가져오기

다음 샘플은 유형 목록 및 지정된 날짜 및 시간 이후로 필터링된 특정 환자 구획(R4)과 관련된 모든 리소스를 가져오는 방법을 보여줍니다. 자세한 내용은 projects.locations.datasets.fhirStores.fhir.Patient-everything를 참조하세요.

curl

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

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

다음 샘플은 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
  • 쉼표로 구분된 리소스 유형 목록과 시작 날짜가 포함된 쿼리 문자열
  • 액세스 토큰

다음 샘플은 Windows PowerShell을 사용한 GET 요청을 보여줍니다.

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

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

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

FHIR 리소스 버전 나열

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

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

curl

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

현재 버전 및 삭제된 버전을 포함하여 FHIR 리소스의 모든 버전을 나열하려면 GET 요청을 수행하고 다음 정보를 지정합니다.

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

다음 샘플은 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": {
        "context": {
          "reference": "Encounter/ENCOUNTER_ID"
        },
        "effectiveDateTime": "2020-01-01T00:00:00+00:00",
        "id": "OBSERVATION_ID",
        "meta": {
          "lastUpdated": "2020-01-01T00:00:00+00:00",
          "versionId": "MTU0MTE5MDg4MTY0MzQ3MjAwMA"
        },
        "resourceType": "Observation",
        "status": "final",
        "subject": {
          "reference": "Patient/PATIENT_ID"
        },
        "valueQuantity": {
          "unit": "bpm",
          "value": 75
        }
      }
    }
  ],
  "resourceType": "Bundle",
  "type": "history"
}

PowerShell

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

현재 버전 및 삭제된 버전을 포함하여 FHIR 리소스의 모든 버전을 나열하려면 GET 요청을 수행하고 다음 정보를 지정합니다.

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

다음 샘플은 Windows PowerShell을 사용한 GET 요청을 보여줍니다.

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

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

요청이 성공하면 서버가 JSON 형식으로 응답을 반환합니다. 이 예시에서는 관찰의 두 가지 버전을 반환합니다. 첫 번째 버전에서 환자의 심박수는 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": {
        "context": {
          "reference": "Encounter/ENCOUNTER_ID"
        },
        "effectiveDateTime": "2020-01-01T00:00:00+00:00",
        "id": "OBSERVATION_ID",
        "meta": {
          "lastUpdated": "2020-01-01T00:00:00+00:00",
          "versionId": "MTU0MTE5MDg4MTY0MzQ3MjAwMA"
        },
        "resourceType": "Observation",
        "status": "final",
        "subject": {
          "reference": "Patient/PATIENT_ID"
        },
        "valueQuantity": {
          "unit": "bpm",
          "value": 75
        }
      }
    }
  ],
  "resourceType": "Bundle",
  "type": "history"
}

Go

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

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

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

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

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

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

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

	defer resp.Body.Close()

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

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

	return nil
}

자바

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collections;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;

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

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

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

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

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

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

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

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }

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

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

Node.js

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

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

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  // const resourceId = '16e8a860-33b3-49be-9b03-de979feed14a';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}/_history`;
  const request = {name};

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

listFhirResourceHistory();

Python

def list_resource_history(
    base_url,
    project_id,
    cloud_region,
    dataset_id,
    fhir_store_id,
    resource_type,
    resource_id,
):
    """Gets the history of a resource."""
    url = "{}/projects/{}/locations/{}".format(base_url, project_id, cloud_region)

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

    # Make an authenticated API request
    session = get_session()

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

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

    resource = response.json()

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

    return resource

FHIR 리소스 버전 검색하기

다음 샘플은 특정 버전의 리소스를 검색하는 방법을 보여줍니다. 자세한 내용은 projects.locations.datasets.fhirStores.fhir.vread를 참조하세요.

아래에는 FHIR 리소스 버전 나열에서 관찰 리소스의 버전 ID가 강조표시됩니다.

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

다음 샘플은 FHIR 리소스 만들기에서 만든 리소스를 사용하고 관찰 리소스를 표시하는 방법을 보여줍니다.

curl

FHIR 리소스의 특정 버전을 가져오려면 GET 요청을 수행하고 다음 정보를 지정합니다.

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

다음 샘플은 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인 첫 번째 관찰 버전이 반환됩니다.

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

PowerShell

FHIR 리소스의 특정 버전을 가져오려면 GET 요청을 수행하고 다음 정보를 지정합니다.

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

다음 샘플은 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인 첫 번째 관찰 버전이 반환됩니다.

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

Go

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

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

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

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

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

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

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

	defer resp.Body.Close()

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

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

	return nil
}

Node.js

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

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

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  // const resourceId = '16e8a860-33b3-49be-9b03-de979feed14a';
  // const versionId = 'MTU2NPg3NDgyNDAxMDc4OTAwMA';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}/_history/${versionId}`;
  const request = {name};

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

getFhirResourceHistory();

Python

def get_resource_history(
    base_url,
    project_id,
    cloud_region,
    dataset_id,
    fhir_store_id,
    resource_type,
    resource_id,
    version_id,
):
    """Gets a version resource."""
    url = "{}/projects/{}/locations/{}".format(base_url, project_id, cloud_region)

    resource_path = "{}/datasets/{}/fhirStores/{}/fhir/{}/{}".format(
        url, dataset_id, fhir_store_id, resource_type, resource_id
    )
    resource_path += "/_history/{}".format(version_id)

    # Make an authenticated API request
    session = get_session()

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

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

    resource = response.json()

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

    return resource

FHIR 리소스 삭제하기

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

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

curl

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

  • 상위 데이터 세트의 이름
  • FHIR 저장소의 이름
  • 액세스 토큰

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

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

요청이 성공하면 서버가 JSON 형식으로 빈 응답 본문을 반환합니다.

{}

PowerShell

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

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

다음 샘플은 Windows PowerShell을 사용한 DELETE 요청을 보여줍니다.

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

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

요청이 성공하면 서버가 JSON 형식으로 빈 응답 본문을 반환합니다.

{}

Go

import (
	"context"
	"fmt"
	"io"

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

// deleteFHIRResource deletes an FHIR resource.
// Regardless of whether the operation succeeds or
// fails, the server returns a 200 OK HTTP status code. To check that the
// resource was successfully deleted, search for or get the resource and
// see if it exists.
func deleteFHIRResource(w io.Writer, projectID, location, datasetID, fhirStoreID, resourceType, fhirResourceID string) error {
	ctx := context.Background()

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

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

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

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

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

	return nil
}

자바

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collections;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;

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

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

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

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

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

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

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

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }

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

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

Node.js

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

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

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  // const resourceId = '9a664e07-79a4-4c2e-04ed-e996c75484e1;
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}`;
  const request = {name};

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

deleteFhirResource();

Python

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

    Regardless of whether the operation succeeds or
    fails, the server returns a 200 OK HTTP status code. To check that the
    resource was successfully deleted, search for or get the resource and
    see if it exists.
    """
    url = "{}/projects/{}/locations/{}".format(base_url, project_id, cloud_region)

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

    # Make an authenticated API request
    session = get_session()

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

    return response

FHIR 리소스 조건부 삭제

다음 샘플은 ID로 리소스를 식별하는 대신 projects.locations.datasets.fhirStores.fhir.conditionalDelete 메서드를 호출하여 검색어와 일치하는 FHIR 리소스를 삭제하는 방법을 보여줍니다.

리소스를 조건부 패치하거나 조건부 업데이트하는 것과 달리 조건부 삭제 메서드는 검색 기준에서 여러 일치 항목이 반환되는 경우 여러 리소스에 적용될 수 있습니다.

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

curl

검색어와 일치하는 FHIR 리소스를 삭제하려면 DELETE 요청을 수행하고 다음 정보를 지정합니다.

  • 상위 데이터 세트의 이름
  • FHIR 저장소의 이름
  • 검색할 리소스 유형
  • 검색할 정보가 포함된 쿼리 문자열
  • 액세스 토큰

다음 샘플은 curl을 사용한 DELETE 요청을 수행하여 statuscancelled(STU3, R4)인 모든 관찰을 삭제합니다.

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

요청이 성공하면 서버가 JSON 형식으로 빈 응답 본문을 반환합니다.

{}

PowerShell

검색어와 일치하는 FHIR 리소스를 삭제하려면 DELETE 요청을 수행하고 다음 정보를 지정합니다.

  • 상위 데이터 세트의 이름
  • FHIR 저장소의 이름
  • 검색할 리소스 유형
  • 검색할 정보가 포함된 쿼리 문자열
  • 액세스 토큰

다음 샘플은 Windows PowerShell을 사용한 DELETE 요청을 수행하여 statuscancelled(STU3, R4)인 모든 관찰을 삭제합니다.

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

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

요청이 성공하면 서버가 JSON 형식으로 빈 응답 본문을 반환합니다.

{}

Go

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

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

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

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

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

	ctx := context.Background()

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

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

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

	call := fhirService.ConditionalDelete(parent, resourceType)

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

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

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

	return nil
}

Python

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

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

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

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

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

    return response

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

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

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

이 샘플은 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
  • 액세스 토큰

다음 샘플은 Windows PowerShell을 사용한 DELETE 요청을 보여줍니다.

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

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

요청이 성공하면 서버가 JSON 형식으로 빈 응답 본문을 반환합니다.

{}

Go

import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

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

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

	return nil
}

자바

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collections;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;

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

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

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

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

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

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

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

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }

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

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

Node.js

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

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

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  // const resourceId = '9a664e07-79a4-4c2e-04ed-e996c75484e1;
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}`;
  const request = {name};

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

deleteFhirResourcePurge();

Python

def delete_resource_purge(
    base_url,
    project_id,
    cloud_region,
    dataset_id,
    fhir_store_id,
    resource_type,
    resource_id,
):
    """Deletes versions of a resource (excluding current version)."""
    url = "{}/projects/{}/locations/{}".format(base_url, project_id, cloud_region)

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

    # Make an authenticated API request
    session = get_session()

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

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

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

    return response