יצירה וניהול של משאבי FHIR

בדף הזה מוסבר איך ליצור, לעדכן, לתקן, לראות, להציג ברשימה, לאחזר ולמחוק משאבי FHIR.

משאב FHIR יכול להכיל נתונים על מטופל, על מכשיר, על תצפית ועוד. רשימה מלאה של משאבי FHIR זמינה במדד משאבי FHIR‏ (DSTU2,‏ STU3,‏ R4 או R5).

הדוגמאות של REST שבדף הזה פועלות עם מאגר R4 FHIR, ולא מובטח שהן יפעלו אם אתם משתמשים במאגר DSTU2 או STU3 FHIR. אם אתם משתמשים בחנות FHIR בגרסה DSTU2 או STU3, תוכלו לעיין במסמכי ה-FHIR הרשמיים כדי לקבל מידע על המרת הדוגמאות לגרסת ה-FHIR שבה אתם משתמשים.

הדוגמאות של Go,‏ Java,‏ Node.js ו-Python פועלות עם מאגר STU3 FHIR.

יצירת משאב FHIR

כדי ליצור משאבי FHIR, צריך קודם ליצור מאגר FHIR.

בדוגמאות של REST ו-Python אפשר לראות איך ליצור את משאבי ה-FHIR הבאים:

  1. משאב Patient (DSTU2, STU3, R4, and R5)
  2. ‫An Encounter (DSTU2, STU3, R4, and R5) resource for the Patient
  3. משאב Observation ‏(DSTU2,‏ STU3,‏ R4 ו-R5) של Encounter

בדוגמאות לכל שאר השפות מוסבר איך ליצור משאב FHIR כללי.

מידע נוסף זמין במאמר projects.locations.datasets.fhirStores.fhir.create.

דוגמאות ה-REST הבאות פועלות עם מאגרי R4 FHIR. הדוגמאות של Go,‏ Java,‏ Node.js ו-Python פועלות עם מאגרי STU3 FHIR.

המסוף

כדי להעלות משאבי FHIR באמצעות JSON למאגר FHIR, מבצעים את השלבים הבאים:

  1. במסוף Google Cloud , פותחים את הדף FHIR Viewer.

    ל-FHIR Viewer

  2. בתפריט הנפתח FHIR Store, בוחרים מערך נתונים ואז בוחרים FHIR Store במערך הנתונים.
  3. לוחצים על הכרטיסייה העלאה.
  4. באזור הטקסט, מזינים משאב FHIR תקין בפורמט JSON. לדוגמה:

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

    הערה: אפשר גם להזין מערך JSON של כמה אובייקטים של משאבי FHIR.
  5. לוחצים על Save. אחרי שההעלאה מסתיימת, אפשר לראות את המשאבים ב-FHIR Viewer. איך מקבלים משאב FHIR

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud
  • LOCATION: המיקום של מערך הנתונים
  • DATASET_ID: מערך הנתונים הראשי של מאגר FHIR
  • FHIR_STORE_ID: מזהה מאגר ה-FHIR

תוכן בקשת JSON:

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

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

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

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

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

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

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

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

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

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

Go

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

	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 := io.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'},
  responseType: 'json',
});

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

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

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

createFhirResource();

Python

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


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

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

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

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

    api_version = "v1"
    service_name = "healthcare"

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

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

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

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

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

אחרי שיוצרים את משאב המטופל, יוצרים משאב Encounter כדי לתאר אינטראקציה בין המטופל לבין איש מקצוע.

בשדה PATIENT_ID, מחליפים את המזהה מהתגובה שהוחזרה על ידי השרת כשיוצרים את מקור המידע של המטופל.

דוגמאות ה-REST הבאות פועלות עם מאגרי R4 FHIR. דוגמת ה-Python פועלת עם מאגרי STU3 FHIR.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud
  • LOCATION: המיקום של מערך הנתונים
  • DATASET_ID: מערך הנתונים הראשי של מאגר FHIR
  • FHIR_STORE_ID: מזהה מאגר ה-FHIR
  • PATIENT_ID: התגובה שהוחזרה על ידי השרת כשנוצר משאב המטופל

תוכן בקשת JSON:

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

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

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

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

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

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

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

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

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

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Python הוראות ההגדרה במאמר מדריך למתחילים לעבודה עם Cloud Healthcare API באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Cloud Healthcare API Python API.

כדי לבצע אימות ב-Cloud Healthcare API, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

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

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

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

    api_version = "v1"
    service_name = "healthcare"

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

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

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

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

    return response

אחרי שיוצרים את משאב Encounter, יוצרים משאב Observation שמשויך למשאב Encounter. משאב התצפית מספק מדידה של הדופק של המטופל בפעימות לדקה (BPM) (80 ב-bpm).

דוגמאות ה-REST הבאות פועלות עם מאגרי R4 FHIR. דוגמת ה-Python פועלת עם מאגרי STU3 FHIR.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud
  • LOCATION: המיקום של מערך הנתונים
  • DATASET_ID: מערך הנתונים הראשי של מאגר FHIR
  • FHIR_STORE_ID: מזהה מאגר ה-FHIR
  • PATIENT_ID: המזהה בתגובה שהוחזרה מהשרת כשיוצרים את משאב המטופל
  • ENCOUNTER_ID: המזהה בתגובה שמוחזרת מהשרת כשיוצרים את משאב המפגש

