Créer et gérer des ressources FHIR

Cette page explique comment créer, mettre à jour, corriger, afficher et supprimer des ressources FHIR.

Une ressource FHIR peut contenir des données sur un patient, un appareil, une observation, etc. Pour obtenir la liste complète des ressources FHIR, consultez l'index des ressources FHIR (DSTU2, STU3 ou R4).

Créer une ressource FHIR

Pour pouvoir créer des ressources FHIR, vous devez créer un magasin FHIR.

Les exemples suivants montrent comment créer des ressources FHIR.

Les exemples curl, Windows PowerShell et Python montrent comment créer une ressource Patient (DSTU2, STU3 et R4), une ressource Encounter (DSTU2, STU3 et R4) pour le patient, ainsi qu'une ressource Observation (DSTU2, STU3 et R4) en fonction de la ressource Encounter.

Les exemples de tous les autres langages montrent comment créer une ressource FHIR générique.

Pour en savoir plus, consultez les sections sur projects.locations.datasets.fhirStores.fhir.create

Commande curl

Pour créer une ressource Patient, exécutez une requête POST et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Un blob de données contenant des informations sur le patient
  • Le type de ressource
  • Un jeton d'accès

L'exemple suivant montre comment envoyer une requête POST à l'aide de curl pour créer une ressource Patient.

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON :

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

PowerShell

Pour créer une ressource Patient, exécutez une requête POST et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Un blob de données contenant des informations sur le patient
  • Le type de ressource
  • Un jeton d'accès

L'exemple suivant montre comment envoyer une requête POST à l'aide de Windows PowerShell pour créer une ressource Patient.

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

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

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON :

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

Go

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

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

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

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

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

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

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

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

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

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

	return nil
}

Java

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

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

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

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

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

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

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

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          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 {
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
    credential.refreshToken();
    return credential.getAccessToken();
  }
}

Node.js

const createResource = async (
  token,
  projectId,
  cloudRegion,
  datasetId,
  fhirStoreId,
  resourceType
) => {
  // Token retrieved in callback
  // getToken(serviceAccountJson, function(cb) {...});
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  const parentName = `${BASE_URL}/projects/${projectId}/locations/${cloudRegion}`;

  const resourcePath = `${parentName}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}`;

  const postData = {
    resourceType: resourceType,
  };

  const options = {
    url: resourcePath,
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/fhir+json; charset=utf-8',
    },
    body: postData,
    json: true,
    method: 'POST',
  };

  try {
    const resource = await request(options);
    console.log(
      `Created FHIR resource ${resourceType} with ID ${resource.id}.`
    );
  } catch (err) {
    console.error(err);
  }
};

Python

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

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

    # Make an authenticated API request
    session = get_session()

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

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

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

    resource = response.json()

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

    return response

Commande curl

Après avoir créé la ressource Patient, créez une ressource Encounter pour décrire une interaction entre le patient et un praticien. L'exemple suivant montre comment envoyer une requête POST à l'aide de curl pour créer une ressource Encounter.

Dans le champ PATIENT_ID, remplacez l'ID de la réponse renvoyée par le serveur lors de la création de la ressource Patient.

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON :

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

PowerShell

Après avoir créé la ressource Patient, créez une ressource Encounter pour décrire une interaction entre le patient et un praticien. L'exemple suivant montre comment envoyer une requête POST à l'aide de Windows PowerShell pour créer une ressource Encounter.

Dans le champ PATIENT_ID, remplacez l'ID de la réponse renvoyée par le serveur lors de la création de la ressource Patient.

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

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

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON :

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

Python

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

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

    # Make an authenticated API request
    session = get_session()

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

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

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

    resource = response.json()

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

    return response

Commande curl

Après avoir créé la ressource Encounter, créez une ressource Observation sur la rencontre. La ressource Observation fournit une mesure des battements cardiaques par minute (BPM) du patient. L'exemple suivant montre comment envoyer une requête POST avec curl pour créer une ressource Observation.

