FHIR-Ressourcen erstellen und verwalten

Auf dieser Seite wird erläutert, wie Sie FHIR-Ressourcen erstellen, aktualisieren, patchen, ansehen, auflisten, abrufen und löschen.

Eine FHIR-Ressource kann Daten zu einem Patienten, einem Gerät, einer Beobachtung und mehr enthalten. Eine vollständige Liste der FHIR-Ressourcen finden Sie im FHIR-Ressourcenindex (DSTU2, STU3 oder R4).

Die curl- und PowerShell-Beispiele auf dieser Seite funktionieren mit einem R4 FHIR-Speicher und funktionieren nicht unbedingt, wenn Sie einen DSTU2- oder STU3 FHIR-Speicher verwenden. Wenn Sie einen DSTU2- oder STU3 FHIR-Speicher verwenden, finden Sie in der offiziellen FHIR-Dokumentation Informationen zum Konvertieren der Beispiele in die von Ihnen verwendete FHIR-Version.

Die Go-, Java-, Node.js- und Python-Beispiele funktionieren mit einem STU3-FHIR-Speicher.

FHIR-Ressourcen erstellen

Bevor Sie FHIR-Ressourcen erstellen können, müssen Sie einen FHIR-Speicher erstellen.

Die Beispiele curl, PowerShell und Python zeigen, wie die folgenden FHIR-Ressourcen erstellt werden:

  1. Eine Patientenressource (DSTU2, STU3 und R4)
  2. Eine Encounter-Ressource (DSTU2, STU3 und R4) für den Patienten
  3. Eine Beobachtungsressource (DSTU2, STU3 und R4) für den Typ "Encounter"

Die Beispiele für alle anderen Sprachen zeigen, wie eine allgemeine FHIR-Ressource erstellt wird.

Weitere Informationen finden Sie unter projects.locations.datasets.fhirStores.fhir.create.

Die folgenden Beispiele für curl und PowerShell funktionieren mit R4-FHIR-Speichern. Die Go-, Java-, Node.js- und Python-Beispiele funktionieren mit STU3-FHIR-Speichern.

REST

Bevor Sie die Anfragedaten verwenden, ersetzen Sie die folgenden Werte:

  • PROJECT_ID ist die ID Ihres Google Cloud-Projekts
  • LOCATION ist der Standort des Datasets
  • DATASET_ID: das übergeordnete Dataset des FHIR-Speichers
  • FHIR_STORE_ID: die FHIR-Speicher-ID

JSON-Text anfordern:

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

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

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

PowerShell

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

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

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

Sie sollten in etwa folgende JSON-Antwort erhalten:

Go

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

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

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

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

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

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

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

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

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

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

	return nil
}

Java

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

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

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

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

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

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

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

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

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

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

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

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
  headers: {'Content-Type': 'application/fhir+json'},
});

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

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

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

createFhirResource();

Python

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

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

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

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

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

    api_version = "v1"
    service_name = "healthcare"

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

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

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

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

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

Nachdem Sie die Patientenressource erstellt haben, erstellen Sie eine Encounter-Ressource zur Beschreibung einer Interaktion zwischen dem Patienten und einem Arzt.

Ersetzen Sie im Feld PATIENT_ID die ID aus der Antwort, die vom Server zurückgegeben wurde, als Sie die Patientenressource erstellt haben.

Die folgenden Beispiele für curl und PowerShell funktionieren mit R4-FHIR-Speichern. Das Python-Beispiel funktioniert mit STU3-FHIR-Speichern.

REST

Bevor Sie die Anfragedaten verwenden, ersetzen Sie die folgenden Werte:

  • PROJECT_ID ist die ID Ihres Google Cloud-Projekts
  • LOCATION ist der Standort des Datasets
  • DATASET_ID: das übergeordnete Dataset des FHIR-Speichers
  • FHIR_STORE_ID: die FHIR-Speicher-ID
  • PATIENT_ID: die Antwort, die vom Server zurückgegeben wurde, als Sie die Patientenressource erstellt haben

JSON-Text anfordern:

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

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

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

PowerShell

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

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

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

Sie sollten in etwa folgende JSON-Antwort erhalten:

Python

Folgen Sie der Einrichtungsanleitung für Python in der Cloud Healthcare API-Kurzanleitung zur Verwendung von Clientbibliotheken, bevor Sie dieses Beispiel ausprobieren. Weitere Informationen finden Sie in der Python API-Referenzdokumentation für die Cloud Healthcare API.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Cloud Healthcare API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

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

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

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

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

    api_version = "v1"
    service_name = "healthcare"

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

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

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

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

    return response

Erstellen Sie nach der Erstellung der Ressource „Encounter” eine Beobachtungsressource, die der Ressource „Encounter” zugeordnet ist. Die Beobachtungsressource liefert eine Messung der Herzfrequenz des Patienten in Schlägen pro Minute (BPM) (80 in bpm).

Die folgenden Beispiele für curl und PowerShell funktionieren mit R4-FHIR-Speichern. Das Python-Beispiel funktioniert mit STU3-FHIR-Speichern.

REST

