Crear y gestionar almacenes FHIR

En esta página se explica cómo crear, editar, ver, enumerar y eliminar almacenes Fast Healthcare Interoperability Resources (FHIR). Los almacenes FHIR contienen recursos FHIR, como recursos Claim, Patient y Medication, entre otros.

La API Cloud Healthcare admite las siguientes versiones de FHIR:

Crear un almacén FHIR

Para poder crear un almacén FHIR, antes debes crear un conjunto de datos.

En los ejemplos siguientes se muestra cómo crear un almacén FHIR mediante el método projects.locations.datasets.fhirStores.create.

Consola

Para crear un almacén FHIR, sigue estos pasos:

  1. En la Google Cloud consola, ve a la página Conjuntos de datos.

    Ve a Conjuntos de datos.

  2. Selecciona el conjunto de datos en el que quieras crear un almacén FHIR.
  3. Haz clic en Crear almacén de datos.
  4. Selecciona FHIR como tipo de almacén de datos.
  5. Escribe un nombre único en tu conjunto de datos. Si el nombre no es único, no se podrá crear el almacén FHIR.
  6. Haz clic en Siguiente.
  7. Para configurar tu almacén FHIR, haz lo siguiente:
    1. Elige la versión de FHIR del almacén FHIR: DSTU2, STU3 o R4.
    2. Selecciona los ajustes avanzados que correspondan de entre los siguientes:
      • Permitir creación con actualización: selecciona esta opción para permitir la creación de un recurso mediante una operación de actualización con un ID especificado por el usuario.
      • Comprobaciones de integridad referencial: selecciona esta opción para habilitar la integridad referencial en esta tienda. No se puede cambiar después de crear la tienda.
      • Gestión de versiones de recursos: selecciona esta opción para registrar automáticamente las versiones históricas de los recursos. No se puede cambiar después de crear la tienda.
    3. Selecciona los ajustes de validación de perfil aplicables en los campos siguientes. Para obtener más información, consulta ValidationConfig:
      • Habilitar validación de perfil: selecciona esta opción para habilitar la validación de perfil. Para aplicar una guía de implementación habilitada en tu almacén FHIR, debes habilitar la validación de perfiles.
      • Habilitar la validación de campos obligatorios: selecciona esta opción para habilitar la validación de campos de recursos en las definiciones de estructura de tu perfil de FHIR.
      • Habilitar validación de tipo de referencia: selecciona esta opción para habilitar la validación de tipo de referencia.
      • Habilitar validación de FHIRPath: selecciona esta opción para habilitar la comprobación de compatibilidad con FHIRPath.
    4. Haz clic en Siguiente.
  8. Opcional: Para habilitar las guías de implementación en tu tienda FHIR, haz lo siguiente:
    1. Haz clic en Habilitar guías de implementación.
    2. Haz clic en la lista Guías de implementación para desplegarla.
    3. Seleccione las guías de implementación correspondientes de la lista.

      Cada guía de implementación admite una versión específica de FHIR. En la lista solo se muestran las guías de implementación compatibles con la versión del almacén FHIR seleccionado.

    4. Haz clic en Importar IG personalizado de Cloud Storage para importar cualquier paquete de validación de perfil personalizado desde una ubicación de Cloud Storage.
    5. En el panel Seleccionar objeto, elija un recurso de paquete de validación de perfil de una ubicación de Cloud Storage. Para obtener más información, consulta Usar la consola Google Cloud para habilitar las guías de implementación.
    6. Haz clic en Seleccionar.
      • Las guías de implementación seleccionadas se muestran en una tabla con su versión, URL y estado.
      • Si has habilitado las guías de implementación, pero no has habilitado la validación de perfiles, la guía de implementación no se aplicará.
      • Haz clic en Siguiente.
  9. Opcional: Para exportar cambios en recursos a BigQuery cada vez que se creen, actualicen, eliminen o se les apliquen parches a los recursos FHIR de tu almacén, haz lo siguiente:
    1. Haga clic en Enviar cambios en recursos a BigQuery.
    2. Haz clic en Añadir una configuración de streaming. Para obtener más información sobre la transmisión de BigQuery, consulta el artículo Transmitir cambios en los recursos FHIR a BigQuery.
    3. Selecciona el nivel de profundidad en el control deslizante Profundidad de la estructura recursiva para definir la profundidad de todas las estructuras recursivas del esquema de salida. De forma predeterminada, el valor de profundidad recursiva es 2.
    4. Haz clic en Hecho para guardar la configuración de la emisión.
    5. Haz clic en Siguiente.
  10. Opcional: Para configurar un tema de Pub/Sub para el almacén FHIR, haga lo siguiente:
    1. Haz clic en Recibir notificaciones de Cloud Pub/Sub.
    2. Haz clic en Añadir un tema de Cloud Pub/Sub y selecciona el nombre del tema.

      Cuando especifiques un tema de Pub/Sub, introduce el URI completo del tema, tal como se muestra en el siguiente ejemplo:

      projects/PROJECT_ID/topics/PUBSUB_TOPIC

    3. Haz clic en Siguiente.
  11. Opcional: Para añadir etiquetas a la tienda, siga estos pasos:
    1. Haga clic en Añadir etiquetas para organizar los almacenes de datos.
    2. Introduce la clave y el valor de la etiqueta. Para obtener más información sobre las etiquetas de recursos, consulta el artículo Usar etiquetas de recursos.
    3. Haz clic en Crear.