Saisissez une valeur dans le champ BPM_VALUE. Dans le champ PATIENT_ID, remplacez l'ID de la réponse renvoyée par le serveur lors de la création de la ressource Patient. Dans le champ ENCOUNTER_ID, remplacez l'ID de la réponse renvoyée par le serveur lors de la création de la ressource Encounter.

curl -X POST \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     -H "Content-Type: application/fhir+json; charset=utf-8" \
     --data "{
         \"resourceType\": \"Observation\",
         \"status\": \"final\",
         \"subject\": {
           \"reference\": \"Patient/PATIENT_ID\"
         },
         \"effectiveDateTime\": \"2018-01-01T00:00:00+00:00\",
         \"code\": {
           \"coding\": [
             {
               \"system\": \"http://loinc.org\",
               \"code\": \"8867-4\",
               \"display\": \"Heart rate\"
             }
           ]
         },
         \"valueQuantity\": {
           \"value\": BPM_VALUE,
           \"unit\": \"bpm\"
         },
         \"context\": {
           \"reference\": \"Encounter/ENCOUNTER_ID\"
         }
     }" \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Observation"

Si la requête aboutit, le serveur renvoie la réponse au format JSON :

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

PowerShell

Après avoir créé la ressource Encounter, créez une ressource Observation sur la rencontre. La ressource Observation fournit une mesure des battements par minute (BPM) du patient. L'exemple suivant montre comment envoyer une requête POST à l'aide de Windows PowerShell pour créer une ressource Observation.

Saisissez une valeur dans le champ BPM_VALUE. Dans le champ PATIENT_ID, remplacez l'ID de la réponse renvoyée par le serveur lors de la création de la ressource Patient. Dans le champ ENCOUNTER_ID, remplacez l'ID de la réponse renvoyée par le serveur lors de la création de la ressource Encounter.

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

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

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON :

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

Python

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

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

    # Make an authenticated API request
    session = get_session()

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

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

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

    resource = response.json()

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

    return response

Mettre à jour une ressource FHIR

Les exemples suivants montrent comment appeler la méthode projects.locations.datasets.fhirStores.fhir.update pour mettre à jour une ressource FHIR. La méthode met en œuvre l'interaction de mise à jour standard FHIR (DSTU2, STU3 et R4).

Lorsque vous mettez à jour une ressource, vous mettez à jour tout son contenu. Cela diffère du correctif appliqué à une ressource, qui ne met à jour qu'une partie d'une ressource.

Si enableUpdateCreate est défini pour le magasin FHIR, la requête est traitée comme une mise à jour ou une insertion, qui met à jour la ressource si elle existe ou l'insère à l'aide de l'ID spécifié si elle n'existe pas.

Le corps de la requête doit contenir une ressource FHIR encodée au format JSON et les en-têtes de requête doivent contenir Content-Type: application/fhir+json. La ressource doit contenir un élément id ayant une valeur identique à l'ID dans le chemin REST de la requête.

Commande curl

Pour mettre à jour une ressource FHIR, exécutez une requête PUT et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type de ressource
  • L'ID de ressource
  • Un jeton d'accès

L'exemple suivant montre comment envoyer une requête PUT avec curl pour modifier une ressource Observation. La ressource Observation fournit une mesure des battements par minute (BPM) d'un patient.

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON :

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

PowerShell

Pour mettre à jour une ressource FHIR, exécutez une requête PUT et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type de ressource
  • L'ID de ressource
  • Un jeton d'accès

L'exemple suivant montre comment envoyer une requête PUT à l'aide de Windows PowerShell pour modifier une ressource Observation. La ressource Observation fournit une mesure des battements par minute (BPM) d'un patient.

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

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

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON :

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

Go

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

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

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

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

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

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

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

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

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

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

	return nil
}

Node.js

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

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

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

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

updateFhirResource();

Python

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

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

    # Make an authenticated API request
    session = get_session()

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

    body = {"resourceType": resource_type, "active": True, "id": resource_id}

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

    resource = response.json()

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

    return resource

Mise à jour conditionnelle d'une ressource FHIR