תוכן בקשת JSON:

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

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

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

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

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

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

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

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

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

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Python הוראות ההגדרה במאמר מדריך למתחילים לעבודה עם Cloud Healthcare API באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Cloud Healthcare API Python API.

כדי לבצע אימות ב-Cloud Healthcare API, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

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

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

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

    api_version = "v1"
    service_name = "healthcare"

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

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

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

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

    return response

יצירה מותנית של משאב FHIR

בדוגמה הבאה של curl אפשר לראות איך משתמשים בשיטה projects.locations.datasets.fhirStores.fhir.create כדי ליצור משאב FHIR באופן מותנה. השיטה מיישמת את האינטראקציה המותנית של FHIR‏ create (DSTU2, ‏ STU3, ‏ R4, ‏ R5).

אפשר להשתמש ביצירה מותנית כדי להימנע מיצירה של משאבי FHIR כפולים. לדוגמה, לכל משאב Patient בשרת FHIR יש בדרך כלל מזהה ייחודי, כמו מספר תיק רפואי (MRN). כדי ליצור משאב חדש מסוג Patient (מטופל) ולוודא שלא קיים משאב מסוג Patient עם אותו מספר רשומה רפואית (MRN), יוצרים את המשאב החדש באופן מותנה באמצעות שאילתת חיפוש. ‫Cloud Healthcare API יוצר את המשאב החדש רק אם אין התאמות לשאילתת החיפוש.

התגובה של השרת תלויה במספר המשאבים שתאמו לשאילתת החיפוש:

התאמות קוד תגובת HTTP התנהגות
אפס 201 CREATED יוצר את המשאב החדש.
אחד 200 OK לא יוצר משאב חדש.
יותר מאחד 412 Precondition Failed לא נוצר משאב חדש ומוחזרת שגיאה "search criteria are not selective enough".

כדי להשתמש באינטראקציה create עם תנאי במקום באינטראקציה create, צריך לציין בבקשה כותרת HTTP ‏If-None-Exist שמכילה שאילתת חיפוש ב-FHIR:

If-None-Exist: FHIR_SEARCH_QUERY

ב-Cloud Healthcare API v1, פעולות מותנות משתמשות באופן בלעדי בפרמטר החיפוש identifier, אם הוא קיים עבור סוג משאב FHIR, כדי לקבוע אילו משאבי FHIR תואמים לשאילתת חיפוש מותנית.

REST

בדוגמה הבאה מוצג אופן היצירה של משאב Observation באמצעות כותרת HTTP‏ If-None-Exist: identifier=my-code-system|ABC-12345. ‫Cloud Healthcare API יוצר את המשאב רק אם אין משאב Observation קיים שתואם לשאילתה identifier=my-code-system|ABC-12345.

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

בדוגמה הבאה של פלט מוצגת בכוונה בקשה שנכשלה. כדי לראות את התגובה מבקשה שהצליחה, אפשר לעיין במאמר בנושא יצירת משאב FHIR.

אם כמה משאבי Observation תואמים לשאילתה, Cloud Healthcare API מחזיר את התגובה הבאה, והבקשה ליצירה מותנית נכשלת:

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

עדכון משאב FHIR

בדוגמאות הבאות אפשר לראות איך משתמשים בשיטה projects.locations.datasets.fhirStores.fhir.update כדי לעדכן משאב FHIR. השיטה מטמיעה את תקן FHIR לעדכון אינטראקציה (DSTU2, STU3, R4, ו-R5).

כשמעדכנים משאב, מעדכנים את כל התוכן שלו. זה שונה מתיקון משאב, שבו מתעדכן רק חלק מהמשאב.

אם המאגר של FHIR כולל את הערך enableUpdateCreate, הבקשה מטופלת כבקשת upsert (עדכון או הוספה) שמעדכנת את המשאב אם הוא קיים, או מוסיפה אותו באמצעות המזהה שצוין בבקשה אם הוא לא קיים.

גוף הבקשה חייב להכיל משאב FHIR מקודד באמצעות JSON, וכותרות הבקשה חייבות להכיל את הערך Content-Type: application/fhir+json. המשאב צריך לכלול את הרכיב id עם ערך זהה למזהה בנתיב REST של הבקשה.

דוגמאות ה-REST הבאות פועלות עם מאגרי R4 FHIR. הדוגמאות של Go,‏ Java,‏ Node.js ו-Python פועלות עם מאגרי STU3 FHIR.

REST

בדוגמאות הבאות אפשר לראות איך מעדכנים את מספר הפעימות בדקה (BPM) במשאב Observation.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud
  • LOCATION: המיקום של מערך הנתונים
  • DATASET_ID: מערך הנתונים הראשי של מאגר FHIR
  • FHIR_STORE_ID: מזהה מאגר ה-FHIR
  • OBSERVATION_ID: מזהה משאב ה-Observation
  • PATIENT_ID: מזהה משאב המטופל
  • ENCOUNTER_ID: מזהה משאב המפגש
  • BPM_VALUE: הערך של פעימות לדקה (BPM) במשאב Observation המעודכן

תוכן בקשת JSON:

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

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

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

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

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

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

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

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

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

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

APIs Explorer