El nuevo almacén de FHIR aparece en la lista.

gcloud

Para crear un almacén FHIR en el conjunto de datos, ejecuta el comando gcloud healthcare fhir-stores create.

Antes de usar los datos de los comandos que se indican a continuación, haz los siguientes cambios:

  • LOCATION: la ubicación del conjunto de datos
  • DATASET_ID: el conjunto de datos superior del almacén FHIR
  • FHIR_STORE_ID: identificador del almacén FHIR. El ID de almacén FHIR debe tener lo siguiente:
    • Un ID único en su conjunto de datos
    • Una cadena Unicode de entre 1 y 256 caracteres que incluya lo siguiente:
      • Numbers
      • Cartas
      • Guiones bajos
      • Guiones
      • Periodos
  • FHIR_STORE_VERSION: la versión de FHIR del almacén FHIR. Las opciones disponibles son DSTU2, STU3 o R4.

Ejecuta el siguiente comando:

Linux, macOS o Cloud Shell

gcloud healthcare fhir-stores create FHIR_STORE_ID \
  --dataset=DATASET_ID \
  --location=LOCATION \
  --version=FHIR_STORE_VERSION

Windows (PowerShell)

gcloud healthcare fhir-stores create FHIR_STORE_ID `
  --dataset=DATASET_ID `
  --location=LOCATION `
  --version=FHIR_STORE_VERSION

Windows (cmd.exe)

gcloud healthcare fhir-stores create FHIR_STORE_ID ^
  --dataset=DATASET_ID ^
  --location=LOCATION ^
  --version=FHIR_STORE_VERSION

Deberías recibir una respuesta similar a la siguiente:

Respuesta

Created fhirStore [FHIR_STORE_ID].

REST

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • PROJECT_ID: el ID de tu Google Cloud proyecto
  • LOCATION: la ubicación del conjunto de datos
  • DATASET_ID: el conjunto de datos superior del almacén FHIR
  • FHIR_STORE_ID: identificador del almacén FHIR. El ID de almacén FHIR debe tener lo siguiente:
    • Un ID único en su conjunto de datos
    • Una cadena Unicode de entre 1 y 256 caracteres que incluya lo siguiente:
      • Numbers
      • Cartas
      • Guiones bajos
      • Guiones
      • Periodos
  • FHIR_STORE_VERSION: la versión de FHIR del almacén FHIR. Las opciones disponibles son DSTU2, STU3 o R4.

Cuerpo JSON de la solicitud:

{
  "version": "FHIR_STORE_VERSION"
}

Para enviar tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json. Ejecuta el siguiente comando en el terminal para crear o sobrescribir este archivo en el directorio actual:

cat > request.json << 'EOF'
{
  "version": "FHIR_STORE_VERSION"
}
EOF

A continuación, ejecuta el siguiente comando para enviar tu solicitud REST:

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

PowerShell

Guarda el cuerpo de la solicitud en un archivo llamado request.json. Ejecuta el siguiente comando en el terminal para crear o sobrescribir este archivo en el directorio actual:

@'
{
  "version": "FHIR_STORE_VERSION"
}
'@  | Out-File -FilePath request.json -Encoding utf8

A continuación, ejecuta el siguiente comando para enviar tu solicitud REST:

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

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

Explorador de APIs

Copia el cuerpo de la solicitud y abre la página de referencia del método. El panel Explorador de APIs se abre en la parte derecha de la página. Puedes interactuar con esta herramienta para enviar solicitudes. Pega el cuerpo de la solicitud en esta herramienta, rellena los campos obligatorios y haz clic en Ejecutar.

Deberías recibir una respuesta JSON similar a la siguiente:

Go

import (
	"context"
	"fmt"
	"io"

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

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

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

	storesService := healthcareService.Projects.Locations.Datasets.FhirStores

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

	resp, err := storesService.Create(parent, &healthcare.FhirStore{Version: version}).FhirStoreId(fhirStoreID).Do()
	if err != nil {
		return fmt.Errorf("Create: %w", err)
	}

	fmt.Fprintf(w, "Created FHIR store: %q\n", resp.Name)
	return nil
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets.FhirStores;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.FhirStore;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

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

  public static void fhirStoreCreate(String datasetName, String fhirStoreId) throws IOException {
    // String datasetName =
    //     String.format(DATASET_NAME, "your-project-id", "your-region-id", "your-dataset-id");
    // String fhirStoreId = "your-fhir-id"

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

    // Configure the FhirStore to be created.
    Map<String, String> labels = new HashMap<>();
    labels.put("key1", "value1");
    labels.put("key2", "value2");
    String version = "STU3";
    FhirStore content = new FhirStore().setLabels(labels).setVersion(version);

    // Create request and configure any parameters.
    FhirStores.Create request =
        client
            .projects()
            .locations()
            .datasets()
            .fhirStores()
            .create(datasetName, content)
            .setFhirStoreId(fhirStoreId);

    // Execute the request and process the results.
    FhirStore response = request.execute();
    System.out.println("FHIR store created: " + response.toPrettyString());
  }

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

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

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

Node.js

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

const createFhirStore = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const version = 'STU3';
  const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}`;
  const request = {
    parent,
    fhirStoreId,
    resource: {
      version,
    },
  };

  await healthcare.projects.locations.datasets.fhirStores.create(request);
  console.log(`Created FHIR store: ${fhirStoreId}`);
};