Les exemples suivants montrent comment appeler la méthode projects.locations.datasets.fhirStores.fhir.conditionalUpdate pour mettre à jour une ressource FHIR correspondant à une requête de recherche, plutôt que d'identifier la ressource par son ID. La méthode met en œuvre l'interaction de mise à jour conditionnelle standard FHIR (DSTU2, STU3 et R4).

Une mise à jour conditionnelle ne peut être appliquée qu'à une seule ressource à la fois.

La réponse renvoyée par le serveur dépend du nombre de correspondances trouvées en fonction des critères de recherche :

  • Une correspondance : la ressource a bien été mise à jour ou une erreur est renvoyée.
  • Plusieurs correspondances : la requête renvoie une erreur 412 Precondition Failed.
  • Aucune correspondance avec un id : si les critères de recherche identifient zéro correspondance, que le corps de la ressource fournie contient un id et que enableUpdateCreate est défini sur le magasin FHIR, la ressource est créée avec un ID attribué par le serveur, comme si elle avait été créée avec projects.locations.datasets.fhirStores.fhir.create. L'élément id est ignoré.
  • Aucune correspondance sans id : si les critères de recherche identifient zéro correspondance et que le corps de la ressource fournie ne contient pas de id, la ressource est créée avec un ID attribué par le serveur, comme si elle avait été créée avec projects.locations.datasets.fhirStores.fhir.create.

Le corps de la requête doit contenir une ressource FHIR encodée au format JSON et les en-têtes de la requête doivent contenir Content-Type: application/fhir+json.

Commande curl

Pour mettre à jour une ressource FHIR correspondant à une requête de recherche, exécutez une requête PUT et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type de ressource que vous recherchez
  • Une chaîne de requête contenant les informations que vous recherchez
  • Un jeton d'accès

L'exemple suivant montre comment envoyer une requête PUT avec curl pour modifier une ressource Observation à l'aide de son identifiant (ABC-12345 dans my-code-system). La ressource Observation fournit une mesure des battements par minute (BPM) d'un patient.

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON :

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

PowerShell

Pour mettre à jour une ressource FHIR correspondant à une requête de recherche, exécutez une requête PUT et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type de ressource que vous recherchez
  • Une chaîne de requête contenant les informations que vous recherchez
  • Un jeton d'accès

L'exemple suivant montre comment envoyer une requête PUT avec Windows PowerShell pour modifier une ressource Observation à l'aide de son identifiant (ABC-12345 dans my-code-system). La ressource Observation fournit une mesure des battements par minute (BPM) d'un patient.

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

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

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON :

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

Go

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

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

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

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

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

	ctx := context.Background()

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

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

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

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

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

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

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

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

	defer resp.Body.Close()

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

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

	return nil
}

Python

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

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

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

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

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

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

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

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

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

    return resource

Appliquer un correctif à une ressource FHIR

Les exemples suivants montrent comment appeler la méthode projects.locations.datasets.fhirStores.fhir.patch pour appliquer un correctif à une ressource FHIR. La méthode met en œuvre l'interaction de correctif standard FHIR (DSTU2, STU3 et R4).

Lorsque vous appliquez un correctif à une ressource, vous mettez à jour une partie de celle-ci en appliquant les opérations spécifiées dans un document de correctif JSON.

La requête doit contenir un document de correctif JSON et ses en-têtes doivent contenir Content-Type: application/json-patch+json.

Commande curl

Pour appliquer un correctif à une ressource FHIR, exécutez une requête PATCH et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type de ressource
  • L'ID de ressource
  • Un jeton d'accès

L'exemple suivant montre comment envoyer une requête PATCH avec curl pour modifier une ressource Observation. La ressource Observation des battements par minute (BPM) d'un patient est mise à jour à l'aide de l'opération de correctif replace.

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON :

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

PowerShell

Pour appliquer un correctif à une ressource FHIR, exécutez une requête PATCH et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type de ressource
  • L'ID de ressource
  • Un jeton d'accès

L'exemple suivant montre comment envoyer une requête PATCH à l'aide de Windows PowerShell pour modifier une ressource Observation. La ressource Observation des battements par minute (BPM) d'un patient est mise à jour à l'aide de l'opération de correctif replace.

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

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

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON :

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