מעתיקים את גוף הבקשה ופותחים את דף העזר של השיטה. החלונית של API Explorer תיפתח בצד שמאל של הדף. אפשר להשתמש בכלי הזה כדי לשלוח בקשות. מדביקים את גוף הבקשה בכלי הזה, ממלאים את כל שדות החובה ולוחצים על Execute.

אתם אמורים לקבל תגובת JSON שדומה לזו:

Go

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

	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 := io.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'},
  responseType: '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};

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

updateFhirResource();

Python

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


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

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

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

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

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

    api_version = "v1"
    service_name = "healthcare"

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

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

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

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

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

    return response

עדכון משאב FHIR באופן מותנה

הדוגמאות הבאות מראות איך להפעיל את השיטה projects.locations.datasets.fhirStores.fhir.conditionalUpdate כדי לעדכן משאב FHIR שתואם לשאילתת חיפוש, במקום לזהות את המשאב לפי המזהה שלו. השיטה מטמיעה את האינטראקציה של עדכון מותנה בתקן FHIR‏ (DSTU2,‏ STU3,‏ R4 ו-R5).

אפשר להחיל עדכון מותנה רק על משאב FHIR אחד בכל פעם.

התגובה שמוחזרת מהשרת תלויה במספר ההתאמות שמתקבלות על סמך קריטריוני החיפוש:

  • התאמה אחת: המשאב עודכן בהצלחה או שהוחזרה שגיאה.
  • יותר מהתאמה אחת: הבקשה מחזירה שגיאה 412 Precondition Failed.
  • אפס התאמות עם id: אם הקריטריונים לחיפוש לא מזהים התאמות, גוף הבקשה שסופק מכיל id, ובמאגר FHIR מוגדר enableUpdateCreate עם הערך true, משאב FHIR נוצר עם id בגוף הבקשה.
  • אפס התאמות ללא id: אם קריטריוני החיפוש מזהים אפס התאמות וגוף הבקשה שסופק לא מכיל id, משאב ה-FHIR נוצר עם מזהה שהוקצה על ידי השרת כאילו המשאב נוצר באמצעות projects.locations.datasets.fhirStores.fhir.create.

גוף הבקשה חייב להכיל משאב FHIR מקודד באמצעות JSON, וכותרות הבקשה חייבות להכיל את הערך Content-Type: application/fhir+json.

ב-Cloud Healthcare API v1, פעולות מותנות משתמשות באופן בלעדי בפרמטר החיפוש identifier, אם הוא קיים עבור סוג משאב FHIR, כדי לקבוע אילו משאבי FHIR תואמים לשאילתת חיפוש מותנית.

REST

בדוגמה הבאה מוצגות בקשת PUT באמצעות curl ו-PowerShell לעריכת משאב Observation באמצעות המזהה של ה-Observation ‏(ABC-12345 ב-my-code-system). ה-Observation מספק מדידה של פעימות הלב לדקה (BPM) של המטופל.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud
  • LOCATION: המיקום של מערך הנתונים
  • DATASET_ID: מערך הנתונים הראשי של מאגר FHIR
  • FHIR_STORE_ID: מזהה מאגר ה-FHIR
  • PATIENT_ID: מזהה משאב המטופל
  • ENCOUNTER_ID: מזהה משאב המפגש
  • BPM_VALUE: הערך של פעימות לדקה (BPM) במשאב Observation

תוכן בקשת JSON:

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

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

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

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

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

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

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

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

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

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

APIs Explorer

מעתיקים את גוף הבקשה ופותחים את דף העזר של השיטה. החלונית של API Explorer תיפתח בצד שמאל של הדף. אפשר להשתמש בכלי הזה כדי לשלוח בקשות. מדביקים את גוף הבקשה בכלי הזה, ממלאים את כל שדות החובה ולוחצים על Execute.

אתם אמורים לקבל תגובת JSON שדומה לזו:

תיקון משאב FHIR

בדוגמאות הבאות אפשר לראות איך מפעילים את השיטה projects.locations.datasets.fhirStores.fhir.patch כדי לעדכן משאב FHIR. השיטה מיישמת את אינטראקציית התיקון בתקן FHIR‏ (DSTU2,‏ STU3,‏ R4 ו-R5).

כשמבצעים תיקון של משאב, מעדכנים חלק מהמשאב על ידי הפעלת הפעולות שמצוינות במסמך JSON Patch.

הבקשה חייבת להכיל מסמך JSON patch, וכותרות הבקשה חייבות להכיל את הערך Content-Type: application/json-patch+json.

בדוגמאות הבאות אפשר לראות איך מעדכנים משאב מסוג Observation. התצפית על פעימות הלב של המטופל לדקה (BPM) מתעדכנת באמצעות פעולת התיקון replace.

דוגמאות ה-REST הבאות פועלות עם מאגרי R4 FHIR. הדוגמאות של Go,‏ Java,‏ Node.js ו-Python פועלות עם מאגרי STU3 FHIR.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud
  • LOCATION: המיקום של מערך הנתונים
  • DATASET_ID: מערך הנתונים הראשי של מאגר FHIR
  • FHIR_STORE_ID: מזהה מאגר ה-FHIR
  • OBSERVATION_ID: מזהה משאב ה-Observation
  • BPM_VALUE: הערך של פעימות לדקה (BPM) במשאב Observation שעבר תיקון

תוכן בקשת JSON:

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

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

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

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

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

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

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

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

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

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

Go

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

	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 := io.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 בחבילת FHIR