createFhirStore();

Python

def create_fhir_store(project_id, location, dataset_id, fhir_store_id, version):
    """Creates a new FHIR store within the parent dataset.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

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

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'  # replace with your GCP project ID
    # location = 'us-central1'  # replace with the parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the FHIR store's parent dataset ID
    # fhir_store_id = 'my-fhir-store'  # replace with the FHIR store's ID
    # version = 'R4'  # replace with the FHIR store version
    fhir_store_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )

    body = {"version": version}

    request = (
        client.projects()
        .locations()
        .datasets()
        .fhirStores()
        .create(parent=fhir_store_parent, body=body, fhirStoreId=fhir_store_id)
    )

    response = request.execute()
    print(f"Created FHIR store: {fhir_store_id}")

    return response

Editar un almacén FHIR

En los ejemplos siguientes se muestra cómo editar un almacén FHIR. Puedes editar un almacén FHIR para modificar propiedades como las siguientes:

  • El tema de Pub/Sub al que la API Cloud Healthcare envía notificaciones de cambios en el almacén FHIR.
  • Las etiquetas del almacén FHIR. Las etiquetas son pares clave-valor que te ayudan a organizar tus Google Cloud recursos.
Cuando especifiques un tema de Pub/Sub, introduce el URI completo del tema, tal como se muestra en el siguiente ejemplo:
projects/PROJECT_ID/topics/PUBSUB_TOPIC
Para que las notificaciones funcionen, debes conceder permisos adicionales a la cuenta de servicio del agente de servicio de Cloud Healthcare. Para obtener más información, consulta Permisos de Pub/Sub para almacenes DICOM, FHIR y HL7v2.

Consola

Para editar un almacén FHIR, sigue estos pasos:

  1. En la Google Cloud consola, ve a la página Conjuntos de datos.
    Ir a conjuntos de datos

  2. Seleccione el conjunto de datos que contenga el almacén FHIR que quiera editar.

  3. En la lista Almacenes de datos, seleccione el almacén de FHIR que quiera editar.

  4. Para editar la configuración del almacén, haz clic en Configuración del almacén FHIR.

    Para obtener más información sobre las opciones de configuración de un almacén FHIR, consulta el artículo Crear un almacén FHIR.

  5. Para editar las guías de implementación de la tienda, haga clic en Guías de implementación y seleccione las guías de implementación correspondientes. También puede importar una guía de implementación personalizada desde Cloud Storage. Para obtener más información, consulta Usar la consola Google Cloud para habilitar guías de implementación.

    Para editar las guías de implementación o aplicar las guías de implementación habilitadas, debe habilitar la validación de perfiles en la sección Configuración del almacén FHIR.

  6. Para exportar cambios en recursos a BigQuery cada vez que se creen, actualicen, eliminen o se les apliquen parches a los recursos FHIR de tu almacén, haz clic en Añadir nueva configuración de streaming en el campo Conjunto de datos.

  7. Selecciona un conjunto de datos de BigQuery en el que se enviarán los cambios en los recursos. Para obtener más información sobre la transmisión de datos a BigQuery, consulta el artículo Transmitir cambios en los recursos FHIR a BigQuery.

  8. Para definir la profundidad de todas las estructuras recursivas del esquema de salida, haz clic en la profundidad correspondiente en el control deslizante Profundidad de estructura recursiva. De forma predeterminada, la profundidad recursiva es 2.

  9. Para exportar los cambios de recursos solo de tipos de recursos específicos, seleccione los tipos de recursos en la lista Seleccionar tipos de recursos FHIR.

  10. Para configurar un tema de Pub/Sub para el almacén de datos, selecciona un nombre de tema en la sección Notificaciones de Cloud Pub/Sub. Cuando especifiques un tema de Pub/Sub, introduce el URI completo del tema, tal como se muestra en el siguiente ejemplo:

    projects/PROJECT_ID/topics/PUBSUB_TOPIC

  11. Para añadir una o varias etiquetas a la tienda, haz clic en Etiquetas, en Añadir etiqueta e introduce la etiqueta clave-valor. Para obtener más información sobre las etiquetas de recursos, consulta el artículo Usar etiquetas de recursos.

  12. Haz clic en Guardar.

gcloud

Para editar un almacén FHIR, ejecuta el comando gcloud healthcare fhir-stores update.

Antes de usar los datos de los comandos que se indican a continuación, haz los siguientes cambios:

  • PROJECT_ID: el ID de tu Google Cloud proyecto
  • LOCATION: la ubicación del conjunto de datos
  • DATASET_ID: el conjunto de datos superior del almacén FHIR
  • FHIR_STORE_ID: el ID del almacén FHIR
  • PUBSUB_TOPIC_ID: un tema de Pub/Sub en el que se publican mensajes cuando se produce un evento en un almacén de datos.

Ejecuta el siguiente comando:

Linux, macOS o Cloud Shell

gcloud healthcare fhir-stores update FHIR_STORE_ID \
  --dataset=DATASET_ID \
  --location=LOCATION \
  --pubsub-topic=projects/PROJECT_ID/topics/PUBSUB_TOPIC_ID

Windows (PowerShell)

gcloud healthcare fhir-stores update FHIR_STORE_ID `
  --dataset=DATASET_ID `
  --location=LOCATION `
  --pubsub-topic=projects/PROJECT_ID/topics/PUBSUB_TOPIC_ID

Windows (cmd.exe)

gcloud healthcare fhir-stores update FHIR_STORE_ID ^
  --dataset=DATASET_ID ^
  --location=LOCATION ^
  --pubsub-topic=projects/PROJECT_ID/topics/PUBSUB_TOPIC_ID

Deberías recibir una respuesta similar a la siguiente:

Respuesta

Updated fhirStore [FHIR_STORE_ID].
name: projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID
notificationConfig:
 pubsubTopic: projects/PROJECT_ID/topics/PUBSUB_TOPIC_ID
version: FHIR_STORE_VERSION

REST

Para editar un almacén FHIR, usa el método projects.locations.datasets.fhirStores.patch.

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • PROJECT_ID: el ID de tu Google Cloud proyecto
  • LOCATION: la ubicación del conjunto de datos
  • DATASET_ID: el conjunto de datos superior del almacén FHIR
  • FHIR_STORE_ID: el ID del almacén FHIR
  • PUBSUB_TOPIC_ID: un tema de Pub/Sub en el que se publican mensajes cuando se produce un evento en un almacén de datos. Para determinar qué datos se deben incluir en las notificaciones de Pub/Sub, consulta Notificaciones de Pub/Sub de FHIR.
  • KEY1: la primera clave de etiqueta
  • VALUE1: el primer valor de la etiqueta
  • KEY2: la segunda clave de etiqueta
  • VALUE2: el segundo valor de la etiqueta

Cuerpo JSON de la solicitud:

{
  "notificationConfigs": [
    {
      "pubsubTopic": "projects/PROJECT_ID/topics/PUBSUB_TOPIC_ID"
    }
  ],
  "labels": {
    "KEY1": "VALUE1",
    "KEY2": "VALUE2"
  }
}

Para enviar tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json. Ejecuta el siguiente comando en el terminal para crear o sobrescribir este archivo en el directorio actual:

cat > request.json << 'EOF'
{
  "notificationConfigs": [
    {
      "pubsubTopic": "projects/PROJECT_ID/topics/PUBSUB_TOPIC_ID"
    }
  ],
  "labels": {
    "KEY1": "VALUE1",
    "KEY2": "VALUE2"
  }
}
EOF

A continuación, ejecuta el siguiente comando para enviar tu solicitud REST:

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

PowerShell

Guarda el cuerpo de la solicitud en un archivo llamado request.json. Ejecuta el siguiente comando en el terminal para crear o sobrescribir este archivo en el directorio actual:

@'
{
  "notificationConfigs": [
    {
      "pubsubTopic": "projects/PROJECT_ID/topics/PUBSUB_TOPIC_ID"
    }
  ],
  "labels": {
    "KEY1": "VALUE1",
    "KEY2": "VALUE2"
  }
}
'@  | Out-File -FilePath request.json -Encoding utf8

A continuación, ejecuta el siguiente comando para enviar tu solicitud REST:

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

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

Explorador de APIs

Copia el cuerpo de la solicitud y abre la página de referencia del método. El panel Explorador de APIs se abre en la parte derecha de la página. Puedes interactuar con esta herramienta para enviar solicitudes. Pega el cuerpo de la solicitud en esta herramienta, rellena los campos obligatorios y haz clic en Ejecutar.

Deberías recibir una respuesta JSON similar a la siguiente:

Go

import (
	"context"
	"fmt"
	"io"

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

// patchFHIRStore updates (patches) a FHIR store by updating its Pub/sub topic name.
func patchFHIRStore(w io.Writer, projectID, location, datasetID, fhirStoreID, topicName string) error {
	ctx := context.Background()

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

	storesService := healthcareService.Projects.Locations.Datasets.FhirStores

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

	// topicName format is "projects/*/locations/*/topics/*"
	notificationConfig := &healthcare.FhirNotificationConfig{
		PubsubTopic: topicName,
	}

	fhirStore := &healthcare.FhirStore{
		NotificationConfigs: []*healthcare.FhirNotificationConfig{notificationConfig},
	}

	patchRequest := storesService.Patch(name, fhirStore).UpdateMask("notificationConfigs")

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

	fmt.Fprintf(w, "Patched FHIR store %s with Pub/sub topic %s\n", datasetID, topicName)

	return nil
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets.FhirStores;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.FhirNotificationConfig;
import com.google.api.services.healthcare.v1.model.FhirStore;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

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

  public static void fhirStorePatch(String fhirStoreName, String pubsubTopic) throws IOException {
    // String fhirStoreName =
    // String.format(
    // FHIR_NAME, "your-project-id", "your-region-id", "your-dataset-id",
    // "your-fhir-id");
    // String pubsubTopic = "projects/your-project-id/topics/your-pubsub-topic";

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

    // Fetch the initial state of the FHIR store.
    FhirStores.Get getRequest = client
        .projects()
        .locations()
        .datasets()
        .fhirStores()
        .get(fhirStoreName);
    FhirStore store = getRequest.execute();

    // Update the FhirStore fields as needed as needed. For a full list of FhirStore
    // fields, see:
    // https://cloud.google.com/healthcare/docs/reference/rest/v1/projects.locations.datasets.fhirStores#FhirStore
    FhirNotificationConfig notificationConfig = new FhirNotificationConfig()
        .setPubsubTopic(pubsubTopic);
    store.setNotificationConfigs(Collections.singletonList(notificationConfig));

    // Create request and configure any parameters.
    FhirStores.Patch request = client
        .projects()
        .locations()
        .datasets()
        .fhirStores()
        .patch(fhirStoreName, store)
        .setUpdateMask("notificationConfigs");

    // Execute the request and process the results.
    store = request.execute();
    System.out.println("FHIR store patched: \n" + store.toPrettyString());
  }

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

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

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

Node.js

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

const patchFhirStore = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const pubsubTopic = 'my-topic'
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}`;
  const request = {
    name,
    updateMask: 'notificationConfigs',
    resource: {
      notificationConfigs: [
        {
          pubsubTopic: `projects/${projectId}/topics/${pubsubTopic}`,
        },
      ],
    },
  };

  await healthcare.projects.locations.datasets.fhirStores.patch(request);
  console.log(
    `Patched FHIR store ${fhirStoreId} with Cloud Pub/Sub topic ${pubsubTopic}`
  );
};

patchFhirStore();

Python

def patch_fhir_store(project_id, location, dataset_id, fhir_store_id, pubsub_topic):
    """Updates the FHIR store.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

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

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'  # replace with your GCP project ID
    # location = 'us-central1'  # replace with the dataset's location
    # dataset_id = 'my-dataset'  # replace with your dataset ID
    # fhir_store_id = 'my-fhir-store'  # replace with the FHIR store's ID
    # pubsub_topic = 'projects/{project_id}/topics/{topic_id}'  # replace with your Pub/Sub topic
    fhir_store_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )
    fhir_store_name = f"{fhir_store_parent}/fhirStores/{fhir_store_id}"

    patch = {
        "notificationConfigs": [{"pubsubTopic": pubsub_topic}] if pubsub_topic else []
    }

    request = (
        client.projects()
        .locations()
        .datasets()
        .fhirStores()
        .patch(name=fhir_store_name, updateMask="notificationConfigs", body=patch)
    )

    response = request.execute()
    print(
        f"Patched FHIR store {fhir_store_id} with Cloud Pub/Sub topic: {pubsub_topic or 'None'}"
    )

    return response