Bevor Sie die Anfragedaten verwenden, ersetzen Sie die folgenden Werte:

  • PROJECT_ID ist die ID Ihres Google Cloud-Projekts
  • LOCATION ist der Standort des Datasets
  • DATASET_ID: das übergeordnete Dataset des FHIR-Speichers
  • FHIR_STORE_ID: die FHIR-Speicher-ID
  • PATIENT_ID: die ID in der Antwort, die vom Server zurückgegeben wurde, als Sie die Patientenressource erstellt haben
  • ENCOUNTER_ID: die ID in der Antwort, die vom Server zurückgegeben wurde, als Sie die Ressource „Encounter” erstellt haben

JSON-Text anfordern:

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

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

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

PowerShell

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

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

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

Sie sollten in etwa folgende JSON-Antwort erhalten:

Python

Folgen Sie der Einrichtungsanleitung für Python in der Cloud Healthcare API-Kurzanleitung zur Verwendung von Clientbibliotheken, bevor Sie dieses Beispiel ausprobieren. Weitere Informationen finden Sie in der Python API-Referenzdokumentation für die Cloud Healthcare API.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Cloud Healthcare API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

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

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

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

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

    api_version = "v1"
    service_name = "healthcare"

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

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

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

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

    return response

Bedingte Erstellung einer FHIR-Ressource

Das folgende curl-Beispiel zeigt, wie Sie mit der Methode projects.locations.datasets.fhirStores.fhir.create eine FHIR-Ressource bedingt erstellen können. Die Methode implementiert die bedingte FHIR-Interaktion create (DSTU2, STU3, R4).

Verwenden Sie die bedingte Erstellung, um doppelte FHIR-Ressourcen zu vermeiden. Beispielsweise hat jede Patientenressource auf einem FHIR-Server eine eindeutige Kennung, z. B. eine Krankenaktennummer (MRN). Wenn Sie eine neue Patientenressource erstellen und verifizieren möchten, dass keine Patientenressource mit derselben MRN bereits vorhanden ist, erstellen Sie die neue Ressource bedingt. Die Cloud Healthcare API erstellt die neue Ressource nur, wenn es keine Übereinstimmungen für die Suchanfrage gibt.

Die Antwort des Servers hängt davon ab, wie viele Ressourcen mit der Suchanfrage übereinstimmen:

Stimmt überein mit HTTP-Antwortcode Verhalten
Null 200 OK Erstellt die neue Ressource.
Eins 200 OK Erstellt keine neue Ressource.
Mehrere 412 Precondition Failed Erstellt keine neue Ressource und gibt den Fehler "search criteria are not selective enough" zurück.

Wenn Sie die bedingte create-Interaktion anstelle der create-Interaktion verwenden möchten, geben Sie in der Anfrage einen If-None-Exist-HTTP-Header an, der eine FHIR-Suchabfrage enthält:

If-None-Exist: FHIR_SEARCH_QUERY

In der Cloud Healthcare API v1 verwenden bedingte Vorgänge ausschließlich den Suchparameter identifier, wenn dieser für den FHIR-Ressourcentyp vorhanden ist, um zu bestimmen, welche FHIR-Ressourcen einer bedingten Suchanfrage entsprechen.

REST

Das folgende Beispiel zeigt, wie Sie eine Beobachtungsressource mit einem If-None-Exist: identifier=my-code-system|ABC-12345-HTTP-Header erstellen. Die Cloud Healthcare API erstellt die Ressource nur dann, wenn keine vorhandene Beobachtungsressource mit der Abfrage identifier=my-code-system|ABC-12345 übereinstimmt.

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

Die folgende Beispielausgabe zeigt absichtlich eine fehlgeschlagene Anfrage. Informationen zum Anzeigen der Antwort einer erfolgreichen Anfrage finden Sie unter FHIR-Ressource erstellen.

Wenn mehrere Beobachtungsressourcen mit der Abfrage übereinstimmen, gibt die Cloud Healthcare API die folgende Antwort zurück und die Anfrage zum Erstellen einer bedingten Erstellung schlägt fehl:

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

Eine FHIR-Ressource aktualisieren

Die folgenden Beispiele zeigen, wie die Methode projects.locations.datasets.fhirStores.fhir.update verwendet wird, um eine FHIR-Ressource zu aktualisieren. Die Methode implementiert die FHIR-Standardaktualisierungsinteraktion (DSTU2, STU3 und R4).

Wenn Sie eine Ressource aktualisieren, aktualisieren Sie den gesamten Inhalt der Ressource. Dies steht im Gegensatz zum Patchen einer Ressource, bei dem nur ein Teil einer Ressource aktualisiert wird.

Wenn für den FHIR-Speicher enableUpdateCreate festgelegt ist, wird die Anfrage als Upsert (Aktualisieren oder Einfügen) behandelt, das die Ressource aktualisiert, falls sie vorhanden ist, oder sie mit der angegebenen Anfrage einfügt, falls sie nicht vorhanden ist.

Der Anfragetext muss eine JSON-codierte FHIR-Ressource enthalten und die Anfrageheader müssen Content-Type: application/fhir+json enthalten. Die Ressource muss ein id-Element enthalten, dessen Wert mit der ID im REST-Pfad der Anfrage identisch ist.

Die folgenden Beispiele für curl und PowerShell funktionieren mit R4-FHIR-Speichern. Die Go-, Java-, Node.js- und Python-Beispiele funktionieren mit STU3-FHIR-Speichern.

REST

Die folgenden Beispiele zeigen, wie die Schläge pro Minute (SpM) in einer Beobachtungsressource aktualisiert werden.