אפשר לציין בקשה ב-FHIR bundle (רק FHIR R4).PATCH ביצוע בקשת PATCH בחבילת FHIR מאפשר לתקן הרבה משאבי FHIR בבת אחת, במקום לשלוח בקשות תיקון נפרדות לכל משאב FHIR.

כדי לשלוח בקשת PATCH בחבילה, צריך לציין את הפרטים הבאים באובייקט resource בבקשה:

  • שדה resourceType מוגדר לערך Binary
  • שדה contentType מוגדר לערך application/json-patch+json
  • גוף התיקון בקידוד base64

מוודאים שאובייקט resource נראה כך:

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

הדוגמה הבאה מציגה את גוף התיקון שקודד ל-base64 בשדה data:

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

בדוגמאות הבאות אפשר לראות איך משתמשים בבקשת PATCH בחבילה כדי לתקן את משאב המטופל שיצרתם במאמר יצירת משאב FHIR כך שערך birthDate יהיה 1990-01-01:

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud
  • LOCATION: המיקום של מערך הנתונים הראשי
  • DATASET_ID: מערך הנתונים הראשי של מאגר FHIR
  • FHIR_STORE_ID: מזהה מאגר ה-FHIR
  • PATIENT_ID: המזהה של משאב Patient קיים

תוכן בקשת JSON:

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

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

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

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

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

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

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

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

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

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

החלת תיקון על משאב FHIR באופן מותנה

בדוגמאות הבאות אפשר לראות איך מפעילים את השיטה projects.locations.datasets.fhirStores.fhir.conditionalPatch כדי לשנות משאב FHIR שתואם לשאילתת חיפוש, במקום לזהות את המשאב לפי המזהה שלו. השיטה מטמיעה את תקן FHIR conditional patch interaction (DSTU2, STU3, R4, and R4).

אפשר להחיל תיקון מותנה רק על משאב אחד בכל פעם. אם קריטריוני החיפוש מזהים יותר מהתאמה אחת, הבקשה מחזירה שגיאת 412 Precondition Failed. אם קריטריון החיפוש לא מזהה התאמות, הבקשה מחזירה שגיאת 404 Not Found.

ב-Cloud Healthcare API v1, פעולות מותנות משתמשות באופן בלעדי בפרמטר החיפוש identifier, אם הוא קיים עבור סוג משאב FHIR, כדי לקבוע אילו משאבי FHIR תואמים לשאילתת חיפוש מותנית.

REST

בדוגמאות הבאות אפשר לראות איך לשלוח בקשת PATCH לעריכת משאב Observation אם המזהה של ה-Observation הוא ABC-12345 ב-my-code-system. התצפית על פעימות הלב של המטופל בדקה (BPM) מתעדכנת באמצעות פעולת התיקון replace.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud
  • LOCATION: המיקום של מערך הנתונים
  • DATASET_ID: מערך הנתונים הראשי של מאגר FHIR
  • FHIR_STORE_ID: מזהה מאגר ה-FHIR
  • BPM_VALUE: הערך של פעימות לדקה (BPM) במשאב Observation

תוכן בקשת JSON:

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

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

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

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

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

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json. כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

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

לאחר מכן מבצעים את הפקודה הבאה כדי לשלוח את בקשת ה-REST:

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

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

APIs Explorer

מעתיקים את גוף הבקשה ופותחים את דף העזר של השיטה. החלונית של API Explorer תיפתח בצד שמאל של הדף. אפשר להשתמש בכלי הזה כדי לשלוח בקשות. מדביקים את גוף הבקשה בכלי הזה, ממלאים את כל שדות החובה ולוחצים על Execute.

אתם אמורים לקבל תגובת JSON שדומה לזו:

קבלת משאב FHIR

בדוגמאות הבאות אפשר לראות איך מקבלים את התוכן של משאב FHIR.

דוגמאות ה-REST הבאות פועלות עם מאגרי R4 FHIR. הדוגמאות של Go,‏ Java,‏ Node.js ו-Python פועלות עם מאגרי STU3 FHIR.

המסוף

  1. נכנסים לדף FHIR viewer במסוף Google Cloud .

    מעבר לכלי לצפייה ב-FHIR

  2. ברשימה הנפתחת FHIR Store (מאגר FHIR), בוחרים מערך נתונים ואז בוחרים מאגר FHIR במערך הנתונים.

  3. כדי לסנן את רשימת סוגי המשאבים, מחפשים את סוגי המשאבים שרוצים להציג.

  4. לוחצים על השדה סוג המשאב.

  5. ברשימה הנפתחת Properties שמופיעה, בוחרים באפשרות Resource Type.

  6. מזינים סוג משאב.

  7. כדי לחפש סוג משאב אחר, בוחרים באפשרות OR מהרשימה הנפתחת Operators שמופיעה, ואז מזינים סוג משאב אחר.

  8. ברשימת סוגי המשאבים, בוחרים את סוג המשאב שרוצים לקבל את התוכן שלו.

  9. בטבלת המשאבים שמופיעה, בוחרים משאב או מחפשים משאב.

REST

בדוגמאות הבאות מוצגות דרכים להשתמש בשיטה projects.locations.datasets.fhirStores.fhir.read כדי לקבל את הפרטים של משאב ה-Observation שנוצר בקטע הקודם.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud
  • LOCATION: המיקום של מערך הנתונים
  • DATASET_ID: מערך הנתונים הראשי של מאגר FHIR
  • FHIR_STORE_ID: מזהה מאגר ה-FHIR
  • OBSERVATION_ID: מזהה משאב ה-Observation

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