Obtener detalles del almacén FHIR

En los ejemplos siguientes se muestra cómo obtener detalles de un almacén FHIR.

Consola

Para ver los detalles de un almacén FHIR, sigue estos pasos:

  1. En la Google Cloud consola, ve a la página Conjuntos de datos.

    Ve a Conjuntos de datos.

  2. Seleccione el conjunto de datos que contiene el almacén FHIR.
  3. Haga clic en el nombre del almacén FHIR.

gcloud

Para obtener detalles sobre un almacén FHIR, ejecuta el comando gcloud healthcare fhir-stores describe.

Antes de usar los datos de los comandos que se indican a continuación, haz los siguientes cambios:

  • LOCATION: la ubicación del conjunto de datos
  • DATASET_ID: el conjunto de datos superior del almacén FHIR
  • FHIR_STORE_ID: el ID del almacén FHIR

Ejecuta el siguiente comando:

Linux, macOS o Cloud Shell

gcloud healthcare fhir-stores describe FHIR_STORE_ID \
 --dataset=DATASET_ID \
 --location=LOCATION

Windows (PowerShell)

gcloud healthcare fhir-stores describe FHIR_STORE_ID `
 --dataset=DATASET_ID `
 --location=LOCATION

Windows (cmd.exe)

gcloud healthcare fhir-stores describe FHIR_STORE_ID ^
 --dataset=DATASET_ID ^
 --location=LOCATION