Bevor Sie die Anfragedaten verwenden, ersetzen Sie die folgenden Werte:

  • PROJECT_ID ist die ID Ihres Google Cloud-Projekts
  • LOCATION ist der Standort des Datasets
  • DATASET_ID: das übergeordnete Dataset des FHIR-Speichers
  • FHIR_STORE_ID: die FHIR-Speicher-ID
  • OBSERVATION_ID: die ID der Beobachtungsressource
  • PATIENT_ID: die Patientenressourcen-ID
  • ENCOUNTER_ID: die ID der Ressource „Encounter“
  • BPM_VALUE: der Wert der Schläge pro Minute (SpM) in der aktualisierten Beobachtungsressource

JSON-Text anfordern:

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

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

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

PowerShell

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

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

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

APIs Explorer

Kopieren Sie den Anfragetext und öffnen Sie die Referenzseite für Methoden. Der API Explorer wird rechts auf der Seite geöffnet. Sie können mit diesem Tool interagieren, um Anfragen zu senden. Fügen Sie den Anfragetext in dieses Tool ein, füllen Sie alle Pflichtfelder aus und klicken Sie auf Ausführen.

Sie sollten in etwa folgende JSON-Antwort erhalten:

Go

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

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

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

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

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

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

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

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

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

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

	return nil
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
  headers: {'Content-Type': 'application/fhir+json'},
});

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

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

updateFhirResource();

Python

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

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

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

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

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

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

    api_version = "v1"
    service_name = "healthcare"

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

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

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

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

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

    return response

Eine FHIR-Ressource bedingt aktualisieren

Die folgenden Beispiele zeigen, wie die Methode projects.locations.datasets.fhirStores.fhir.conditionalUpdate aufgerufen wird, um eine FHIR-Ressource, die mit einer Suchanfrage übereinstimmt, zu aktualisieren, anstatt die Ressource anhand ihrer ID zu identifizieren. Die Methode implementiert die bedingte Aktualisierungsinteraktion des FHIR-Standards (DSTU2, STU3 und R4).

Ein bedingtes Update kann jeweils nur auf eine FHIR-Ressource angewendet werden.

Die vom Server zurückgegebene Antwort hängt davon ab, wie viele Übereinstimmungen basierend auf den Suchkriterien auftreten:

  • Eine Übereinstimmung: Die Ressource wurde erfolgreich aktualisiert oder ein Fehler wird zurückgegeben.
  • Mehr als eine Übereinstimmung: Die Anfrage gibt einen 412 Precondition Failed-Fehler zurück.
  • Keine Übereinstimmungen mit einem id: Wenn die Suchkriterien keine Übereinstimmungen identifizieren, der bereitgestellte Anfragetext einen id enthält und der FHIR-Speicher enableUpdateCreate auf true gesetzt ist, wird die FHIR-Ressource mit der id im Anfragetext erstellt.
  • Keine Übereinstimmungen ohne id: Wenn die Suchkriterien keine Übereinstimmungen identifizieren und der angegebene Anfragetext kein id enthält, wird die FHIR-Ressource mit einer vom Server zugewiesenen ID erstellt, als ob die Ressource mit projects.locations.datasets.fhirStores.fhir.create erstellt worden wäre.

Der Anfragetext muss eine JSON-codierte FHIR-Ressource enthalten und die Anfrageheader müssen Content-Type: application/fhir+json enthalten.

In der Cloud Healthcare API v1 verwenden bedingte Vorgänge ausschließlich den Suchparameter identifier, wenn dieser für den FHIR-Ressourcentyp vorhanden ist, um zu bestimmen, welche FHIR-Ressourcen einer bedingten Suchanfrage entsprechen.

REST

Im folgenden Beispiel wird gezeigt, wie Sie eine PUT-Anfrage mit curl und PowerShell senden, um eine Beobachtungsressource mit der Beobachtungs-ID (ABC-12345 in my-code-system) zu bearbeiten. Die Beobachtung liefert eine Messung der Herzschläge eines Patienten pro Minute (SpM).

Bevor Sie die Anfragedaten verwenden, ersetzen Sie die folgenden Werte:

  • PROJECT_ID ist die ID Ihres Google Cloud-Projekts
  • LOCATION ist der Standort des Datasets
  • DATASET_ID: das übergeordnete Dataset des FHIR-Speichers
  • FHIR_STORE_ID: die FHIR-Speicher-ID
  • PATIENT_ID: die Patientenressourcen-ID
  • ENCOUNTER_ID: die ID der Ressource „Encounter“
  • BPM_VALUE: der Wert der Schläge pro Minute (SpM) in der Beobachtungsressource

JSON-Text anfordern:

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

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

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

PowerShell

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

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

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

APIs Explorer

Kopieren Sie den Anfragetext und öffnen Sie die Referenzseite für Methoden. Der API Explorer wird rechts auf der Seite geöffnet. Sie können mit diesem Tool interagieren, um Anfragen zu senden. Fügen Sie den Anfragetext in dieses Tool ein, füllen Sie alle Pflichtfelder aus und klicken Sie auf Ausführen.

Sie sollten in etwa folgende JSON-Antwort erhalten:

Eine FHIR-Ressource patchen

In den folgenden Beispielen wird gezeigt, wie Sie die Methode projects.locations.datasets.fhirStores.fhir.patch zum Patchen einer FHIR-Ressource aufrufen. Die Methode implementiert die FHIR-Standardpatch-Interaktion (DSTU2, STU3 und R4).