Go

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

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

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

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

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

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

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

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

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

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

	return nil
}

Java

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

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

  public static void fhirResourcePatch(String resourceName, String data)
      throws IOException, URISyntaxException {
    // String resourceName =
    //    String.format(
    //        FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "resource-type",
    // "resource-id");
    // 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
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          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 {
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
    credential.refreshToken();
    return credential.getAccessToken();
  }
}

Node.js

const patchResource = async (
  token,
  projectId,
  cloudRegion,
  datasetId,
  fhirStoreId,
  resourceType,
  resourceId
) => {
  // Token retrieved in callback
  // getToken(serviceAccountJson, function(cb) {...});
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const resourceType = 'Patient';
  // const resourceId = 'd64a85ae-da1b-4a10-0eb8-cfaf55bdbe3f';
  const parentName = `${BASE_URL}/projects/${projectId}/locations/${cloudRegion}`;

  const resourcePath = `${parentName}/datasets/${datasetId}/fhirStores/${fhirStoreId}/fhir/${resourceType}/${resourceId}`;

  const patchOperations = [{op: 'replace', path: '/active', value: true}];

  const options = {
    url: resourcePath,
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json-patch+json',
    },
    body: patchOperations,
    json: true,
    method: 'PATCH',
  };

  try {
    await request(options);
    console.log(`Patched ${resourceType} resource`);
  } catch (err) {
    console.error(err);
  }
};

Python

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

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

    # Make an authenticated API request
    session = get_session()

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

    body = json.dumps([{"op": "replace", "path": "/active", "value": False}])

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

    resource = response.json()

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

    return resource

Appliquer un correctif conditionnel à une ressource FHIR

Les exemples suivants montrent comment appeler la méthode projects.locations.datasets.fhirStores.fhir.conditionalPatch pour appliquer un correctif à une ressource FHIR correspondant à une requête de recherche, plutôt que d'identifier la ressource par son ID. La méthode met en œuvre l'interaction de correctif conditionnel standard FHIR (DSTU2, STU3 et R4).

Un correctif conditionnel ne peut être appliqué qu'à une seule ressource à la fois. Si les critères de recherche identifient plusieurs correspondances, la requête renvoie une erreur 412 Precondition Failed.

Commande curl

Pour appliquer un correctif à une ressource FHIR correspondant à une requête de recherche, exécutez une requête PATCH et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type de ressource que vous recherchez
  • Une chaîne de requête contenant les informations que vous recherchez
  • Un jeton d'accès

L'exemple suivant montre comment envoyer une requête PATCH avec curl pour modifier une ressource Observation si l'objet de cette ressource est "Patient123". La ressource Observation des battements par minute (BPM) d'un patient est mise à jour à l'aide de l'opération de correctif replace.

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON :

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

PowerShell

Pour appliquer un correctif à une ressource FHIR correspondant à une requête de recherche, exécutez une requête PATCH et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type de ressource que vous recherchez
  • Une chaîne de requête contenant les informations que vous recherchez
  • Un jeton d'accès

L'exemple suivant montre comment envoyer une requête PATCH à l'aide de Windows PowerShell pour modifier une ressource Observation si l'objet de cette ressource est "Patient123". La ressource Observation des battements par minute (BPM) d'un patient est mise à jour à l'aide de l'opération de correctif replace.

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

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

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON :

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

Go


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

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

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

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

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

	ctx := context.Background()

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

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

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

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

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

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

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

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

	defer resp.Body.Close()

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

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

	return nil
}

Python

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

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

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

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

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

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

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

    print(response.url)

    resource = response.json()

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

    return resource

Obtenir une ressource FHIR

Les exemples suivants montrent comment obtenir le contenu d'une ressource FHIR. Pour en savoir plus, consultez la page concernant projects.locations.datasets.fhirStores.fhir.read

Commande curl

Pour obtenir le contenu d'une ressource FHIR, exécutez une requête GET et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type et l'ID de ressource
  • Un jeton d'accès

L'exemple suivant montre une requête GET utilisant curl sur la ressource Observation créé dans la section précédente.

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON :

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