Deberías recibir una respuesta similar a la siguiente.

Si has configurado algún campo del recurso FhirStore, también aparecerá en la respuesta.

Respuesta

...
name: projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID
...
version: FHIR_STORE_VERSION

REST

Para obtener detalles sobre un almacén FHIR, usa el método projects.locations.datasets.fhirStores.get.

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • PROJECT_ID: el ID de tu Google Cloud proyecto
  • LOCATION: la ubicación del conjunto de datos
  • DATASET_ID: el conjunto de datos superior del almacén FHIR
  • FHIR_STORE_ID: el ID del almacén FHIR

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el comando siguiente:

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

PowerShell

Ejecuta el comando siguiente:

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

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

Explorador de APIs

Abre la página de referencia del método. El panel Explorador de APIs se abre en la parte derecha de la página. Puedes interactuar con esta herramienta para enviar solicitudes. Rellena los campos obligatorios y haz clic en Ejecutar.

Deberías recibir una respuesta similar a la siguiente.

Si has configurado algún campo del recurso FhirStore, también aparecerá en la respuesta.

Go

import (
	"context"
	"fmt"
	"io"

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

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

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

	storesService := healthcareService.Projects.Locations.Datasets.FhirStores

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

	store, err := storesService.Get(name).Do()
	if err != nil {
		return fmt.Errorf("Get: %w", err)
	}

	fmt.Fprintf(w, "Got FHIR store: %q\n", store.Name)
	return nil
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets.FhirStores;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.FhirStore;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

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

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

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

    // Create request and configure any parameters.
    FhirStores.Get request =
        client.projects().locations().datasets().fhirStores().get(fhirStoreName);

    // Execute the request and process the results.
    FhirStore store = request.execute();
    System.out.println("FHIR store retrieved: \n" + store.toPrettyString());
  }

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

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

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