מריצים את הפקודה הבאה:

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

PowerShell

מריצים את הפקודה הבאה:

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

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

APIs Explorer

פותחים את דף העזר של ה-method. החלונית של API Explorer תיפתח בצד שמאל של הדף. אפשר להשתמש בכלי הזה כדי לשלוח בקשות. ממלאים את כל שדות החובה ולוחצים על Execute.

אתם אמורים לקבל תגובת JSON שדומה לזו:

Go

import (
	"context"
	"fmt"
	"io"

	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 := io.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'],
  }),
  responseType: 'json',
});

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

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

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

קבלת כל הפרטים של משאב Encounter

בדוגמאות הבאות אפשר לראות איך צופים בפרטים על משאב Encounter ובכל המשאבים שקשורים אליו.

השיטה מטמיעה את הפעולה המורחבת של FHIR‏ Encounter-everything שמוגדרת בגרסאות הבאות של FHIR:

REST

משתמשים בשיטה projects.locations.datasets.fhirStores.fhir.Encounter-everything.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud
  • LOCATION: המיקום של מערך הנתונים
  • DATASET_ID: מזהה קבוצת הנתונים
  • FHIR_STORE_ID: מזהה מאגר ה-FHIR
  • ENCOUNTER_ID: מזהה משאב המפגש

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

מריצים את הפקודה הבאה:

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

PowerShell

מריצים את הפקודה הבאה:

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

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Encounter/ENCOUNTER_ID/\$everything" | Select-Object -Expand Content
התגובה לדוגמה הבאה מוחזרת כשקוראים ל-method במשאב Encounter עם המזהה c427ce3e-7677-400e-bc06-33a8cecfdd77, שהוא משאב סינתטי בקטגוריה הציבורית של Cloud Storage‏ gs://gcp-public-data--synthea-fhir-data-10-patients/fhir_r4_ndjson/.

קבלת כל משאבי תא המטופל

בדוגמאות הבאות מוצגות דרכים לאחזור כל המשאבים שמשויכים לתא מטופל מסוים (DSTU2,‏ STU3,‏ R4 ו-R5). מידע נוסף זמין במאמר projects.locations.datasets.fhirStores.fhir.Patient-everything.

דוגמאות ה-REST הבאות פועלות עם מאגרי R4 FHIR. הדוגמאות של Go,‏ Java,‏ Node.js ו-Python פועלות עם מאגרי STU3 FHIR.

המסוף

כדי לראות משאבים בתא של מטופל ב-FHIR Viewer, פועלים לפי השלבים הבאים:

  1. במסוף Google Cloud , פותחים את הדף FHIR Viewer.

    ל-FHIR Viewer

  2. בתפריט הנפתח FHIR Store, בוחרים מערך נתונים ואז בוחרים FHIR Store במערך הנתונים.
  3. כדי לסנן את רשימת סוגי המשאבים לפי משאבי Patient, לוחצים על השדה Resource Type ובוחרים באפשרות Resource Type בתפריט הנפתח Properties. מזינים Patient בתור ערך המסנן.
  4. לוחצים על הקישור של סוג המשאב Patient בשורה בטבלה.
  5. בטבלת המקורות שמופיעה, בוחרים מטופל או מחפשים מטופל.
  6. בפינה השמאלית העליונה מופיע הלחצן Explore patient (ניתוח נתוני המטופל). לוחצים עליו כדי לראות את נתוני המטופל.

curl

כדי לקבל את המשאבים במחיצה של מטופל, צריך לשלוח בקשת GET ולציין את הפרטים הבאים:

  • השם של קבוצת הנתונים הראשית
  • השם של מאגר FHIR
  • מזהה המטופל
  • טוקן גישה

בדוגמה הבאה מוצגת בקשת GET באמצעות 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"

אם הבקשה מצליחה, השרת מחזיר תגובה שדומה לדוגמה הבאה בפורמט JSON:

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

PowerShell

כדי לקבל את המשאבים במחיצה של מטופל, צריך לשלוח בקשת GET ולציין את הפרטים הבאים:

  • השם של קבוצת הנתונים הראשית
  • השם של מאגר FHIR
  • מזהה המטופל
  • טוקן גישה

בדוגמה הבאה מוצגת בקשת GET באמצעות 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

אם הבקשה מצליחה, השרת מחזיר תגובה שדומה לדוגמה הבאה בפורמט JSON:

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

Go

import (
	"context"
	"fmt"
	"io"

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

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

	return nil
}

Java

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

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

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

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

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

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

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

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

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

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

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

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

Node.js

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

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

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

getPatientEverything();

Python

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

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

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

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

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

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

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

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

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

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

    resource = response.json()

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

    return resource

קבלת משאבים של תאים של מטופלים שסוננו לפי סוג או תאריך

בדוגמאות הבאות מוצגות דרכים לאחזר את כל המשאבים שמשויכים לתא מטופל (R4) מסוים, מסוננים לפי רשימת סוגים ומאז תאריך ושעה ספציפיים. מידע נוסף זמין במאמר projects.locations.datasets.fhirStores.fhir.Patient-everything.

דוגמאות ה-REST הבאות פועלות עם מאגרי R4 FHIR.