Beim Patchen einer Ressource aktualisieren Sie einen Teil der Ressource, indem Sie die in einem JSON Patch-Dokument angegebenen Vorgänge anwenden.

Die Anfrage muss ein JSON-Patchdokument enthalten und die Anfrageheader müssen Content-Type: application/json-patch+json enthalten.

Die folgenden Beispiele zeigen, wie eine Beobachtungsressource gepatcht werden kann. Die Beobachtung der Herzschläge eines Patienten pro Minute (SpM) wird mit dem replace-Patch-Vorgang aktualisiert.

Die folgenden Beispiele für curl und PowerShell funktionieren mit R4-FHIR-Speichern. Die Go-, Java-, Node.js- und Python-Beispiele funktionieren mit STU3-FHIR-Speichern.

REST

Bevor Sie die Anfragedaten verwenden, ersetzen Sie die folgenden Werte:

  • PROJECT_ID ist die ID Ihres Google Cloud-Projekts
  • LOCATION ist der Standort des Datasets
  • DATASET_ID: das übergeordnete Dataset des FHIR-Speichers
  • FHIR_STORE_ID: die FHIR-Speicher-ID
  • OBSERVATION_ID: die ID der Beobachtungsressource
  • BPM_VALUE: der Wert der Schläge pro Minute (SpM) in der gepatchten Beobachtungsressource

JSON-Text anfordern:

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

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

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

PowerShell

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

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

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

Sie sollten in etwa folgende JSON-Antwort erhalten:

Go

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

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

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

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

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

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

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

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

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

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

	return nil
}

Java

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

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

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

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

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

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

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

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

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

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

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

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

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
  headers: {'Content-Type': 'application/json-patch+json'},
});

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

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

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

patchFhirResource();

Python

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

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

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

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

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

    api_version = "v1"
    service_name = "healthcare"

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

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

    # The following sample body works with a Patient resource and isn't guaranteed
    # to work with other types of FHIR resources. If necessary,
    # supply a new body with data that corresponds to the resource you
    # are updating.
    patient_body = [{"op": "replace", "path": "/active", "value": False}]

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

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

    response = request.execute()

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

    return response

PATCH-Anfrage in einem FHIR-Bundle ausführen

Sie können eine PATCH-Anfrage in einem FHIR-Bundle (nur FHIR R4) angeben. Wenn Sie eine PATCH-Anfrage in einem FHIR-Bundle ausführen, können Sie viele FHIR-Ressourcen gleichzeitig patchen. So müssen Sie nicht für jede FHIR-Ressource einzelne Patchanfragen stellen.

Wenn Sie eine PATCH-Anfrage in einem Bundle stellen möchten, geben Sie die folgenden Informationen in einem resource-Objekt in der Anfrage an:

  • Das Feld resourceType ist auf Binary festgelegt
  • Das Feld contentType ist auf application/json-patch+json festgelegt
  • Der in base64-codierte Patchtext

Das resource-Objekt sollte so aussehen:

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

Das folgende Beispiel zeigt den Patchtext, der im Feld data in base64 codiert wurde:

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

Die folgenden Beispiele zeigen, wie Sie mit einer PATCH-Anfrage in einem Bundle die Patientenressource aktualisieren, die Sie unter Eine FHIR-Ressource erstellen erstellt haben, mit einem birthDate-Wert von 1990-01-01 patchen:

Bevor Sie die Anfragedaten verwenden, ersetzen Sie die folgenden Werte:

  • PROJECT_ID: Ihre Google Cloud-Projekt-ID
  • LOCATION: der Speicherort des übergeordneten Datasets
  • DATASET_ID: das übergeordnete Dataset des FHIR-Speichers
  • FHIR_STORE_ID: die FHIR-Speicher-ID
  • PATIENT_ID: die ID einer vorhandenen Patientenressource

JSON-Text anfordern:

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

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

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

PowerShell

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

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

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

Sie sollten in etwa folgende JSON-Antwort erhalten:

Eine FHIR-Ressource bedingt patchen

Die folgenden Beispiele zeigen, wie die Methode projects.locations.datasets.fhirStores.fhir.conditionalPatch aufgerufen wird, um eine FHIR-Ressource, die mit einer Suchanfrage übereinstimmt, zu korrigieren, anstatt die Ressource anhand ihrer ID zu identifizieren. Die Methode implementiert die bedingte Patch-Interaktion des FHIR-Standards (DSTU2, STU3 und R4).

Ein bedingter Patch kann jeweils nur auf eine Ressource angewendet werden. Wenn die Suchkriterien mehr als eine Übereinstimmung identifizieren, gibt die Anfrage den Fehler 412 Precondition Failed zurück.

In der Cloud Healthcare API v1 verwenden bedingte Vorgänge ausschließlich den Suchparameter identifier, wenn dieser für den FHIR-Ressourcentyp vorhanden ist, um zu bestimmen, welche FHIR-Ressourcen einer bedingten Suchanfrage entsprechen.

REST

Das folgende Beispiel zeigt, wie Sie eine PATCH-Anfrage mit curl und PowerShell senden, um eine Beobachtungsressource zu bearbeiten, wenn die ID der Beobachtung in my-code-system ABC-12345 ist. Die Beobachtung der Herzschläge eines Patienten pro Minute (BPM) wird mit dem replace-Patch-Vorgang aktualisiert.