PowerShell

Pour obtenir le contenu d'une ressource FHIR, exécutez une requête GET et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type et l'ID de ressource
  • Un jeton d'accès

L'exemple suivant montre une requête GET utilisant Windows PowerShell sur la ressource Observation créée dans la section précédente.

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

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON :

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

Go

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

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

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

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

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

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

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

	defer resp.Body.Close()

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

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

	return nil
}

Java

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

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

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

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

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

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

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

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          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 {
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
    credential.refreshToken();
    return credential.getAccessToken();
  }
}

Node.js

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

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

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

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

getFhirResource();

Python

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

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

    # Make an authenticated API request
    session = get_session()

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

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

    resource = response.json()

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

    return resource

Obtenir toutes les ressources de compartiment de patient

Les exemples suivants montrent comment obtenir toutes les ressources associées à un compartiment de patient particulier (DSTU2, STU3 et R4). Pour en savoir plus, consultez la page concernant projects.locations.datasets.fhirStores.fhir.Patient-everything

Commande curl

Pour obtenir les ressources d'un compartiment de patient, exécutez une requête GET et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • L'ID du patient
  • Un jeton d'accès

L'exemple suivant montre une requête GET utilisant 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"

Si la requête aboutit, le serveur renvoie la réponse au format JSON :

{
  "entry": [
    {
      "resource": {
        "birthDate": "1970-01-01",
        "gender": "female",
        "id": "PATIENT_ID",
        "name": [
          {
            "family": "Smith",
            "given": [
              "Darcy"
            ],
            "use": "official"
          }
        ],
        "resourceType": "Patient"
      }
    },
    {
      "resource": {
        "class": {
          "code": "IMP",
          "display": "inpatient encounter",
          "system": "http://hl7.org/fhir/v3/ActCode"
        },
        "id": "ENCOUNTER_ID",
        "reason": [
          {
            "text": "The patient had an abnormal heart rate. She was concerned about this."
          }
        ],
        "resourceType": "Encounter",
        "status": "finished",
        "subject": {
          "reference": "Patient/PATIENT_ID"
        }
      }
    },
    {
      "resource": {
        "context": {
          "reference": "Encounter/ENCOUNTER_ID"
        },
        "effectiveDateTime": "2018-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

Pour obtenir les ressources d'un compartiment de patient, exécutez une requête GET et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • L'ID du patient
  • Un jeton d'accès

L'exemple suivant montre une requête GET utilisant Windows 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

Si la requête aboutit, le serveur renvoie la réponse au format JSON :

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

Go

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

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

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

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

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

	defer resp.Body.Close()

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

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

	return nil
}

Java

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

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

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

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

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

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

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

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

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          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 {
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
    credential.refreshToken();
    return credential.getAccessToken();
  }
}

Node.js

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

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

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

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

getPatientEverything();

Python

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

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

    # Make an authenticated API request
    session = get_session()

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

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

    resource = response.json()

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

    return resource

Répertorier les versions des ressources FHIR

Les exemples suivants montrent comment répertorier toutes les versions historiques d'une ressource FHIR. Pour en savoir plus, consultez les sections sur projects.locations.datasets.fhirStores.fhir.history

Les exemples utilisent les ressources créées dans la section Créer une ressource FHIR et montrent comment répertorier les versions d'une ressource Observation.

Commande curl

L'exemple suivant montre comment répertorier toutes les versions d'une ressource Observation. La ressource Observation a été mise à jour une fois après sa création initiale afin de changer les battements par minute (BPM) du patient.

Pour répertorier toutes les versions d'une ressource FHIR, y compris la version actuelle et les versions supprimées, exécutez une requête GET et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type et l'ID de ressource
  • Un jeton d'accès

L'exemple suivant montre une requête GET utilisant curl.

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON. Dans cet exemple, il renvoie deux versions de la ressource Observation. Dans la première version, le BPM du patient était de 75. Dans la deuxième version, le BPM du patient était de 85.

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

PowerShell

L'exemple suivant montre comment répertorier toutes les versions d'une ressource Observation. La ressource Observation a été mise à jour une fois après sa création initiale afin de changer les battements par minute (BPM) du patient.

Pour répertorier toutes les versions d'une ressource FHIR, y compris la version actuelle et les versions supprimées, exécutez une requête GET et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type et l'ID de ressource
  • Un jeton d'accès

L'exemple suivant montre une requête GET utilisant Windows PowerShell.

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

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON. Dans cet exemple, il renvoie deux versions de la ressource Observation. Dans la première version, le BPM du patient était de 75. Dans la deuxième version, le BPM du patient était de 85.

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

Go

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

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

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

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

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

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

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

	defer resp.Body.Close()

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

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

	return nil
}

Java

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

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

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

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

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

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

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

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

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          credential.initialize(request);
          request.setConnectTimeout(1 * 60 * 1000); // 1 minute connect timeout
          request.setReadTimeout(1 * 60 * 1000); // 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 {
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
    credential.refreshToken();
    return credential.getAccessToken();
  }
}