Node.js

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

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

  const fhirStore =
    await healthcare.projects.locations.datasets.fhirStores.get(request);
  console.log(fhirStore.data);
};

getFhirStore();

Python

def get_fhir_store(project_id, location, dataset_id, fhir_store_id):
    """Gets the specified FHIR store.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    # Imports Python's built-in "json" module
    import json

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

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

    fhir_stores = client.projects().locations().datasets().fhirStores()
    fhir_store = fhir_stores.get(name=fhir_store_name).execute()

    print(json.dumps(fhir_store, indent=2))
    return fhir_store

Mostrar los almacenes FHIR de un conjunto de datos

En los ejemplos siguientes se muestra cómo enumerar los almacenes FHIR en un conjunto de datos.

Consola

Para ver los almacenes de datos de un conjunto de datos, sigue estos pasos:

  1. En la Google Cloud consola, ve a la página Conjuntos de datos.

    Ve a Conjuntos de datos.

  2. Selecciona el conjunto de datos que contiene el almacén de datos que quieres ver.

gcloud

Para ver los detalles de un almacén FHIR, ejecuta el comando gcloud healthcare fhir-stores list.

Antes de usar los datos de los comandos que se indican a continuación, haz los siguientes cambios:

  • DATASET_ID: el conjunto de datos superior del almacén FHIR
  • LOCATION: la ubicación del conjunto de datos

Ejecuta el siguiente comando:

Linux, macOS o Cloud Shell

gcloud healthcare fhir-stores list --dataset=DATASET_ID --location=LOCATION

Windows (PowerShell)

gcloud healthcare fhir-stores list --dataset=DATASET_ID --location=LOCATION

Windows (cmd.exe)

gcloud healthcare fhir-stores list --dataset=DATASET_ID --location=LOCATION

Deberías recibir una respuesta similar a la siguiente.

Si has configurado algún campo del recurso FhirStore, también aparecerá en la respuesta.

ID             LOCATION     REF_INT  RES_VER  UPDATE_CREATE  TOPIC
FHIR_STORE_ID  LOCATION                                       PUBSUB_TOPIC
...

REST

Para enumerar los almacenes FHIR de un conjunto de datos, usa el método projects.locations.datasets.fhirStores.list.

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • PROJECT_ID: el ID de tu Google Cloud proyecto
  • DATASET_ID: el conjunto de datos superior del almacén FHIR
  • LOCATION: la ubicación del conjunto de datos

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el comando siguiente:

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

PowerShell

Ejecuta el comando siguiente:

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

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

Explorador de APIs

Abre la página de referencia del método. El panel Explorador de APIs se abre en la parte derecha de la página. Puedes interactuar con esta herramienta para enviar solicitudes. Rellena los campos obligatorios y haz clic en Ejecutar.

Deberías recibir una respuesta similar a la siguiente.

Si has configurado algún campo del recurso FhirStore, también aparecerá en la respuesta.

Go

import (
	"context"
	"fmt"
	"io"

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

// listFHIRStores prints a list of FHIR stores to w.
func listFHIRStores(w io.Writer, projectID, location, datasetID string) error {
	ctx := context.Background()

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

	storesService := healthcareService.Projects.Locations.Datasets.FhirStores

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

	resp, err := storesService.List(parent).Do()
	if err != nil {
		return fmt.Errorf("List: %w", err)
	}

	fmt.Fprintln(w, "FHIR stores:")
	for _, s := range resp.FhirStores {
		fmt.Fprintln(w, s.Name)
	}
	return nil
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets.FhirStores;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.FhirStore;
import com.google.api.services.healthcare.v1.model.ListFhirStoresResponse;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

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

  public static void fhirStoreList(String datasetName) throws IOException {
    // String datasetName =
    //    String.format(DATASET_NAME, "your-project-id", "your-region-id", "your-dataset-id");

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

    // Results are paginated, so multiple queries may be required.
    String pageToken = null;
    List<FhirStore> stores = new ArrayList<>();
    do {
      // Create request and configure any parameters.
      FhirStores.List request =
          client
              .projects()
              .locations()
              .datasets()
              .fhirStores()
              .list(datasetName)
              .setPageSize(100) // Specify pageSize up to 1000
              .setPageToken(pageToken);

      // Execute response and collect results.
      ListFhirStoresResponse response = request.execute();
      stores.addAll(response.getFhirStores());

      // Update the page token for the next request.
      pageToken = response.getNextPageToken();
    } while (pageToken != null);

    // Print results.
    System.out.printf("Retrieved %s Fhir stores: \n", stores.size());
    for (FhirStore data : stores) {
      System.out.println("\t" + data.toPrettyString());
    }
  }

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

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

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

Node.js

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

const listFhirStores = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}`;
  const request = {parent};

  const fhirStores =
    await healthcare.projects.locations.datasets.fhirStores.list(request);
  console.log(JSON.stringify(fhirStores.data));
};

listFhirStores();

Python

def list_fhir_stores(project_id, location, dataset_id):
    """Lists the FHIR stores in the given dataset.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

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

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'  # replace with your GCP project ID
    # location = 'us-central1'  # replace with the dataset's location
    # dataset_id = 'my-dataset'  # replace with the parent dataset's ID
    fhir_store_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )

    fhir_stores = (
        client.projects()
        .locations()
        .datasets()
        .fhirStores()
        .list(parent=fhir_store_parent)
        .execute()
        .get("fhirStores", [])
    )

    for fhir_store in fhir_stores:
        print(fhir_store)

    return fhir_stores