curl

כדי לקבל את המשאבים בתא של מטופל מסוג מסוים ומאז תאריך מסוים, שולחים בקשת GET ומציינים את הפרטים הבאים:

  • השם של קבוצת הנתונים הראשית
  • השם של מאגר FHIR
  • מזהה המטופל
  • מחרוזת שאילתה שמכילה רשימה מופרדת בפסיקים של סוגי משאבים ותאריך התחלה
  • טוקן גישה

בדוגמה הבאה מוצגת בקשת GET באמצעות 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"

אם הבקשה תצליח, השרת יחזיר את כל המשאבים שתואמים לקריטריונים שצוינו בפורמט JSON.

PowerShell

כדי לקבל את המשאבים בתא של מטופל מסוג מסוים ומאז תאריך מסוים, שולחים בקשת GET ומציינים את הפרטים הבאים:

  • השם של קבוצת הנתונים הראשית
  • השם של מאגר FHIR
  • מזהה המטופל
  • מחרוזת שאילתה שמכילה רשימה מופרדת בפסיקים של סוגי משאבים ותאריך התחלה
  • טוקן גישה

בדוגמה הבאה מוצגת בקשת GET באמצעות 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

אם הבקשה תצליח, השרת יחזיר את כל המשאבים שתואמים לקריטריונים שצוינו בפורמט JSON.

הצגת רשימה של גרסאות של משאבי FHIR

אפשר לראות את הגרסאות ההיסטוריות של משאב FHIR, כולל הגרסה הנוכחית וכל הגרסאות שנמחקו. כך תוכלו:

  • מעקב אחרי שינויים בתיקים רפואיים של מטופלים, בתרופות או בתוכניות טיפול.
  • אם משאב FHIR מכיל נתונים שגויים, אפשר להציג גרסאות קודמות כדי לגלות מתי הוזנו הנתונים השגויים ולשחזר את המידע הנכון.
  • כדי לעמוד בדרישות הרגולטוריות, צריך לספק נתוני ביקורת מלאים.

דוגמאות ה-REST הבאות פועלות עם מאגרי R4 FHIR. הדוגמאות של Go,‏ Java,‏ Node.js ו-Python פועלות עם מאגרי STU3 FHIR.

המסוף

  1. נכנסים לדף FHIR viewer במסוף Google Cloud .

    מעבר לכלי לצפייה ב-FHIR

  2. בתפריט FHIR store, בוחרים מערך נתונים ואז בוחרים FHIR store במערך הנתונים.

  3. כדי לסנן את רשימת סוגי משאבי FHIR, מחפשים את סוגי המשאבים שרוצים להציג.

  4. לוחצים על השדה סוג המשאב.

  5. ברשימה הנפתחת Properties שמופיעה, בוחרים באפשרות Resource Type.

  6. מזינים סוג משאב FHIR.

  7. ברשימת סוגי משאבי FHIR, בוחרים סוג משאב.

  8. בטבלה של משאבי FHIR שמופיעה, בוחרים משאב או מחפשים משאב.

  9. כדי לראות ולהשוות בין גרסאות היסטוריות של משאב FHIR, לוחצים על הכרטיסייה סקירה כללית ופועלים לפי השלבים הבאים:

    1. כדי לראות גרסאות היסטוריות של משאב FHIR, לוחצים על הצגת גרסאות היסטוריות באותה שורה של מזהה הגרסה. בחלונית בחירת גרסת משאב, בוחרים את הגרסה ולוחצים על אישור. הנתונים בגרסה מאוכלסים בכרטיסיות סקירה כללית, רכיבים ו-JSON.
    2. כדי להשוות בין שתי גרסאות של משאב FHIR, באותה שורה של מזהה גרסה, לוחצים על השוואת גרסאות של משאב. בחלונית בחירת גרסאות של משאבים להשוואה, בוחרים שתי גרסאות של משאבים ולוחצים על אישור. שתי הגרסאות של המשאב מוצגות בתצוגת השוואה. הגרסה הראשונה שבחרתם מוצגת בצד ימין והגרסה השנייה מוצגת בצד שמאל.

REST

משתמשים בשיטה projects.locations.datasets.fhirStores.fhir.history.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud
  • LOCATION: המיקום של מערך הנתונים
  • DATASET_ID: מערך הנתונים הראשי של מאגר FHIR
  • FHIR_STORE_ID: מזהה מאגר ה-FHIR
  • RESOURCE_TYPE: סוג משאב FHIR
  • RESOURCE_ID: מזהה משאב FHIR

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

בדוגמאות הבאות אפשר לראות איך מציגים את כל הגרסאות של משאב Observation. התצפית עודכנה פעם אחת אחרי היצירה המקורית שלה כדי לשנות את קצב פעימות הלב של המטופל (BPM).

מריצים את הפקודה הבאה:

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

PowerShell

בדוגמאות הבאות אפשר לראות איך מציגים את כל הגרסאות של משאב Observation. התצפית עודכנה פעם אחת אחרי היצירה המקורית שלה כדי לשנות את קצב פעימות הלב של המטופל (BPM).

מריצים את הפקודה הבאה:

$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/RESOURCE_TYPE/RESOURCE_ID/_history" | Select-Object -Expand Content
אם הבקשה מצליחה, השרת מחזיר את התגובה בפורמט JSON. בדוגמה הזו, הפונקציה מחזירה שתי גרסאות של התצפית. בגרסה הראשונה, הדופק של המטופל היה 75 פעימות לדקה. בגרסה השנייה, קצב הלב של המטופל היה 85 פעימות בדקה.
{
  "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"

	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 := io.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'],
  }),
  responseType: 'json',
});

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

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

listFhirResourceHistory();

Python

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


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

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

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

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

    api_version = "v1"
    service_name = "healthcare"

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

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

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

אחזור של גרסת משאב FHIR

בדוגמאות הבאות אפשר לראות איך מאחזרים גרסה ספציפית של משאב FHIR. כדי למצוא גרסה ספציפית, אפשר לרשום את הגרסאות של משאב FHIR ואז להציג את המידע של הגרסה הזו. מזהה הגרסה מופיע בשדה "versionId". לדוגמה, אפשר לראות את גוף ה-JSON הבא שבו מודגשים מזהי הגרסה של משאב ה-Observation ברשימת גרסאות של משאבי FHIR:

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

בדוגמאות הבאות נעשה שימוש במשאבים שנוצרו בקטע יצירת משאב FHIR, ומוצגות בהן דרכים לצפייה במשאב Observation. הדוגמאות של REST פועלות עם חנויות FHIR R4. הדוגמאות של Go,‏ Node.js ו-Python פועלות עם מאגרי STU3 FHIR.

המסוף

  1. נכנסים לדף FHIR viewer במסוף Google Cloud .

    מעבר לכלי לצפייה ב-FHIR

  2. בתפריט FHIR store, בוחרים מערך נתונים ואז בוחרים FHIR store במערך הנתונים.

  3. כדי לסנן את רשימת סוגי משאבי FHIR, מחפשים את סוגי המשאבים שרוצים להציג.

  4. לוחצים על השדה סוג המשאב.

  5. ברשימה הנפתחת Properties שמופיעה, בוחרים באפשרות Resource Type.

  6. מזינים סוג משאב FHIR.

  7. ברשימת סוגי משאבי FHIR, בוחרים סוג משאב.

  8. בטבלה של משאבי FHIR שמופיעה, בוחרים משאב או מחפשים משאב.

  9. כדי לראות גרסה ספציפית של משאב FHIR:

    1. לוחצים על הכרטיסייה סקירה כללית.
    2. באותה שורה של מזהה גרסה, לוחצים על הצגת גרסאות היסטוריות.
    3. בחלונית בחירת גרסת משאב, בוחרים את הגרסה ולוחצים על אישור. הנתונים בגרסה מאוכלסים בכרטיסיות סקירה כללית, רכיבים ו-JSON.

REST

משתמשים בשיטה projects.locations.datasets.fhirStores.fhir.vread.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud
  • LOCATION: המיקום של מערך הנתונים
  • DATASET_ID: מערך הנתונים הראשי של מאגר FHIR
  • FHIR_STORE_ID: מזהה מאגר ה-FHIR
  • RESOURCE_TYPE: סוג משאב FHIR
  • RESOURCE_ID: מזהה משאב FHIR
  • RESOURCE_VERSION: גרסת משאב ה-FHIR

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

בדוגמאות הבאות אפשר לראות איך מציגים את כל הגרסאות של משאב Observation. התצפית עודכנה פעם אחת אחרי היצירה המקורית שלה כדי לשנות את קצב פעימות הלב של המטופל (BPM).

מריצים את הפקודה הבאה:

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

PowerShell

בדוגמאות הבאות אפשר לראות איך מציגים את כל הגרסאות של משאב Observation. התצפית עודכנה פעם אחת אחרי היצירה המקורית שלה כדי לשנות את קצב פעימות הלב של המטופל (BPM).

מריצים את הפקודה הבאה:

$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/RESOURCE_TYPE/RESOURCE_ID/_history/RESOURCE_VERSION" | Select-Object -Expand Content
אם הבקשה מצליחה, השרת מחזיר את התגובה בפורמט JSON. בדוגמה הזו, מוחזרת הגרסה הראשונה של התצפית, שבה קצב הלב של המטופל היה 75 פעימות בדקה.
{
  "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"

	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 := io.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'],
  }),
  responseType: 'json',
});

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

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

getFhirResourceHistory();

Python

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


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

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

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

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

    api_version = "v1"
    service_name = "healthcare"

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

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

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

    return response

מחיקת משאב FHIR

בדוגמאות הבאות אפשר לראות איך מפעילים את השיטה projects.locations.datasets.fhirStores.fhir.delete כדי למחוק משאב מסוג Observation FHIR.

לא משנה אם הפעולה הצליחה או נכשלה, השרת מחזיר קוד סטטוס 200 OK של HTTP. כדי לוודא שהמשאב נמחק בהצלחה, מחפשים או מקבלים את המשאב ובודקים אם הוא קיים.

דוגמאות ה-REST הבאות פועלות עם מאגרי R4 FHIR. הדוגמאות של Go,‏ Java,‏ Node.js ו-Python פועלות עם מאגרי STU3 FHIR.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud
  • LOCATION: המיקום של מערך הנתונים
  • DATASET_ID: מערך הנתונים הראשי של מאגר FHIR
  • FHIR_STORE_ID: מזהה מאגר ה-FHIR
  • OBSERVATION_ID: מזהה משאב ה-Observation

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