Node.js

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

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

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

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

listFhirResourceHistory();

Python

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

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

    # Make an authenticated API request
    session = get_session()

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

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

    resource = response.json()

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

    return resource

Récupérer une version de ressource FHIR

Les exemples suivants montrent comment récupérer une version spécifique d'une ressource. Pour en savoir plus, consultez les sections sur projects.locations.datasets.fhirStores.fhir.vread

Les ID de version de la ressource Observation de la section Répertorier les versions des ressources FHIR sont mis en surbrillance ci-dessous :

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

Les exemples suivants utilisent les ressources créées dans la section Créer une ressource FHIR et montrent comment afficher une ressource Observation.

Commande curl

Pour obtenir une version spécifique d'une ressource FHIR, exécutez une requête GET et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type et l'ID de ressource
  • La version de la ressource
  • Un jeton d'accès

L'exemple suivant montre une requête GET utilisant curl.

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON. Dans cet exemple, la première version de la ressource Observation, où le BPM du patient était de 75, est renvoyée.

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

PowerShell

Pour obtenir une version spécifique d'une ressource FHIR, exécutez une requête GET et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type et l'ID de ressource
  • La version de la ressource
  • Un jeton d'accès

L'exemple suivant montre une requête GET utilisant curl.

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

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

Si la requête aboutit, le serveur renvoie la réponse au format JSON. Dans cet exemple, la première version de la ressource Observation, où le BPM du patient était de 75, est renvoyée.

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

Go

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

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

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

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

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

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

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

	defer resp.Body.Close()

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

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

	return nil
}

Node.js

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

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

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

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

getFhirResourceHistory();

Python

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

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

    # Make an authenticated API request
    session = get_session()

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

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

    resource = response.json()

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

    return resource

Supprimer une ressource FHIR

Les exemples suivants montrent comment appeler la méthode projects.locations.datasets.fhirStores.fhir.delete pour supprimer une ressource FHIR.

Que l'opération réussisse ou échoue, le serveur renvoie un code d'état HTTP 200 OK. Pour vérifier que la ressource a bien été supprimée, recherchez ou récupérez la ressource et vérifiez si elle existe.

Commande curl

Pour supprimer une ressource FHIR, exécutez une requête DELETE et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Un jeton d'accès

L'exemple suivant montre une requête DELETE utilisant curl.

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

Si la requête aboutit, le serveur renvoie le corps de réponse vide au format JSON :

{}

PowerShell

Pour supprimer une ressource FHIR, exécutez une requête DELETE et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type et l'ID de ressource
  • Un jeton d'accès

L'exemple suivant montre une requête DELETE utilisant Windows PowerShell.

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

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

Si la requête aboutit, le serveur renvoie le corps de réponse vide au format JSON :

{}

Go

import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

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

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

	return nil
}

Java

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

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

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

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

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

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

    // Execute the request and process the results.
    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
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          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 {
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
    credential.refreshToken();
    return credential.getAccessToken();
  }
}

Node.js

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

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

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

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

deleteFhirResource();

Python

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

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

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

    # Make an authenticated API request
    session = get_session()

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

    return response

Supprimer une ressource FHIR de manière conditionnelle