Obtener la declaración de capacidades o de conformidad de un almacén FHIR

En los ejemplos siguientes se muestra cómo obtener la declaración de capacidades (STU3, R4 o R5) o de conformidad (DSTU2) de un almacén FHIR.

La información incluida en la declaración de capacidades o de conformidad refleja la configuración del almacén FHIR. Por ejemplo, si FhirStore.enableUpdateCreate se define como true, esto se reflejará en el campo CapabilityStatement.rest.resource.updateCreate de la declaración de funciones.

En la siguiente tabla se muestra el método de la API Cloud Healthcare para obtener la declaración de capacidades o de conformidad de un almacén FHIR y su interacción de la especificación FHIR equivalente:

Método de la API Cloud Healthcare Interacción de la especificación FHIR
projects.locations.datasets.fhirStores.fhir.capabilities capabilities (STU3, R4 o R5) o conformance (DSTU2)

Consola

La consola de Google Cloud y la CLI de gcloud no admiten esta acción. En su lugar, usa curl, PowerShell o el lenguaje que prefieras.

gcloud

La consola de Google Cloud y la CLI de gcloud no admiten esta acción. En su lugar, usa curl, PowerShell o el lenguaje que prefieras.

REST

Para obtener la declaración de capacidades o de conformidad de un almacén FHIR, usa el método projects.locations.datasets.fhirStores.fhir.capabilities.

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • PROJECT_ID: el ID de tu Google Cloud proyecto
  • LOCATION: la ubicación del conjunto de datos
  • DATASET_ID: el conjunto de datos superior del almacén FHIR
  • FHIR_STORE_ID: el ID del almacén FHIR

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el comando siguiente:

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

PowerShell

Ejecuta el comando siguiente:

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

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

Explorador de APIs

Abre la página de referencia del método. El panel Explorador de APIs se abre en la parte derecha de la página. Puedes interactuar con esta herramienta para enviar solicitudes. Rellena los campos obligatorios y haz clic en Ejecutar.

Deberías recibir una respuesta JSON similar a la siguiente:

Go