Bevor Sie die Anfragedaten verwenden, ersetzen Sie die folgenden Werte:

  • PROJECT_ID ist die ID Ihres Google Cloud-Projekts
  • LOCATION ist der Standort des Datasets
  • DATASET_ID: das übergeordnete Dataset des FHIR-Speichers
  • FHIR_STORE_ID: die FHIR-Speicher-ID
  • BPM_VALUE: der Wert der Schläge pro Minute (SpM) in der Beobachtungsressource

JSON-Text anfordern:

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

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

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

PowerShell

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

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

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

APIs Explorer

Kopieren Sie den Anfragetext und öffnen Sie die Referenzseite für Methoden. Der API Explorer wird rechts auf der Seite geöffnet. Sie können mit diesem Tool interagieren, um Anfragen zu senden. Fügen Sie den Anfragetext in dieses Tool ein, füllen Sie alle Pflichtfelder aus und klicken Sie auf Ausführen.

Sie sollten in etwa folgende JSON-Antwort erhalten:

Eine FHIR-Ressource erhalten

Die folgenden Beispiele zeigen, wie Sie mit der Methode projects.locations.datasets.fhirStores.fhir.read den Inhalt einer FHIR-Ressource abrufen.

Die folgenden Beispiele für curl und PowerShell funktionieren mit R4-FHIR-Speichern. Die Go-, Java-, Node.js- und Python-Beispiele funktionieren mit STU3-FHIR-Speichern.

Console

So rufen Sie den Inhalt einer FHIR-Ressource ab:

  1. Rufen Sie in der Google Cloud Console die Seite FHIR-Betrachter auf.

    Zum FHIR-Viewer

  2. Wählen Sie in der Drop-down-Liste FHIR-Speicher ein Dataset und dann einen FHIR-Speicher im Dataset aus.

  3. Suchen Sie nach den Ressourcentypen, die Sie anzeigen möchten, um die Liste der Ressourcentypen zu filtern.

  4. Klicken Sie auf das Feld Ressourcentyp.

  5. Wählen Sie in der nun angezeigten Drop-down-Liste Attribute die Option Ressourcentyp aus.

  6. Geben Sie einen Ressourcentyp ein.

  7. Wenn Sie nach einem anderen Ressourcentyp suchen möchten, wählen Sie aus der nun angezeigten Drop-down-Liste Operatoren OR aus und geben einen anderen Ressourcentyp ein.

  8. Wählen Sie in der Liste der Ressourcentypen den Typ der Ressource aus, für die Sie Inhalte abrufen möchten.

  9. Wählen Sie in der angezeigten Tabelle eine Ressource aus oder suchen Sie nach einer Ressource.

REST

Die folgenden Beispiele zeigen, wie Sie die Details der in einem vorherigen Abschnitt erstellten Beobachtungsressource abrufen können.

Bevor Sie die Anfragedaten verwenden, ersetzen Sie die folgenden Werte:

  • PROJECT_ID ist die ID Ihres Google Cloud-Projekts
  • LOCATION ist der Standort des Datasets
  • DATASET_ID: das übergeordnete Dataset des FHIR-Speichers
  • FHIR_STORE_ID: die FHIR-Speicher-ID
  • OBSERVATION_ID: die ID der Beobachtungsressource

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Führen Sie folgenden Befehl aus:

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

PowerShell

Führen Sie folgenden Befehl aus:

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

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

APIs Explorer

Öffnen Sie die Methodenreferenzseite. Der API Explorer wird rechts auf der Seite geöffnet. Sie können mit diesem Tool interagieren, um Anfragen zu senden. Füllen Sie die Pflichtfelder aus und klicken Sie auf Ausführen.

Sie sollten in etwa folgende JSON-Antwort erhalten:

Go

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

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

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

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

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

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

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

	defer resp.Body.Close()

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

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

	return nil
}

Java

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

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

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

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

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

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

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

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

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

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

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

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

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

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

getFhirResource();

Python

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

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

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

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

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

    api_version = "v1"
    service_name = "healthcare"

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

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

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

    return response

Alle Ressourcen für den Patientenbereich abrufen

Die folgenden Beispiele zeigen, wie Sie alle Ressourcen abrufen, die mit einem bestimmten Patientenbereich (DSTU2, STU3 und R4) verknüpft sind. Weitere Informationen finden Sie unter projects.locations.datasets.fhirStores.fhir.Patient-everything.

Die folgenden Beispiele für curl und PowerShell funktionieren mit R4-FHIR-Speichern. Die Go-, Java-, Node.js- und Python-Beispiele funktionieren mit STU3-FHIR-Speichern.

curl

Wenn Sie die Ressourcen in einem Patientenbereich abrufen möchten, senden Sie eine GET-Anfrage und geben Sie die folgenden Informationen an:

  • Der Name des übergeordneten Datasets
  • Der Name des FHIR-Speichers
  • Die Patienten-ID
  • Ein Zugriffstoken

Das folgende Beispiel zeigt eine GET-Anfrage mit curl.

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"

Wenn die Anfrage erfolgreich ist, gibt der Server eine Antwort wie die folgende im JSON-Format zurück:

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

PowerShell