Les exemples suivants montrent comment appeler la méthode projects.locations.datasets.fhirStores.fhir.conditionalDelete pour supprimer une ressource FHIR correspondant à une requête de recherche, plutôt que d'identifier la ressource par son ID.

Contrairement à l'application d'un correctif conditionnel ou à la mise à jour conditionnelle d'une ressource, la méthode de suppression conditionnelle peut s'appliquer à plusieurs ressources si plusieurs correspondances sont renvoyées par les critères de recherche.

Que l'opération réussisse ou échoue, le serveur renvoie un code d'état HTTP 200 OK. Pour vous assurer que la ressource a bien été supprimée, recherchez ou récupérez la ressource et vérifiez si elle existe.

Commande curl

Pour supprimer des ressources FHIR correspondant à une requête de recherche, exécutez une requête DELETE et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type de ressource que vous recherchez
  • Une chaîne de requête contenant les informations que vous recherchez
  • Un jeton d'accès

L'exemple suivant montre une requête DELETE utilisant curl pour supprimer toutes les ressources Observations avec un status de cancelled (DSTU2, STU3 et R4).

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

Si la requête aboutit, le serveur renvoie le corps de réponse vide au format JSON :

{}

PowerShell

Pour supprimer des ressources FHIR correspondant à une requête de recherche, exécutez une requête DELETE et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type de ressource que vous recherchez
  • Une chaîne de requête contenant les informations que vous recherchez
  • Un jeton d'accès

L'exemple suivant montre une requête DELETE utilisant Windows PowerShell pour supprimer toutes les ressources Observations avec un status de cancelled (DSTU2, STU3, et R4).

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

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

Si la requête aboutit, le serveur renvoie le corps de réponse vide au format JSON :

{}

Go

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

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

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

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

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

	ctx := context.Background()

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

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

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

	call := fhirService.ConditionalDelete(parent, resourceType)

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

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

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

	return nil
}

Python

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

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

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

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

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

    return response

Supprimer des versions historiques d'une ressource FHIR

Les exemples suivants montrent comment supprimer toutes les versions historiques d'une ressource FHIR. Pour en savoir plus, consultez les sections sur projects.locations.datasets.fhirStores.fhir.Resource-purge

L'appel de la méthode projects.locations.datasets.fhirStores.fhir.Resource-purge est limité aux utilisateurs (appelants) dotés du rôle roles/healthcare.fhirStoreAdmin. Les utilisateurs disposant du rôle roles/healthcare.fhirResourceEditor ne peuvent pas appeler la méthode. Pour permettre à un appelant de supprimer les versions historiques d'une ressource FHIR, procédez comme suit :

Les exemples utilisent les ressources créées dans la section Créer une ressource FHIR et montrent comment supprimer les versions historiques d'une ressource Observation.

Commande curl

Pour supprimer toutes les versions historiques d'une ressource FHIR, exécutez une requête DELETE et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type et l'ID de ressource
  • Un jeton d'accès

L'exemple suivant montre une requête DELETE utilisant curl.

curl -X DELETE \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     -H "Content-Type: application/fhir+json; charset=utf-8" \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/RESOURCE_TYPE/RESOURCE_ID/$purge"

Si la requête aboutit, le serveur renvoie le corps de réponse vide au format JSON :

{}

PowerShell

Pour supprimer toutes les versions historiques d'une ressource FHIR, exécutez une requête DELETE et spécifiez les informations suivantes :

  • Le nom de l'ensemble de données parent
  • Le nom du magasin FHIR
  • Le type et l'ID de ressource
  • Un jeton d'accès

L'exemple suivant montre une requête DELETE utilisant Windows PowerShell.

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

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

Si la requête aboutit, le serveur renvoie le corps de réponse vide au format JSON :

{}

Go

import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

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

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

	return nil
}

Java

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

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

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

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

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

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

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

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

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          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 {
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
    credential.refreshToken();
    return credential.getAccessToken();
  }
}

Node.js

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

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

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

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

deleteFhirResourcePurge();

Python

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

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

    # Make an authenticated API request
    session = get_session()

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

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

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

    return response