Como criar e gerenciar lojas HL7v2

Nesta página, você aprende a criar, editar, ver e excluir os armazenamentos de Health Level Seven Versão 2.x (HL7v2). Os armazenamentos HL7v2 contêm mensagens HL7v2, que são usadas para transmitir dados clínicos entre sistemas.

Como criar um armazenamento HL7v2

Antes de criar um armazenamento HL7v2, você precisa criar um conjunto de dados.

Ao criar um armazenamento HL7v2, especifique a versão do analisador V3. Não é possível alterar a versão do analisador depois de criar o armazenamento HL7v2.

Os exemplos a seguir mostram como criar um armazenamento HL7v2 usando o analisador V3.

Console

  1. No console do Google Cloud, acesse a página Conjuntos de dados.

    Acessar conjuntos de dados

  2. Selecione o conjunto de dados em que você quer criar o armazenamento de HL7v2. A página Conjunto de dados é exibida.

  3. Clique em Criar repositório de dados. A página Criar repositório de dados vai aparecer.

  4. No menu Tipo, selecione HL7v2.

  5. No campo ID, digite um nome para o armazenamento HL7v2. O nome precisa ser exclusivo no conjunto de dados. Consulte Requisitos de tamanho e caracteres permitidos para ver mais requisitos de nomenclatura.

  6. Clique em Próxima. A seção Configurar o armazenamento de HL7v2 será exibida.

  7. Defina as configurações a seguir:

    1. Na seção Versão, não altere a seleção padrão de V3.
    2. Para permitir a criação e a ingestão de mensagens HL7v2 sem cabeçalho, selecione Permitir cabeçalhos de mensagens nulos (MSH, na sigla em inglês).
    3. Para definir um terminador de segmento personalizado, clique em Definir um terminador de segmento personalizado e insira o terminador no campo Terminador de segmento. Para mais informações, consulte Como configurar o terminador de segmentos.
    4. Para rejeitar mensagens HL7v2 recebidas com os mesmos bytes brutos de uma mensagem HL7v2 que já existe no armazenamento HL7v2, selecione Rejeitar mensagens duplicadas.
  8. Clique em Próxima. A seção Receber notificações do Cloud Pub/Sub é exibida.

  9. Se você quiser receber notificações do Pub/Sub quando um evento clínico ocorrer no armazenamento HL7v2, especifique o tópico do Pub/Sub. O tópico precisa existir antes que você possa configurá-lo no armazenamento HL7v2.

  10. Clique em Próxima. A seção Adicionar rótulos para organizar seus armazenamentos de dados será exibida.

  11. Para adicionar um ou mais rótulos de chave-valor ao armazenamento HL7v2, clique em Adicionar rótulo. Para mais informações sobre rótulos de recursos, consulte Como usar rótulos de recursos.

  12. Clique em Criar. A página Conjunto de dados é exibida e o armazenamento de HL7v2 é exibido na tabela Repositórios de dados.

gcloud

A CLI do Google Cloud não oferece suporte à configuração da versão do analisador ao criar um armazenamento HL7v2. Em vez disso, use o console do Google Cloud, curl, PowerShell ou seu idioma preferido.

REST

Para criar um armazenamento HL7v2, use o método projects.locations.datasets.hl7V2Stores.create.

Antes de usar os dados da solicitação, faça as substituições a seguir:

Solicitar corpo JSON:

{
  "parserConfig": {
    "version": "V3"
  }
}

Para enviar a solicitação, escolha uma destas opções:

curl

Salve o corpo da solicitação em um arquivo chamado request.json. Execute o comando a seguir no terminal para criar ou substituir esse arquivo no diretório atual:

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

Depois execute o comando a seguir para enviar a solicitação 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/hl7V2Stores?hl7V2StoreId=HL7V2_STORE_ID"

PowerShell

Salve o corpo da solicitação em um arquivo chamado request.json. Execute o comando a seguir no terminal para criar ou substituir esse arquivo no diretório atual:

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