מריצים את הפקודה הבאה:

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

PowerShell

מריצים את הפקודה הבאה:

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

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

APIs Explorer

פותחים את דף העזר של ה-method. החלונית של API Explorer תיפתח בצד שמאל של הדף. אפשר להשתמש בכלי הזה כדי לשלוח בקשות. ממלאים את כל שדות החובה ולוחצים על Execute.

אתם אמורים לקבל תגובת JSON שדומה לזו:

Go

import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

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

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

	return nil
}

Java

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

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

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

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

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

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

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

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

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

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

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

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

Node.js

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

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.
  try {
    await healthcare.projects.locations.datasets.fhirStores.fhir.delete(
      request
    );
    console.log(`Deleted FHIR resource: ${resourceId}`);
  } catch (error) {
    console.error('Error deleting FHIR resource:', error.message || error);
  }
};

deleteFhirResource();

Python

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

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

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

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

    api_version = "v1"
    service_name = "healthcare"

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

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

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

    return response

מחיקה מותנית של משאב FHIR

ב-Cloud Healthcare API v1, פעולות מותנות משתמשות באופן בלעדי בפרמטר החיפוש identifier, אם הוא קיים בסוג המשאב FHIR, כדי לקבוע אילו משאבי FHIR תואמים לשאילתת חיפוש מותנה.

משאב FHIR תואם לשאילתה ?identifier=my-code-system|ABC-12345 אם ורק אם הערך של identifier.system במשאב הוא my-code-system והערך של identifier.value הוא ABC-12345. אם משאב FHIR תואם לשאילתה, Cloud Healthcare API מוחק את המשאב.

אם בשאילתה נעשה שימוש בפרמטר החיפוש identifier והיא תואמת לכמה משאבי FHIR, ‏ Cloud Healthcare API מחזיר שגיאה "412 - Condition not selective enough". כדי למחוק את המשאבים בנפרד, פועלים לפי השלבים הבאים:

  1. מחפשים כל משאב כדי לקבל את המזהה הייחודי שהוקצה לו על ידי השרת.
  2. מוחקים כל משאב בנפרד באמצעות המזהה.

הדוגמאות הבאות מראות איך למחוק באופן מותנה משאב FHIR שתואם לשאילתת חיפוש, במקום לזהות את משאב FHIR לפי המזהה שלו. שאילתת החיפוש תואמת למשאב Observation ותמחק אותו באמצעות המזהה של Observation (ABC-12345 ב-my-code-system).

REST

משתמשים בשיטה projects.locations.datasets.fhirStores.fhir.conditionalDelete.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud
  • LOCATION: המיקום של מערך הנתונים
  • DATASET_ID: מערך הנתונים הראשי של מאגר FHIR
  • FHIR_STORE_ID: מזהה מאגר ה-FHIR

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

מריצים את הפקודה הבאה:

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

PowerShell

מריצים את הפקודה הבאה:

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

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

APIs Explorer

פותחים את דף העזר של ה-method. החלונית של API Explorer תיפתח בצד שמאל של הדף. אפשר להשתמש בכלי הזה כדי לשלוח בקשות. ממלאים את כל שדות החובה ולוחצים על Execute.

אמורים לקבל קוד סטטוס של הצלחה (2xx) ותגובה ריקה.

מחיקה של גרסאות היסטוריות של משאב FHIR

בדוגמאות הבאות מוצג איך למחוק את כל הגרסאות הקודמות של משאב FHIR באמצעות השיטה projects.locations.datasets.fhirStores.fhir.Resource-purge.

השימוש במתודה projects.locations.datasets.fhirStores.fhir.Resource-purge מוגבל למשתמשים (מתקשרים) עם התפקיד roles/healthcare.fhirStoreAdmin. משתמשים עם התפקיד roles/healthcare.fhirResourceEditor לא יכולים להשתמש במתודה. כדי לאפשר למתקשר למחוק גרסאות היסטוריות של משאב FHIR, אפשר:

בדוגמאות נעשה שימוש במשאבים שנוצרו במאמר יצירת משאב FHIR, ומוצגות בהן דרכים למחיקת הגרסאות ההיסטוריות של משאב Observation.

דוגמאות ה-REST הבאות פועלות עם מאגרי R4 FHIR. הדוגמאות של Go,‏ Java,‏ Node.js ו-Python פועלות עם מאגרי STU3 FHIR.

REST

משתמשים בשיטה projects.locations.datasets.fhirStores.fhir.Resource-purge.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud
  • LOCATION: המיקום של מערך הנתונים
  • DATASET_ID: מערך הנתונים הראשי של מאגר FHIR
  • FHIR_STORE_ID: מזהה מאגר ה-FHIR
  • RESOURCE_TYPE: סוג משאב FHIR
  • RESOURCE_ID: מזהה משאב FHIR

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

מריצים את הפקודה הבאה:

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

PowerShell

מריצים את הפקודה הבאה:

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

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

אמורים לקבל קוד סטטוס של הצלחה (2xx) ותגובה ריקה.

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'],
  }),
  responseType: 'json',
});

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

  try {
    await healthcare.projects.locations.datasets.fhirStores.fhir.ResourcePurge(
      request
    );
    console.log(`Purged all historical versions of resource: ${resourceId}`);
  } catch (error) {
    console.error('Error purging FHIR resource:', error.message || error);
  }
};

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