Wenn Sie die Ressourcen in einem Patientenbereich abrufen möchten, senden Sie eine GET-Anfrage und geben Sie die folgenden Informationen an:

  • Der Name des übergeordneten Datasets
  • Der Name des FHIR-Speichers
  • Die Patienten-ID
  • Ein Zugriffstoken

Das folgende Beispiel zeigt eine GET-Anfrage mit PowerShell:

$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

Wenn die Anfrage erfolgreich ist, gibt der Server eine Antwort wie diese im JSON-Format zurück:

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

Go

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

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

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

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

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

	defer resp.Body.Close()

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

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

	return nil
}

Java

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

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

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

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

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

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

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

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

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

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

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

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

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

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

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

getPatientEverything();

Python

def get_patient_everything(
    project_id,
    location,
    dataset_id,
    fhir_store_id,
    resource_id,
):
    """Gets all the resources in the patient compartment.

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

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

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

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

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

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

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

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

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

    resource = response.json()

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

    return resource

Ressourcen für Patientenbereich, gefiltert nach Typ oder Datum

In den folgenden Beispielen wird gezeigt, wie Sie alle Ressourcen seit einem bestimmten Datum und einer bestimmten Uhrzeit abrufen, die mit einem bestimmten Patientenbereich (R4) verbunden und nach einer Liste von Typen gefiltert sind. Weitere Informationen finden Sie unter projects.locations.datasets.fhirStores.fhir.Patient-everything.

Die folgenden Beispiele für curl und PowerShell funktionieren mit R4-FHIR-Speichern.

curl

Wenn Sie die Ressourcen in einem Patientenbereich eines angegebenen Typs und seit einem bestimmten Datum benötigen, stellen Sie eine GET-Anfrage und geben Sie die folgenden Informationen an:

  • Der Name des übergeordneten Datasets
  • Der Name des FHIR-Speichers
  • Die Patienten-ID
  • Ein Abfragestring, der eine kommagetrennte Liste von Ressourcentypen und das Startdatum enthält
  • Ein Zugriffstoken

Das folgende Beispiel zeigt eine GET-Anfrage mit curl.

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"

Wenn die Anfrage erfolgreich ist, gibt der Server alle Ressourcen zurück, die die angegebenen Kriterien im JSON-Format erfüllen.

PowerShell

Wenn Sie die Ressourcen in einem Patientenbereich eines angegebenen Typs und seit einem bestimmten Datum benötigen, stellen Sie eine GET-Anfrage und geben Sie die folgenden Informationen an:

  • Der Name des übergeordneten Datasets
  • Der Name des FHIR-Speichers
  • Die Patienten-ID
  • Ein Abfragestring, der eine kommagetrennte Liste von Ressourcentypen und das Startdatum enthält
  • Ein Zugriffstoken

Das folgende Beispiel zeigt eine GET-Anfrage mit PowerShell:

$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

Wenn die Anfrage erfolgreich ist, gibt der Server alle Ressourcen zurück, die die angegebenen Kriterien im JSON-Format erfüllen.

FHIR-Ressourcen-Versionen auflisten

Die folgenden Beispiele zeigen, wie alle historischen Versionen einer FHIR-Ressource aufgelistet werden. Weitere Informationen finden Sie unter projects.locations.datasets.fhirStores.fhir.history.

Die Beispiele verwenden die in Erstellen einer FHIR-Ressource erstellten Ressourcen und zeigen, wie die Versionen einer Beobachtungsressource aufgelistet werden.

Die folgenden Beispiele für curl und PowerShell funktionieren mit R4-FHIR-Speichern. Die Go-, Java-, Node.js- und Python-Beispiele funktionieren mit STU3-FHIR-Speichern.

curl

Das folgende Beispiel zeigt, wie alle Versionen einer Beobachtungsressource aufgelistet werden. Die Beobachtung wurde einmal nach der ursprünglichen Erstellung aktualisiert, um die Herzschläge des Patienten pro Minute zu ändern.

Wenn Sie alle Versionen einer FHIR-Ressource auflisten möchten, einschließlich der aktuellen und aller gelöschten Versionen, stellen Sie eine GET-Anfrage und geben Sie die folgenden Informationen an:

  • Der Name des übergeordneten Datasets
  • Der Name des FHIR-Speichers
  • Ressourcentyp und ID
  • Ein Zugriffstoken

Das folgende Beispiel zeigt eine GET-Anfrage mit curl.

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"

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück: In diesem Beispiel werden zwei Versionen der Beobachtung zurückgegeben. In der ersten Version betrug die Herzfrequenz des Patienten 75 Schläge pro Minute. In der zweiten Version lag die Herzfrequenz des Patienten bei 85 Schlägen pro Minute.

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

PowerShell

Das folgende Beispiel zeigt, wie alle Versionen einer Beobachtungsressource aufgelistet werden. Die Beobachtung wurde einmal nach der ursprünglichen Erstellung aktualisiert, um die Herzschläge des Patienten pro Minute zu ändern.

Wenn Sie alle Versionen einer FHIR-Ressource auflisten möchten, einschließlich der aktuellen und aller gelöschten Versionen, stellen Sie eine GET-Anfrage und geben Sie die folgenden Informationen an:

  • Der Name des übergeordneten Datasets
  • Der Name des FHIR-Speichers
  • Ressourcentyp und ID
  • Ein Zugriffstoken

Das folgende Beispiel zeigt eine GET-Anfrage mit PowerShell.

$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

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück: In diesem Beispiel werden zwei Versionen der Beobachtung zurückgegeben. In der ersten Version betrug die Herzfrequenz des Patienten 75 Schläge pro Minute. In der zweiten Version lag die Herzfrequenz des Patienten bei 85 Schlägen pro Minute.

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

Go

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

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

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

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

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

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

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

	defer resp.Body.Close()

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

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

	return nil
}

Java


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

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

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

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

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

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

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

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

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

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

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

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

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

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

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

listFhirResourceHistory();

Python

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

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

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

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

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

    api_version = "v1"
    service_name = "healthcare"

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

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

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

Eine FHIR-Ressourcenversion abrufen

Die folgenden Beispiele zeigen, wie Sie eine bestimmte Version einer Ressource abrufen können. Weitere Informationen finden Sie unter projects.locations.datasets.fhirStores.fhir.vread.

Die Versions-IDs für die Beobachtungsressource aus der Liste der FHIR-Ressourcenversionen sind unten hervorgehoben:

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

In den folgenden Beispielen werden die unter Erstellen einer FHIR-Ressource erstellten Ressourcen verwendet und es wird gezeigt, wie eine Beobachtungsressource angezeigt wird.

Die folgenden Beispiele für curl und PowerShell funktionieren mit R4-FHIR-Speichern. Die Go-, Node.js- und Python-Beispiele funktionieren mit STU3 FHIR-Speichern.

curl

Um eine bestimmte Version einer FHIR-Ressource abzurufen, senden Sie eine GET-Anfrage und geben Sie die folgenden Informationen an:

  • Der Name des übergeordneten Datasets
  • Der Name des FHIR-Speichers
  • Ressourcentyp und ID
  • Die Ressourcenversion
  • Ein Zugriffstoken

Das folgende Beispiel zeigt eine GET-Anfrage mit curl.

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"

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück: In diesem Beispiel wird die erste Version der Beobachtung zurückgegeben, bei der die Herzfrequenz des Patienten 75 Schlägen pro Minute entspricht.

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

PowerShell

Um eine bestimmte Version einer FHIR-Ressource abzurufen, senden Sie eine GET-Anfrage und geben Sie die folgenden Informationen an:

  • Der Name des übergeordneten Datasets
  • Der Name des FHIR-Speichers
  • Ressourcentyp und ID
  • Die Ressourcenversion
  • Ein Zugriffstoken

Das folgende Beispiel zeigt eine GET-Anfrage mit curl.

$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

Wenn die Anfrage erfolgreich ist, gibt der Server die Antwort im JSON-Format zurück: In diesem Beispiel wird die erste Version der Beobachtung zurückgegeben, bei der die Herzfrequenz des Patienten 75 Schlägen pro Minute entspricht.

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

Go

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

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

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

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

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

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

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

	defer resp.Body.Close()

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

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

	return nil
}

Java

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

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

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

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

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

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

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

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

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

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

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

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

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

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

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

getFhirResourceHistory();

Python

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

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

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

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

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

    api_version = "v1"
    service_name = "healthcare"

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

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

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

    return response

Eine FHIR-Ressource löschen

Die folgenden Beispiele zeigen, wie die Methode projects.locations.datasets.fhirStores.fhir.delete aufgerufen wird, um eine Beobachtungs-FHIR-Ressource zu löschen.

Unabhängig davon, ob der Vorgang erfolgreich ist oder nicht, gibt der Server den HTTP-Statuscode 200 OK zurück. Wenn Sie prüfen möchten, ob die Ressource erfolgreich gelöscht wurde, suchen oder holen Sie die Ressource und prüfen Sie, ob sie vorhanden ist.

Die folgenden Beispiele für curl und PowerShell funktionieren mit R4-FHIR-Speichern. Die Go-, Java-, Node.js- und Python-Beispiele funktionieren mit STU3-FHIR-Speichern.

REST

Bevor Sie die Anfragedaten verwenden, ersetzen Sie die folgenden Werte:

  • PROJECT_ID ist die ID Ihres Google Cloud-Projekts
  • LOCATION ist der Standort des Datasets
  • DATASET_ID: das übergeordnete Dataset des FHIR-Speichers
  • FHIR_STORE_ID: die FHIR-Speicher-ID
  • OBSERVATION_ID: die ID der Beobachtungsressource

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Führen Sie folgenden Befehl aus:

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

PowerShell

Führen Sie folgenden Befehl aus:

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

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

APIs Explorer

Öffnen Sie die Methodenreferenzseite. Der API Explorer wird rechts auf der Seite geöffnet. Sie können mit diesem Tool interagieren, um Anfragen zu senden. Füllen Sie die Pflichtfelder aus und klicken Sie auf Ausführen.

Sie sollten in etwa folgende JSON-Antwort erhalten:

Go

import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

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

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

	return nil
}

Java

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

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

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

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

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

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

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

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

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

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

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

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

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

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

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

deleteFhirResource();

Python

def delete_resource(
    project_id: str,
    location: str,
    dataset_id: str,
    fhir_store_id: str,
    resource_type: str,
    resource_id: str,
) -> dict:
    """Deletes a FHIR resource.

    Regardless of whether the operation succeeds or
    fails, the server returns a 200 OK HTTP status code. To check that the
    resource was successfully deleted, search for or get the resource and
    see if it exists.

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

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

    api_version = "v1"
    service_name = "healthcare"

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

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

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

    return response