Depois execute o comando a seguir para enviar a solicitação 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/hl7V2Stores?hl7V2StoreId=HL7V2_STORE_ID" | Select-Object -Expand Content

APIs Explorer

Copie o corpo da solicitação e abra a página de referência do método. O painel "APIs Explorer" é aberto no lado direito da página. Interaja com essa ferramenta para enviar solicitações. Cole o corpo da solicitação nessa ferramenta, preencha todos os outros campos obrigatórios e clique em Executar.

Você receberá uma resposta JSON semelhante a esta:

Go

Ver no GitHub (em inglês) Feedback
import (
	"context"
	"fmt"
	"io"

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

// createHL7V2Store creates an HL7V2 store.
func createHL7V2Store(w io.Writer, projectID, location, datasetID, hl7V2StoreID 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.Hl7V2Stores

	// Set the HL7v2 store parser version to V3.
	store := &healthcare.Hl7V2Store{ParserConfig: &healthcare.ParserConfig{Version: "V3"}}
	parent := fmt.Sprintf("projects/%s/locations/%s/datasets/%s", projectID, location, datasetID)

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

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

Java

Ver no GitHub (em inglês) Feedback
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.Hl7V2Stores;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.Hl7V2Store;
import com.google.api.services.healthcare.v1.model.ParserConfig;
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 Hl7v2StoreCreate {
  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 hl7v2StoreCreate(String datasetName, String hl7v2StoreId) throws IOException {
    // String datasetName =
    // String.format(DATASET_NAME, "your-project-id", "your-region-id",
    // "your-dataset-id");
    // String hl7v2StoreId = "your-hl7v25-id"

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

    // Configure the store to be created.
    Map<String, String> labels = new HashMap<>();
    labels.put("key1", "value1");
    labels.put("key2", "value2");
    Hl7V2Store content =
        new Hl7V2Store().setLabels(labels).setParserConfig(new ParserConfig().setVersion("V3"));

    // Create request and configure any parameters.
    Hl7V2Stores.Create request = client
        .projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .create(datasetName, content)
        .setHl7V2StoreId(hl7v2StoreId);

    // Execute the request and process the results.
    Hl7V2Store response = request.execute();
    System.out.println("Hl7V2Store 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

Ver no GitHub (em inglês) Feedback
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 createHl7v2Store = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}`;
  const request = {
    parent,
    hl7V2StoreId: hl7v2StoreId,
    resource: {
      parserConfig: {
        version: 'V3',
      },
    },
  };

  await healthcare.projects.locations.datasets.hl7V2Stores.create(request);
  console.log(`Created HL7v2 store: ${hl7v2StoreId}`);
};

createHl7v2Store();

Python

Ver no GitHub (em inglês) Feedback
def create_hl7v2_store(project_id, location, dataset_id, hl7v2_store_id):
    """Creates a new HL7v2 store within the parent dataset.
    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/hl7v2
    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 HL7v2 store's parent dataset ID
    # hl7v2_store_id = 'my-hl7v2-store'  # replace with the HL7v2 store's ID
    hl7v2_store_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )

    # Use the V3 parser. Immutable after HL7v2 store creation.
    body = {"parserConfig": {"version": "V3"}}

    request = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .create(parent=hl7v2_store_parent, body=body, hl7V2StoreId=hl7v2_store_id)
    )

    response = request.execute()
    print(f"Created HL7v2 store: {hl7v2_store_id}")
    return response

Usar tópicos e filtros do Pub/Sub

Usar o Pub/Sub e filtros com armazenamentos HL7v2 é um caso de uso comum, principalmente ao transmitir mensagens HL7v2 por conexões TCP/IP.

Alguns dos exemplos nesta página mostram como configurar um tópico do Pub/Sub atual para que a API Cloud Healthcare envie notificações de eventos clínicos em um armazenamento HL7v2. Ao especificar uma lista de tópicos e filtros do Pub/Sub existentes, a API Cloud Healthcare pode enviar notificações para vários tópicos, e você pode usar os filtros para restringir quais notificações são enviadas. Para mais informações sobre como configurar tópicos e filtros do Pub/Sub, consulte Notificações de HL7v2 e Visualizar notificações de HL7v2.

Como editar um armazenamento HL7v2

Os exemplos a seguir mostram como editar a lista de tópicos e filtros do Pub/Sub que a API Cloud Healthcare usa para enviar notificações de alterações no armazenamento HL7v2.

Vários exemplos também mostram como editar os rótulos no armazenamento HL7v2.

Ao especificar um tópico do Pub/Sub, insira o URI qualificado para o tópico, conforme mostrado no exemplo a seguir:
projects/PROJECT_ID/topics/PUBSUB_TOPIC
Para que as notificações funcionem, você precisa conceder permissões adicionais para a conta de serviço do Agente de serviço do Cloud Healthcare. Para mais informações, consulte Permissões do Pub/Sub para armazenamento DICOM, FHIR e HL7v2.

Console

Para editar um armazenamento HL7v2, conclua as seguintes etapas:

  1. No console do Google Cloud, acesse a página Conjuntos de dados.

    Acessar conjuntos de dados

  2. Selecione o conjunto de dados que contém o armazenamento HL7v2 que você quer editar.
  3. Na lista Armazenamento de dados, clique no armazenamento de dados que você quer editar.
  4. Para editar a configuração do armazenamento HL7v2, clique em Configuração do armazenamento HL7v2.

    Saiba mais sobre as opções de configuração do armazenamento HL7v2 em Como criar um armazenamento HL7v2.
  5. Se você quiser configurar um tópico do Pub/Sub para o armazenamento de dados, clique em Adicionar tópico do Pub/Sub e selecione o nome do tópico. Ao especificar um tópico do Pub/Sub, insira o URI qualificado para o tópico, conforme mostrado no exemplo a seguir:
    projects/PROJECT_ID/topics/PUBSUB_TOPIC
    
  6. Se você adicionou um tópico do Pub/Sub, clique em Concluído.
  7. Para adicionar um ou mais rótulos ao armazenamento, clique em Rótulos, em Adicionar rótulo e insira o rótulo de chave-valor. Para mais informações sobre rótulos de recursos, consulte Como usar rótulos de recursos.
  8. Clique em Salvar.

gcloud

A CLI gcloud não é compatível com essa ação. Em vez disso, use o console do Google Cloud, curl, o PowerShell ou sua linguagem preferida.

REST

Para editar um armazenamento HL7v2, use o método projects.locations.datasets.hl7V2Stores.patch.

Antes de executar as amostras a seguir, crie pelo menos um tópico do Pub/Sub no seu projeto.

Antes de usar os dados da solicitação, faça as substituições a seguir:

  • PROJECT_ID: o ID do seu projeto do Google Cloud;
  • LOCATION: o local do conjunto de dados;
  • DATASET_ID: o conjunto de dados pai do armazenamento HL7v2.
  • HL7V2_STORE_ID: o ID do armazenamento HL7v2.
  • PUBSUB_TOPIC1: um tópico do Pub/Sub em que as mensagens são publicadas quando um evento ocorre em um repositório de dados.
  • FILTER1: uma string usada para corresponder as mensagens publicadas no domínio PUBSUB_TOPIC1

    Consulte filter para conferir exemplos de valores de filtro válidos.

  • PUBSUB_TOPIC2: um tópico do Pub/Sub em que as mensagens são publicadas
  • FILTER2: uma string usada para corresponder as mensagens publicadas no domínio PUBSUB_TOPIC2
  • KEY1: a primeira chave de rótulo
  • VALUE1: o valor do primeiro rótulo
  • KEY2: a segunda chave de rótulo
  • VALUE2: o segundo valor de rótulo

Solicitar corpo JSON:

{
  'notificationConfigs': [
    {
      'pubsubTopic': 'projects/PROJECT_ID/topics/PUBSUB_TOPIC1',
      'filter' : 'FILTER1'
    },
    {
      'pubsubTopic': 'projects/PROJECT_ID/topics/PUBSUB_TOPIC2',
      'filter': 'FILTER2'
    },
  ],
  'labels': {
    'KEY1':'VALUE1',
    'KEY2':'VALUE2'
  }
}

Para enviar a solicitação, escolha uma destas opções:

curl

Salve o corpo da solicitação em um arquivo chamado request.json. Execute o comando a seguir no terminal para criar ou substituir esse arquivo no diretório atual:

cat > request.json << 'EOF'
{
  'notificationConfigs': [
    {
      'pubsubTopic': 'projects/PROJECT_ID/topics/PUBSUB_TOPIC1',
      'filter' : 'FILTER1'
    },
    {
      'pubsubTopic': 'projects/PROJECT_ID/topics/PUBSUB_TOPIC2',
      'filter': 'FILTER2'
    },
  ],
  'labels': {
    'KEY1':'VALUE1',
    'KEY2':'VALUE2'
  }
}
EOF

Depois execute o comando a seguir para enviar a solicitação 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/hl7V2Stores/HL7V2_STORE_ID?updateMask=notificationConfigs,labels"

PowerShell

Salve o corpo da solicitação em um arquivo chamado request.json. Execute o comando a seguir no terminal para criar ou substituir esse arquivo no diretório atual:

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

Depois execute o comando a seguir para enviar a solicitação 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/hl7V2Stores/HL7V2_STORE_ID?updateMask=notificationConfigs,labels" | Select-Object -Expand Content

APIs Explorer

Copie o corpo da solicitação e abra a página de referência do método. O painel "APIs Explorer" é aberto no lado direito da página. Interaja com essa ferramenta para enviar solicitações. Cole o corpo da solicitação nessa ferramenta, preencha todos os outros campos obrigatórios e clique em Executar.

Você receberá uma resposta JSON semelhante a esta:

Go

Ver no GitHub (em inglês) Feedback
import (
	"context"
	"fmt"
	"io"

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

// patchHL7V2Store updates (patches) a HL7V2 store by updating its Pub/sub topic name.
func patchHL7V2Store(w io.Writer, projectID, location, datasetID, hl7v2StoreID, 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.Hl7V2Stores

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

	if _, err := storesService.Patch(name, &healthcare.Hl7V2Store{
		NotificationConfigs: []*healthcare.Hl7V2NotificationConfig{
			{
				PubsubTopic: topicName, // format is "projects/*/locations/*/topics/*"
			},
		},
	}).UpdateMask("notificationConfigs").Do(); err != nil {
		return fmt.Errorf("Patch: %w", err)
	}

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

	return nil
}

Java

Ver no GitHub (em inglês) Feedback
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.Hl7V2Stores;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.Hl7V2NotificationConfig;
import com.google.api.services.healthcare.v1.model.Hl7V2Store;
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 Hl7v2StorePatch {
  private static final String HL7v2_NAME = "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void patchHl7v2Store(String hl7v2StoreName, String pubsubTopic) throws IOException {
    // String hl7v2StoreName =
    //    String.format(
    //        HL7v2_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-hl7v2-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 HL7v2 store.
    Hl7V2Stores.Get getRequest =
        client.projects().locations().datasets().hl7V2Stores().get(hl7v2StoreName);
    Hl7V2Store store = getRequest.execute();

    Hl7V2NotificationConfig notificationConfig = new Hl7V2NotificationConfig();
    notificationConfig.setPubsubTopic(pubsubTopic);
    List<Hl7V2NotificationConfig> notificationConfigs = new ArrayList<Hl7V2NotificationConfig>();
    notificationConfigs.add(notificationConfig);
    // Update the Hl7v2Store fields as needed as needed. For a full list of Hl7v2Store fields, see:
    // https://cloud.google.com/healthcare/docs/reference/rest/v1/projects.locations.datasets.hl7V2Store#Hl7v2Store
    store.setNotificationConfigs(notificationConfigs);

    // Create request and configure any parameters.
    Hl7V2Stores.Patch request =
        client
            .projects()
            .locations()
            .datasets()
            .hl7V2Stores()
            .patch(hl7v2StoreName, store)
            .setUpdateMask("notificationConfigs");

    // Execute the request and process the results.
    store = request.execute();
    System.out.println("HL7v2 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

Ver no GitHub (em inglês) Feedback
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 patchHl7v2Store = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  // const pubsubTopic = 'my-topic'
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}`;
  const request = {
    name,
    updateMask: 'notificationConfigs',
    resource: {
      notificationConfigs: [
        {
          pubsubTopic: `projects/${projectId}/topics/${pubsubTopic}`,
        },
      ],
    },
  };

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

patchHl7v2Store();

Python

Ver no GitHub (em inglês) Feedback
def patch_hl7v2_store(project_id, location, dataset_id, hl7v2_store_id):
    """Updates the HL7v2 store.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/hl7v2
    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 HL7v2 store's parent dataset
    # hl7v2_store_id = 'my-hl7v2-store'  # replace with the HL7v2 store's ID
    hl7v2_store_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )
    hl7v2_store_name = f"{hl7v2_store_parent}/hl7V2Stores/{hl7v2_store_id}"

    # TODO(developer): Replace with the full URI of an existing Pub/Sub topic
    patch = {"notificationConfigs": None}

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

    response = request.execute()
    print(f"Patched HL7v2 store {hl7v2_store_id} with Cloud Pub/Sub topic: None")
    return response

Como conseguir detalhes da loja HL7v2

Os exemplos a seguir mostram como conseguir detalhes sobre uma loja HL7v2.

Console

Para visualizar os detalhes de um armazenamento HL7v2:

  1. No console do Google Cloud, acesse a página Conjuntos de dados.

    Acessar conjuntos de dados

  2. Selecione o conjunto de dados que contém o armazenamento HL7v2 que você quer visualizar.
  3. Clique no nome do armazenamento HL7v2.
  4. A página Detalhes do Datastore exibe os detalhes de um armazenamento HL7v2 selecionado.

gcloud

Para acessar detalhes sobre um armazenamento HL7v2, execute o comando gcloud healthcare hl7v2-stores describe.

Antes de usar os dados do comando abaixo, faça estas substituições:

  • LOCATION: o local do conjunto de dados;
  • DATASET_ID: o conjunto de dados pai do armazenamento HL7v2.
  • HL7V2_STORE_ID: o ID do armazenamento HL7v2.

Execute o seguinte comando:

Linux, macOS ou Cloud Shell

gcloud healthcare hl7v2-stores describe HL7V2_STORE_ID \
  --dataset=DATASET_ID \
  --location=LOCATION

Windows (PowerShell)

gcloud healthcare hl7v2-stores describe HL7V2_STORE_ID `
  --dataset=DATASET_ID `
  --location=LOCATION

Windows (cmd.exe)

gcloud healthcare hl7v2-stores describe HL7V2_STORE_ID ^
  --dataset=DATASET_ID ^
  --location=LOCATION

Você vai receber uma resposta semelhante à seguinte.

Se você tiver configurado algum campo no recurso Hl7V2Store, ele também aparecerá na resposta.

...
name: projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID
...

REST

Para ver detalhes sobre um armazenamento HL7v2, use o método projects.locations.datasets.hl7V2Stores.get.

Antes de usar os dados da solicitação, faça as substituições a seguir:

  • PROJECT_ID: o ID do seu projeto do Google Cloud;
  • LOCATION: o local do conjunto de dados;
  • DATASET_ID: o conjunto de dados pai do armazenamento HL7v2.
  • HL7V2_STORE_ID: o ID do armazenamento HL7v2.

Para enviar a solicitação, escolha uma destas opções:

curl

execute o seguinte comando:

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

PowerShell

execute o seguinte comando:

$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/hl7V2Stores/HL7V2_STORE_ID" | Select-Object -Expand Content

APIs Explorer

Abra a página de referência do método. O painel APIs Explorer é aberto no lado direito da página. Interaja com essa ferramenta para enviar solicitações. Preencha todos os campos obrigatórios e clique em Executar.

Você vai receber uma resposta semelhante à seguinte.

Se você tiver configurado algum campo no recurso Hl7V2Store, ele também aparecerá na resposta.

Go

Ver no GitHub (em inglês) Feedback
import (
	"context"
	"fmt"
	"io"

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

// getHL7V2Store gets an HL7V2 store.
func getHL7V2Store(w io.Writer, projectID, location, datasetID, hl7v2StoreID 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.Hl7V2Stores

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

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

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

Java

Ver no GitHub (em inglês) Feedback
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.Hl7V2Stores;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.Hl7V2Store;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

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

  public static void hl7v2eStoreGet(String hl7v2StoreName) throws IOException {
    // String hl7v2StoreName =
    //    String.format(
    //        HL7v2_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-hl7v2-id");

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

    // Create request and configure any parameters.
    Hl7V2Stores.Get request =
        client.projects().locations().datasets().hl7V2Stores().get(hl7v2StoreName);

    // Execute the request and process the results.
    Hl7V2Store store = request.execute();
    System.out.println("HL7v2 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

Ver no GitHub (em inglês) Feedback
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 getHl7v2Store = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}`;
  const request = {name};

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

getHl7v2Store();

Python

Ver no GitHub (em inglês) Feedback
def get_hl7v2_store(project_id, location, dataset_id, hl7v2_store_id):
    """Gets the specified HL7v2 store.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/hl7v2
    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 HL7v2 store's parent dataset
    # hl7v2_store_id = 'my-hl7v2-store'  # replace with the HL7v2 store's ID
    hl7v2_store_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )
    hl7v2_store_name = f"{hl7v2_store_parent}/hl7V2Stores/{hl7v2_store_id}"

    hl7v2_stores = client.projects().locations().datasets().hl7V2Stores()
    hl7v2_store = hl7v2_stores.get(name=hl7v2_store_name).execute()

    print("Name: {}".format(hl7v2_store.get("name")))
    if hl7v2_store.get("notificationConfigs") is not None:
        print("Notification configs:")
        for notification_config in hl7v2_store.get("notificationConfigs"):
            print(
                "\tPub/Sub topic: {}".format(notification_config.get("pubsubTopic")),
                "\tFilter: {}".format(notification_config.get("filter")),
            )

    return hl7v2_store

Como listar os armazenamentos HL7v2 em um conjunto de dados

Os exemplos a seguir mostram como listar os armazenamentos HL7v2 em um conjunto de dados.

Console

Para visualizar os armazenamentos de dados em um conjunto de dados:

  1. No console do Google Cloud, acesse a página Conjuntos de dados.

    Acessar conjuntos de dados

  2. Selecione o conjunto de dados que contém o repositório de dados que você quer visualizar.

gcloud

Para listar os armazenamentos de HL7v2 em um conjunto de dados, execute o comando gcloud healthcare hl7v2-stores list.

Antes de usar os dados do comando abaixo, faça estas substituições:

  • LOCATION: o local do conjunto de dados;
  • DATASET_ID: o conjunto de dados pai do armazenamento HL7v2.

Execute o seguinte comando:

Linux, macOS ou Cloud Shell

gcloud healthcare hl7v2-stores list --dataset=DATASET_ID \
  --location=LOCATION

Windows (PowerShell)

gcloud healthcare hl7v2-stores list --dataset=DATASET_ID `
  --location=LOCATION

Windows (cmd.exe)

gcloud healthcare hl7v2-stores list --dataset=DATASET_ID ^
  --location=LOCATION

Você vai receber uma resposta semelhante à seguinte.

Se você tiver configurado algum campo no recurso Hl7V2Store, ele também aparecerá na resposta.

ID              LOCATION     TOPIC
HL7V2_STORE_ID  LOCATION     projects/PROJECT_ID/topics/PUBSUB_TOPIC                                   PUBSUB_TOPIC
...

REST

Para listar os armazenamentos HL7v2 em um conjunto de dados, use o método projects.locations.datasets.hl7V2Stores.list.

Antes de usar os dados da solicitação, faça as substituições a seguir:

  • PROJECT_ID: o ID do seu projeto do Google Cloud;
  • LOCATION: o local do conjunto de dados;
  • DATASET_ID: o conjunto de dados pai do armazenamento HL7v2.

Para enviar a solicitação, escolha uma destas opções:

curl

execute o seguinte comando:

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

PowerShell

execute o seguinte comando:

$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/hl7V2Stores" | Select-Object -Expand Content

APIs Explorer

Abra a página de referência do método. O painel APIs Explorer é aberto no lado direito da página. Interaja com essa ferramenta para enviar solicitações. Preencha todos os campos obrigatórios e clique em Executar.

Você vai receber uma resposta semelhante à seguinte.

Se você tiver configurado algum campo no recurso Hl7V2Store, ele também aparecerá na resposta.

Go

Ver no GitHub (em inglês) Feedback
import (
	"context"
	"fmt"
	"io"

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

// listHL7V2Stores prints a list of HL7V2 stores to w.
func listHL7V2Stores(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.Hl7V2Stores

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

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

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

Java

Ver no GitHub (em inglês) Feedback
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.Hl7V2Stores;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.Hl7V2Store;
import com.google.api.services.healthcare.v1.model.ListHl7V2StoresResponse;
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 Hl7v2StoreList {
  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 hl7v2StoreList(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<Hl7V2Store> stores = new ArrayList<>();
    do {
      // Create request and configure any parameters.
      Hl7V2Stores.List request =
          client
              .projects()
              .locations()
              .datasets()
              .hl7V2Stores()
              .list(datasetName)
              .setPageSize(100) // Specify pageSize up to 1000
              .setPageToken(pageToken);

      // Execute response and collect results.
      ListHl7V2StoresResponse response = request.execute();
      stores.addAll(response.getHl7V2Stores());

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

    // Print results.
    System.out.printf("Retrieved %s HL7v2 stores: \n", stores.size());
    for (Hl7V2Store 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

Ver no GitHub (em inglês) Feedback
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 listHl7v2Stores = 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 hl7v2Stores =
    await healthcare.projects.locations.datasets.hl7V2Stores.list(request);
  console.log(hl7v2Stores.data);
};

listHl7v2Stores();

Python

Ver no GitHub (em inglês) Feedback
def list_hl7v2_stores(project_id, location, dataset_id):
    """Lists the HL7v2 stores in the given dataset.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/hl7v2
    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 HL7v2 store's parent dataset
    hl7v2_store_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )

    hl7v2_stores = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .list(parent=hl7v2_store_parent)
        .execute()
        .get("hl7V2Stores", [])
    )

    for hl7v2_store in hl7v2_stores:
        print("HL7v2 store:\nName: {}".format(hl7v2_store.get("name")))
        if hl7v2_store.get("notificationConfigs") is not None:
            print("Notification configs:")
            for notification_config in hl7v2_store.get("notificationConfigs"):
                print(
                    "\tPub/Sub topic: {}".format(
                        notification_config.get("pubsubTopic")
                    ),
                    "\tFilter: {}".format(notification_config.get("filter")),
                )
    return hl7v2_stores

Como excluir um armazenamento HL7v2

Os exemplos a seguir mostram como excluir um armazenamento HL7v2.

Console

Para excluir um repositório de dados:

  1. No console do Google Cloud, acesse a página Conjuntos de dados.

    Acessar conjuntos de dados

  2. Selecione o conjunto de dados que contém o armazenamento de dados que você quer excluir.
  3. Escolha Excluir na lista suspensa Ações para o armazenamento de dados que você quer excluir.
  4. Para confirmar, digite o nome do repositório de dados e clique em Excluir.

gcloud

Para excluir um armazenamento HL7v2, execute o comando gcloud healthcare hl7v2-stores delete.

Antes de usar os dados do comando abaixo, faça estas substituições:

  • LOCATION: o local do conjunto de dados;
  • DATASET_ID: o conjunto de dados pai do armazenamento HL7v2.
  • HL7V2_STORE_ID: o ID do armazenamento HL7v2.

Execute o seguinte comando:

Linux, macOS ou Cloud Shell

gcloud healthcare hl7v2-stores delete HL7V2_STORE_ID \
  --dataset=DATASET_ID \
  --location=LOCATION

Windows (PowerShell)

gcloud healthcare hl7v2-stores delete HL7V2_STORE_ID `
  --dataset=DATASET_ID `
  --location=LOCATION

Windows (cmd.exe)

gcloud healthcare hl7v2-stores delete HL7V2_STORE_ID ^
  --dataset=DATASET_ID ^
  --location=LOCATION
Para confirmar, digite Y. Você vai receber uma resposta semelhante à seguinte.
Deleted hl7v2Store [HL7V2_STORE_ID].

REST

Para excluir um armazenamento HL7v2, use o método projects.locations.datasets.hl7V2Stores.delete.

Antes de usar os dados da solicitação, faça as substituições a seguir:

  • PROJECT_ID: o ID do seu projeto do Google Cloud;
  • LOCATION: o local do conjunto de dados;
  • DATASET_ID: o conjunto de dados pai do armazenamento HL7v2.
  • HL7V2_STORE_ID: o ID do armazenamento HL7v2.

Para enviar a solicitação, escolha uma destas opções:

curl

execute o seguinte comando:

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

PowerShell

execute o seguinte comando:

$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/hl7V2Stores/HL7V2_STORE_ID" | Select-Object -Expand Content

APIs Explorer

Abra a página de referência do método. O painel APIs Explorer é aberto no lado direito da página. Interaja com essa ferramenta para enviar solicitações. Preencha todos os campos obrigatórios e clique em Executar.

Você vai receber uma resposta JSON semelhante a esta:

Go

Ver no GitHub (em inglês) Feedback
import (
	"context"
	"fmt"
	"io"

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

// deleteHL7V2Store deletes an HL7V2 store.
func deleteHL7V2Store(w io.Writer, projectID, location, datasetID, hl7V2StoreID 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.Hl7V2Stores

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

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

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

Java

Ver no GitHub (em inglês) Feedback
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.Hl7V2Stores;
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 Hl7v2StoreDelete {
  private static final String HL7v2_NAME = "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void hl7v2StoreDelete(String hl7v2StoreName) throws IOException {
    // String hl7v2StoreName =
    //    String.format(
    //        HL7v2_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-hl7v2-id");

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

    // Create request and configure any parameters.
    Hl7V2Stores.Delete request =
        client.projects().locations().datasets().hl7V2Stores().delete(hl7v2StoreName);

    // Execute the request and process the results.
    request.execute();
    System.out.println("HL7v2 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

Ver no GitHub (em inglês) Feedback
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 deleteHl7v2Store = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}`;
  const request = {name};

  await healthcare.projects.locations.datasets.hl7V2Stores.delete(request);
  console.log(`Deleted HL7v2 store: ${hl7v2StoreId}`);
};

deleteHl7v2Store();

Python

Ver no GitHub (em inglês) Feedback
def delete_hl7v2_store(project_id, location, dataset_id, hl7v2_store_id):
    """Deletes the specified HL7v2 store.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/hl7v2
    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 HL7v2 store's parent dataset
    # hl7v2_store_id = 'my-hl7v2-store'  # replace with the HL7v2 store's ID
    hl7v2_store_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )
    hl7v2_store_name = f"{hl7v2_store_parent}/hl7V2Stores/{hl7v2_store_id}"

    request = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .delete(name=hl7v2_store_name)
    )

    response = request.execute()
    print(f"Deleted HL7v2 store: {hl7v2_store_id}")
    return response

A seguir