import (
	"context"
	"fmt"
	"io"

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

// getFHIRMetadata gets FHIR store metadata.
func getFHIRMetadata(w io.Writer, projectID, location, datasetID, fhirStoreID string) error {
	ctx := context.Background()

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

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

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

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

	defer resp.Body.Close()

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

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

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets.FhirStores.Fhir.Capabilities;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.HttpBody;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

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

  public static void fhirStoreGetMetadata(String fhirStoreName) throws IOException {
    // String fhirStoreName =
    //    String.format(
    //        FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id");

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

    // Create request and configure any parameters.
    Capabilities request =
        client.projects().locations().datasets().fhirStores().fhir().capabilities(fhirStoreName);

    // Execute the request and process the results.
    HttpBody response = request.execute();
    System.out.println("FHIR store metadata retrieved: " + response.toPrettyString());
  }

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

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

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

Node.js

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

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

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

getFhirStoreCapabilities();

Python

def get_fhir_store_metadata(project_id, location, dataset_id, fhir_store_id):
    """Gets the FHIR capability statement (STU3, R4), or the conformance statement
    in the DSTU2 case for the store, which contains a description of functionality
    supported by the server.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    # Imports Python's built-in "json" module
    import json

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

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

    fhir_stores = client.projects().locations().datasets().fhirStores()
    response = fhir_stores.fhir().capabilities(name=fhir_store_name).execute()

    print(json.dumps(response, indent=2))
    return response

Definir el nivel de validación de recursos base

De forma predeterminada, todos los recursos de tu almacén FHIR tienen aplicada la validación de recursos base. Esta validación asegura que se cumplan las siguientes condiciones cuando se cree el recurso:

  • Se han definido todos los campos obligatorios.
  • Todos los tipos de recursos a los que se hace referencia son válidos.
  • El recurso cumple todas las restricciones de FHIRPath.

Puedes hacer que la validación de recursos base sea menos estricta inhabilitando uno o varios de estos tipos de validación de recursos base en tu almacén FHIR.

Consola

La consola de Google Cloud y la CLI de gcloud no admiten esta acción. En su lugar, usa curl, PowerShell o el lenguaje que prefieras.

gcloud

La consola de Google Cloud y la CLI de gcloud no admiten esta acción. En su lugar, usa curl, PowerShell o el lenguaje que prefieras.

REST

Para inhabilitar la validación de recursos base en un almacén FHIR, usa el método projects.locations.datasets.fhirStores.patch.

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • PROJECT_ID: el ID de tu Google Cloud proyecto
  • DATASET_ID: el conjunto de datos superior del almacén FHIR
  • LOCATION: la ubicación del conjunto de datos
  • BASE_RESOURCE_VALIDATION_TYPE: el tipo de validación de recursos base que quieras inhabilitar. Para inhabilitar la validación, asigna el valor true a cualquiera de los siguientes campos:
    • disableRequiredFieldValidation
    • disableReferenceTypeValidation
    • disableFhirpathValidation

Cuerpo JSON de la solicitud:

{
  "validationConfig": {
    "BASE_RESOURCE_VALIDATION_TYPE": true
  }
}

Para enviar tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json. Ejecuta el siguiente comando en el terminal para crear o sobrescribir este archivo en el directorio actual:

cat > request.json << 'EOF'
{
  "validationConfig": {
    "BASE_RESOURCE_VALIDATION_TYPE": true
  }
}
EOF

A continuación, ejecuta el siguiente comando para enviar tu solicitud REST:

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

PowerShell

Guarda el cuerpo de la solicitud en un archivo llamado request.json. Ejecuta el siguiente comando en el terminal para crear o sobrescribir este archivo en el directorio actual:

@'
{
  "validationConfig": {
    "BASE_RESOURCE_VALIDATION_TYPE": true
  }
}
'@  | Out-File -FilePath request.json -Encoding utf8

A continuación, ejecuta el siguiente comando para enviar tu solicitud REST:

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

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

Explorador de APIs

Copia el cuerpo de la solicitud y abre la página de referencia del método. El panel Explorador de APIs se abre en la parte derecha de la página. Puedes interactuar con esta herramienta para enviar solicitudes. Pega el cuerpo de la solicitud en esta herramienta, rellena los campos obligatorios y haz clic en Ejecutar.

Deberías recibir una respuesta similar a la siguiente.

Si has configurado algún campo del recurso FhirStore, también aparecerá en la respuesta.

Eliminar un almacén FHIR

En los ejemplos siguientes se muestra cómo eliminar un almacén FHIR.

Consola

Para eliminar un almacén de datos, sigue estos pasos:

  1. En la Google Cloud consola, ve a la página Conjuntos de datos.

    Ve a Conjuntos de datos.

  2. Selecciona el conjunto de datos que contiene el almacén de datos que quieres eliminar.
  3. En la lista desplegable Acciones del almacén de datos que quiere eliminar, seleccione Eliminar.
  4. Para confirmar la acción, escribe el nombre del almacén de datos y haz clic en Eliminar.

gcloud

Para eliminar un almacén FHIR, ejecuta el comando gcloud healthcare fhir-stores delete.

Antes de usar los datos de los comandos que se indican a continuación, haz los siguientes cambios:

  • LOCATION: la ubicación del conjunto de datos
  • DATASET_ID: el conjunto de datos superior del almacén FHIR
  • FHIR_STORE_ID: el ID del almacén FHIR

Ejecuta el siguiente comando:

Linux, macOS o Cloud Shell

gcloud healthcare fhir-stores delete FHIR_STORE_ID \
  --dataset=DATASET_ID \
  --location=LOCATION

Windows (PowerShell)

gcloud healthcare fhir-stores delete FHIR_STORE_ID `
  --dataset=DATASET_ID `
  --location=LOCATION

Windows (cmd.exe)

gcloud healthcare fhir-stores delete FHIR_STORE_ID ^
  --dataset=DATASET_ID ^
  --location=LOCATION

Deberías recibir una respuesta similar a la siguiente:

Deleted fhirStore [FHIR_STORE_ID].

REST

Para eliminar un almacén FHIR, usa el método projects.locations.datasets.fhirStores.delete.

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • PROJECT_ID: el ID de tu Google Cloud proyecto
  • LOCATION: la ubicación del conjunto de datos
  • DATASET_ID: el conjunto de datos superior del almacén FHIR
  • FHIR_STORE_ID: el ID del almacén FHIR

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el comando siguiente:

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

PowerShell

Ejecuta el comando siguiente:

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

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

Explorador de APIs

Abre la página de referencia del método. El panel Explorador de APIs se abre en la parte derecha de la página. Puedes interactuar con esta herramienta para enviar solicitudes. Rellena los campos obligatorios y haz clic en Ejecutar.

Deberías recibir una respuesta JSON similar a la siguiente:

Go

import (
	"context"
	"fmt"
	"io"

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

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

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

	storesService := healthcareService.Projects.Locations.Datasets.FhirStores

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

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

	fmt.Fprintf(w, "Deleted FHIR store: %q\n", fhirStoreID)
	return nil
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets.FhirStores;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

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

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

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

    // Create request and configure any parameters.
    FhirStores.Delete request =
        client.projects().locations().datasets().fhirStores().delete(fhirStoreName);

    // Execute the request and process the results.
    request.execute();
    System.out.println("FHIR store deleted.");
  }

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

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

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

Node.js

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

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

  await healthcare.projects.locations.datasets.fhirStores.delete(request);
  console.log(`Deleted FHIR store: ${fhirStoreId}`);
};

deleteFhirStore();

Python

def delete_fhir_store(project_id, location, dataset_id, fhir_store_id):
    """Deletes the specified FHIR store.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

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

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

    request = (
        client.projects()
        .locations()
        .datasets()
        .fhirStores()
        .delete(name=fhir_store_name)
    )

    response = request.execute()
    print(f"Deleted FHIR store: {fhir_store_id}")

    return response

Siguientes pasos

Aprende a crear recursos FHIR y a trabajar con ellos.