Eine FHIR-Ressource unter Bedingungen löschen

In der Cloud Healthcare API v1 verwenden bedingte Vorgänge ausschließlich den Suchparameter identifier, wenn dieser für den FHIR-Ressourcentyp vorhanden ist, um zu bestimmen, welche FHIR-Ressourcen einer bedingten Suchanfrage entsprechen.

Eine FHIR-Ressource stimmt nur dann mit der Abfrage ?identifier=my-code-system|ABC-12345 überein, wenn die identifier.system der Ressource my-code-system und ihr identifier.value ABC-12345 ist. Wenn eine FHIR-Ressource mit der Abfrage übereinstimmt, löscht die Cloud Healthcare API die Ressource.

Wenn die Abfrage den Suchparameter identifier verwendet und mit mehreren FHIR-Ressourcen übereinstimmt, gibt die Cloud Healthcare API den Fehler "412 - Condition not selective enough" zurück. So löschen Sie die Ressourcen einzeln:

  1. Suchen Sie nach jeder Ressource, um ihre eindeutige, vom Server zugewiesene ID zu erhalten.
  2. Löschen Sie jede Ressource einzeln anhand der ID.

In den folgenden Beispielen wird gezeigt, wie Sie eine FHIR-Ressource, die mit einer Suchanfrage übereinstimmt, bedingt löschen, anstatt die FHIR-Ressource anhand ihrer ID zu identifizieren. Bei der Suchanfrage wird eine Beobachtungsressource anhand der ID der Beobachtung (ABC-12345 in my-code-system) abgeglichen und gelöscht.

REST

Verwenden Sie die Methode projects.locations.datasets.fhirStores.fhir.conditionalDelete.

Bevor Sie die Anfragedaten verwenden, ersetzen Sie die folgenden Werte:

  • PROJECT_ID ist die ID Ihres Google Cloud-Projekts
  • LOCATION ist der Standort des Datasets
  • DATASET_ID: das übergeordnete Dataset des FHIR-Speichers
  • FHIR_STORE_ID ist die FHIR-Speicher-ID

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Führen Sie folgenden Befehl aus:

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

PowerShell

Führen Sie folgenden Befehl aus:

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

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

APIs Explorer

Öffnen Sie die Methodenreferenzseite. Der API Explorer wird rechts auf der Seite geöffnet. Sie können mit diesem Tool interagieren, um Anfragen zu senden. Füllen Sie die erforderlichen Felder aus und klicken Sie auf Ausführen.

Sie sollten einen erfolgreichen Statuscode (2xx) und eine leere Antwort als Ausgabe erhalten.

Historische Versionen einer FHIR-Ressource löschen

In den folgenden Beispielen wird gezeigt, wie Sie alle Verlaufsversionen einer FHIR-Ressource löschen. Weitere Informationen finden Sie unter projects.locations.datasets.fhirStores.fhir.Resource-purge.

Der Aufruf der Methode projects.locations.datasets.fhirStores.fhir.Resource-purge ist auf Nutzer (Aufrufer) mit der Rolle roles/healthcare.fhirStoreAdmin beschränkt. Nutzer mit der Rolle roles/healthcare.fhirResourceEditor können die Methode nicht aufrufen. So lassen Sie zu, dass ein Aufrufer historische Versionen einer FHIR-Ressource löscht:

Die Beispiele verwenden die unter FHIR-Ressource erstellen erstellten Ressourcen und zeigen, wie die Verlaufsversionen einer Beobachtungsressource gelöscht werden.

Die folgenden Beispiele für curl und PowerShell funktionieren mit R4-FHIR-Speichern. Die Go-, Java-, Node.js- und Python-Beispiele funktionieren mit STU3-FHIR-Speichern.

curl

Wenn Sie alle historischen Versionen einer FHIR-Ressource löschen möchten, senden Sie eine DELETE-Anfrage und geben Sie die folgenden Informationen an:

  • Der Name des übergeordneten Datasets
  • Der Name des FHIR-Speichers
  • Ressourcentyp und ID
  • Ein Zugriffstoken

Das folgende Beispiel zeigt eine DELETE-Anfrage mit curl.

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"

Wenn die Anfrage erfolgreich ist, gibt der Server den leeren Antworttext im JSON-Format zurück:

{}

PowerShell

Wenn Sie alle historischen Versionen einer FHIR-Ressource löschen möchten, senden Sie eine DELETE-Anfrage und geben Sie die folgenden Informationen an:

  • Der Name des übergeordneten Datasets
  • Der Name des FHIR-Speichers
  • Ressourcentyp und ID
  • Ein Zugriffstoken

Das folgende Beispiel zeigt eine DELETE-Anfrage mit PowerShell.

$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

Wenn die Anfrage erfolgreich ist, gibt der Server den leeren Antworttext im JSON-Format zurück:

{}

Go

import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

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

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

	return nil
}

Java

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

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

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

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

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

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

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

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

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

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

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

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

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

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

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

deleteFhirResourcePurge();

Python

def delete_resource_purge(
    project_id: str,
    location: str,
    dataset_id: str,
    fhir_store_id: str,
    resource_type: str,
    resource_id: str,
) -> dict:
    """Deletes all versions of a FHIR resource (excluding the current version).

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

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

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

    api_version = "v1"
    service_name = "healthcare"

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

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

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