Como criar e gerenciar mensagens HL7v2

Esta página explica como ingerir, criar, marcar, listar, visualizar e excluir mensagens HL7v2. As mensagens HL7v2 são usadas para transmitir dados clínicos entre sistemas. Uma mensagem HL7v2 pode conter informações sobre um resultado de observação, uma receita médica para enviar a uma farmácia, uma transação financeira ou outros eventos clínicos.

Visão geral da criação e da ingestão de mensagens HL7v2

Use um dos seguintes métodos para armazenar uma mensagem HL7v2 na API Cloud Healthcare:

Quando você usa messages.ingest, o método gera uma resposta contendo uma das seguintes opções:

  • Uma mensagem de confirmação HL7v2 (ACK) quando bem-sucedida
  • Uma mensagem de confirmação negativa (NACK) quando há um erro

As mensagens ACK e NACK são usadas para responder aos sistemas de interface HL7v2 que esperam essas confirmações.

Ingestão e criação de mensagens com um adaptador MLLP

As mensagens HL7v2 são entregues entre os sistemas de saúde e a API Cloud Healthcare usando o protocolo mínimo de camada inferior (MLLP, na sigla em inglês). Para mais informações, consulte MLLP e o adaptador MLLP do Google Cloud Platform. Para instruções sobre como configurar um adaptador MLLP para se comunicar com segurança com a API Cloud Healthcare, consulte Como transmitir mensagens HL7v2 por conexões TCP/IP.

Como processar mensagens HL7v2

Depois que a API Cloud Healthcare ingerir a mensagem de um sistema de assistência, a API Cloud Healthcare gerará uma resposta que contém um campo hl7ack, que contém uma mensagem HL7v2 codificada em base64 com as seguintes características:

  • O tipo de mensagem é ACK.
  • As instalações de envio e de recebimento são revertidas, e o aplicativo de envio e o aplicativo de recebimento são revertidos.
  • O horário de envio da mensagem é o horário atual e um novo ID de controle é gerado.
  • O valor do campo MSH-9.1 define o tipo de mensagem.
  • O valor do campo MSA.1 define um tipo de resposta. Um tipo de resposta AA indica Application Accept, o que significa que a mensagem foi validada e processada.
  • O valor MSA.2 contém o ID de controle da mensagem original.

Os exemplos a seguir mostram como processar uma mensagem HL7v2 usando o método projects.locations.datasets.hl7V2Stores.messages.ingest.

curl

Para ingerir uma mensagem HL7v2, faça uma solicitação POST e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • Uma Message

O exemplo a seguir mostra uma solicitação POST usando curl e um arquivo JSON de exemplo chamado hl7v2-sample.json.

curl -X POST \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     --data-binary @hl7v2-sample.json \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages:ingest"

O exemplo de resposta a seguir mostra o hl7Ack e os detalhes da mensagem.

{
  "hl7Ack": "TVNIfF5+XCZ8QXxBfEF8U0VORF9GQUNJTElUWXwyMDIwMDIxNDIxMjAwNXx8QUNLfDFmMmQ1MjQzLTFhOWEtNGE4My05ZmI5LWNlNTIzMTVmZjk2M3xUfDAuMA1NU0F8QUF8MjAxODAxMDEwMDAwMDA=",
  "message": {
    "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
    "data": "TVNIfF5+XCZ8QXxTRU5EX0ZBQ0lMSVRZfEF8QXwyMDE4MDEwMTAwMDAwMHx8VFlQRV5BfDIwMTgwMTAxMDAwMDAwfFR8MC4wfHx8QUF8fDAwfEFTQ0lJDUVWTnxBMDB8MjAxODAxMDEwNDAwMDANUElEfHwxNAExMTFeXl5eTVJOfDExMTExMTExXl5eXk1STn4xMTExMTExMTExXl5eXk9SR05NQlI=",
    "sendFacility": "SEND_FACILITY",
    "sendTime": "2018-01-01T00:00:00Z",
    "messageType": "TYPE",
    "createTime": "CREATE_TIME",
    "patientIds": [
      {
        "value": "14\u0001111",
        "type": "MRN"
      },
      {
        "value": "11111111",
        "type": "MRN"
      },
      {
        "value": "1111111111",
        "type": "ORGNMBR"
      }
    ]
  }
}

PowerShell

Para ingerir uma mensagem HL7v2, faça uma solicitação POST e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • Uma Message

O exemplo a seguir mostra uma solicitação POST com o uso do Windows PowerShell e um arquivo JSON de exemplo chamado hl7v2-sample.json.

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

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -InFile hl7v2-sample.json `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages:ingest" | Select-Object -Expand Content

O exemplo de resposta a seguir mostra o hl7Ack e os detalhes da mensagem.

{
  "hl7Ack": "TVNIfF5+XCZ8QXxBfEF8U0VORF9GQUNJTElUWXwyMDIwMDIxNDIxMjAwNXx8QUNLfDFmMmQ1MjQzLTFhOWEtNGE4My05ZmI5LWNlNTIzMTVmZjk2M3xUfDAuMA1NU0F8QUF8MjAxODAxMDEwMDAwMDA=",
  "message": {
    "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
    "data": "TVNIfF5+XCZ8QXxTRU5EX0ZBQ0lMSVRZfEF8QXwyMDE4MDEwMTAwMDAwMHx8VFlQRV5BfDIwMTgwMTAxMDAwMDAwfFR8MC4wfHx8QUF8fDAwfEFTQ0lJDUVWTnxBMDB8MjAxODAxMDEwNDAwMDANUElEfHwxNAExMTFeXl5eTVJOfDExMTExMTExXl5eXk1STn4xMTExMTExMTExXl5eXk9SR05NQlI=",
    "sendFacility": "SEND_FACILITY",
    "sendTime": "2018-01-01T00:00:00Z",
    "messageType": "TYPE",
    "createTime": "CREATE_TIME",
    "patientIds": [
      {
        "value": "14\u0001111",
        "type": "MRN"
      },
      {
        "value": "11111111",
        "type": "MRN"
      },
      {
        "value": "1111111111",
        "type": "ORGNMBR"
      }
    ]
  }
}

Go

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

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

// ingestHL7V2Message ingests an HL7V2 message.
func ingestHL7V2Message(w io.Writer, projectID, location, datasetID, hl7V2StoreID, messageFile string) error {
	ctx := context.Background()

	hl7v2message, err := ioutil.ReadFile(messageFile)
	if err != nil {
		return fmt.Errorf("ReadFile: %w", err)
	}

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

	messagesService := healthcareService.Projects.Locations.Datasets.Hl7V2Stores.Messages

	req := &healthcare.IngestMessageRequest{
		Message: &healthcare.Message{
			Data: base64.StdEncoding.EncodeToString(hl7v2message),
		},
	}
	parent := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s", projectID, location, datasetID, hl7V2StoreID)

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

	fmt.Fprintf(w, "Ingested HL7V2 message: %q\n", resp.Message.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.Hl7V2Stores.Messages;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.IngestMessageRequest;
import com.google.api.services.healthcare.v1.model.IngestMessageResponse;
import com.google.api.services.healthcare.v1.model.Message;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;

@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class HL7v2MessageIngest {
  private static final String HL7v2_NAME = "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s";
  private static final String MESSAGE_NAME =
      "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s/messages/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void hl7v2MessageIngest(String hl7v2StoreName, String filePath) 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();

    // Load the data from file and format it into an ingest request.
    List<String> lines = Files.readAllLines(Paths.get(filePath), Charset.defaultCharset());
    String data = String.join("\n", lines);
    Message message = new Message().setData(data);
    IngestMessageRequest ingestRequest = new IngestMessageRequest().setMessage(message);

    // Create request and configure any parameters.
    Messages.Ingest request =
        client
            .projects()
            .locations()
            .datasets()
            .hl7V2Stores()
            .messages()
            .ingest(hl7v2StoreName, ingestRequest);

    // Execute the request and process the results.
    IngestMessageResponse response = request.execute();
    System.out.println("HL7v2 message ingested: " + 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 fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);

const ingestHl7v2Message = 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 hl7v2MessageFile = 'hl7v2-message.json';
  const hl7v2Message = JSON.parse(await readFile(hl7v2MessageFile));

  const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}`;
  const request = {parent, resource: hl7v2Message};

  const response =
    await healthcare.projects.locations.datasets.hl7V2Stores.messages.ingest(
      request
    );
  const data = response.data.hl7Ack;
  const buff = new Buffer.from(data, 'base64');
  const hl7Ack = buff.toString('ascii');
  console.log('Ingested HL7v2 message with ACK:\n', hl7Ack);
};

ingestHl7v2Message();

Python

def ingest_hl7v2_message(
    project_id, location, dataset_id, hl7v2_store_id, hl7v2_message_file
):
    """Ingests a new HL7v2 message from the hospital and sends a notification
    to the Cloud Pub/Sub topic. Return is an HL7v2 ACK message if the message
    was successfully stored.

    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

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

    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_message_file = 'hl7v2-message.json'  # replace with the path to the HL7v2 file
    hl7v2_parent = f"projects/{project_id}/locations/{location}"
    hl7v2_store_name = "{}/datasets/{}/hl7V2Stores/{}".format(
        hl7v2_parent, dataset_id, hl7v2_store_id
    )

    with open(hl7v2_message_file) as hl7v2_message:
        hl7v2_message_content = json.load(hl7v2_message)

    request = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .messages()
        .ingest(parent=hl7v2_store_name, body=hl7v2_message_content)
    )

    response = request.execute()
    print(f"Ingested HL7v2 message from file: {hl7v2_message_file}")
    return response

Como criar mensagens HL7v2

Os exemplos a seguir mostram como criar uma mensagem HL7v2 usando o método projects.locations.datasets.hl7V2Stores.messages.create.

REST

Para criar uma mensagem de HL7v2, use o método projects.locations.datasets.hl7V2Stores.messages.create.

Se você precisar de um arquivo de mensagens HL7v2 para usar com os comandos de amostra, faça o download do arquivo JSON hl7v2-sample.json.

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.
  • HL7V2_MESSAGE_FILE: o caminho para um arquivo formatado em JSON que contém uma mensagem HL7v2 na máquina local.

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

curl

execute o seguinte comando:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
--data-binary @HL7V2_MESSAGE_FILE \
"https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages"

PowerShell

execute o seguinte comando:

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-InFile HL7V2_MESSAGE_FILE `
-Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages" | 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.

A seguinte saída é retornada ao criar uma mensagem usando o arquivo JSON hl7v2-sample.json:

Go

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

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

// createHL7V2Message creates an HL7V2 message.
func createHL7V2Message(w io.Writer, projectID, location, datasetID, hl7V2StoreID, messageFile string) error {
	ctx := context.Background()

	hl7v2message, err := ioutil.ReadFile(messageFile)
	if err != nil {
		return fmt.Errorf("ReadFile: %w", err)
	}

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

	messagesService := healthcareService.Projects.Locations.Datasets.Hl7V2Stores.Messages

	req := &healthcare.CreateMessageRequest{
		Message: &healthcare.Message{
			Data: base64.StdEncoding.EncodeToString(hl7v2message),
		},
	}
	parent := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s", projectID, location, datasetID, hl7V2StoreID)
	resp, err := messagesService.Create(parent, req).Do()
	if err != nil {
		return fmt.Errorf("Create: %w", err)
	}

	fmt.Fprintf(w, "Created HL7V2 message: %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.Hl7V2Stores.Messages;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.CreateMessageRequest;
import com.google.api.services.healthcare.v1.model.Message;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;

@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class HL7v2MessageCreate {
  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 hl7v2MessageCreate(String hl7v2StoreName, String messageId, String filePath)
      throws IOException {
    // String hl7v2StoreName =
    //    String.format(
    //        HL7v2_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-hl7v2-id");
    // String messageId = "your-message-id";
    // String filePath = "path/to/file.txt";

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

    // Load the data from file representing the message.
    List<String> lines = Files.readAllLines(Paths.get(filePath), Charset.defaultCharset());
    String data = String.join("\n", lines);
    Message message = new Message().setData(data).setName(messageId);
    CreateMessageRequest createRequest = new CreateMessageRequest().setMessage(message);

    // Create request and configure any parameters.
    Messages.Create request =
        client
            .projects()
            .locations()
            .datasets()
            .hl7V2Stores()
            .messages()
            .create(hl7v2StoreName, createRequest);

    // Execute the request and process the results.
    Message response = request.execute();
    System.out.println("HL7v2 message 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 fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);

const createHl7v2Message = 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 hl7v2MessageFile = 'hl7v2-message.json';
  const hl7v2Message = JSON.parse(await readFile(hl7v2MessageFile));

  const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}`;
  const request = {parent, resource: hl7v2Message};

  const response =
    await healthcare.projects.locations.datasets.hl7V2Stores.messages.create(
      request
    );
  const {data} = response;
  console.log('Created HL7v2 message with data:\n', data);
};

createHl7v2Message();

Python

def create_hl7v2_message(
    project_id, location, dataset_id, hl7v2_store_id, hl7v2_message_file
):
    """Creates an HL7v2 message and sends a notification to the
    Cloud Pub/Sub topic.

    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

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

    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_message_file = 'hl7v2-message.json'  # replace with the path to the HL7v2 file
    hl7v2_parent = f"projects/{project_id}/locations/{location}"
    hl7v2_store_name = "{}/datasets/{}/hl7V2Stores/{}".format(
        hl7v2_parent, dataset_id, hl7v2_store_id
    )

    with open(hl7v2_message_file) as hl7v2_message:
        hl7v2_message_content = json.load(hl7v2_message)

    request = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .messages()
        .create(parent=hl7v2_store_name, body=hl7v2_message_content)
    )

    response = request.execute()
    print(f"Created HL7v2 message from file: {hl7v2_message_file}")
    return response

Separadores de segmento de mensagem HL7v2 e codificação

O separador de segmento padrão em HL7v2 é um retorno de carro (\r). A maioria dos editores de texto usa caracteres de nova linha (\n) como separadores de segmentos. Isso produz mensagens HL7v2 que não podem ser ingeridas na API Cloud Healthcare usando a configuração padrão. Para permitir que um armazenamento HL7v2 processe mensagens que usam caracteres de nova linha como separadores de segmentos, consulte Como configurar o terminador de segmentos.

Para converter os caracteres de nova linha em um arquivo em retornos de carro, execute o seguinte comando em um shell do Linux:

sed -z 's/\n/\r/g' INPUT_FILENAME > OUTPUT_FILENAME

Os métodos de ingestão e criação esperam que as mensagens HL7v2 sejam strings codificadas em base64. Para converter uma string em codificação base64, execute o seguinte comando em um shell do Linux:

openssl base64 -A -in ./INPUT_FILENAME -out ./OUTPUT_FILENAME

Como configurar o terminador de segmento

Ao criar ou processar dados, o formato de mensagem HL7v2 exige que os segmentos sejam encerrados usando o caractere de retorno \r. É possível configurar um armazenamento HL7v2 para aceitar mensagens HL7v2 com um terminador não padrão, como \n.

Considere a seguinte mensagem HL7v2 que usa o \r padrão como o terminador de segmento. Essa mensagem é aceita por padrão quando você cria um armazenamento HL7v2.

MSH|^~\\&|FROM_APP|FROM_FACILITY|TO_APP|TO_FACILITY|20150503223000||ADT^A01|20150503223000|P|2.5|\r
EVN|A01|20110613083617|\r
PID|1||21004053^^^^MRN||SULLY^BRIAN||19611209|M|||123 MAIN ST^^MOUNTAIN SPRINGS^CO^80439|\r
PV1||I|H73 RM1^1^^HIGHWAY 73 CLINIC||||5148^MARY QUINN|||||||||Y||||||||||||||||||||||||||||20150503223000|\r

A mensagem a seguir é idêntica à anterior, exceto pelo fato de usar \n como o terminador de segmento:

MSH|^~\\&|FROM_APP|FROM_FACILITY|TO_APP|TO_FACILITY|20150503223000||ADT^A01|20150503223000|P|2.5|\n
EVN|A01|20110613083617|\n
PID|1||21004053^^^^MRN||SULLY^BRIAN||19611209|M|||123 MAIN ST^^MOUNTAIN SPRINGS^CO^80439|\n
PV1||I|H73 RM1^1^^HIGHWAY 73 CLINIC||||5148^MARY QUINN|||||||||Y||||||||||||||||||||||||||||20150503223000|\n

Para armazenar a mensagem com o terminador não padrão, configure o objeto ParserConfig no armazenamento HL7v2 e defina o campo segmentTerminator como a codificação base64 de \n.

Os exemplos a seguir mostram como configurar segmentTerminator em ParserConfig ao criar um armazenamento HL7v2. Se você tiver um armazenamento HL7v2 existente, poderá editá-lo para fornecer o corpo ParserConfig. Depois de definir o terminador de segmento, você pode criar ou processar a mensagem.

curl

Para criar um armazenamento HL7v2 com o terminador de segmento definido como \n, faça uma solicitação POST e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • Um objeto parserConfig com o segmentTerminator definido como Cg== (a codificação base64 de \n)

O exemplo a seguir mostra uma solicitação POST usando curl.

curl -X POST \
    --data "{
      'parserConfig': {
        'segmentTerminator': 'Cg=='
      }
    }" \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores?hl7V2StoreId=HL7V2_STORE_ID"

Se a solicitação for bem-sucedida, o servidor retornará a resposta no formato JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID",
  "parserConfig": {
    "segmentTerminator": "Cg=="
  }
}

PowerShell

Para criar um armazenamento HL7v2 com o terminador de segmento definido como \n, faça uma solicitação POST e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • Um objeto parserConfig com o segmentTerminator definido como Cg== (a codificação base64 de \n)

O exemplo a seguir mostra uma solicitação POST feita com o Windows PowerShell.

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

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
      'parserConfig': {
        'segmentTerminator': 'Cg=='
      }
  } `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores?hl7V2StoreId=HL7V2_STORE_ID" | Select-Object -Expand Content

Se a solicitação for bem-sucedida, o servidor retornará a resposta no formato JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID",
  "parserConfig": {
    "segmentTerminator": "Cg=="
  }
}

Como usar um cabeçalho de segmento nulo

Uma mensagem HL7v2 sem um segmento de cabeçalho de mensagem (MSH) tem um cabeçalho de segmento nulo. Normalmente, uma mensagem HL7v2 contém um MSH que define metadados, como origem, intent, finalidade e destino da mensagem. O MSH permite pesquisar e filtrar mensagens. No entanto, é possível armazenar mensagens que não contenham um MSH configurando o objeto ParserConfig no armazenamento HL7v2 e definindo o campo allowNullHeader como true.

A mensagem de amostra a seguir contém um segmento de Identificação de pacientes (PID), mas nenhum MSH:

PID|1||21004053^^^^MRN||SULLY^BRIAN||19611209|M|||123 MAIN ST^^MOUNTAIN SPRINGS^CO^80439

Os exemplos a seguir mostram como configurar allowNullHeader em ParserConfig ao criar um armazenamento HL7v2. Se você tiver um armazenamento HL7v2 existente, poderá editá-lo e fornecer o corpo ParserConfig. Depois de definir allowNullHeader como true, você pode criar ou processar mensagens com cabeçalhos de segmento nulos.

curl

Para criar um armazenamento HL7v2 e armazenar mensagens que não contenham um MSH, faça uma solicitação POST e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • Um objeto parserConfig com allowNullHeader definido como true

O exemplo a seguir mostra uma solicitação POST usando curl.

curl -X POST \
    --data "{
      'parserConfig': {
        'allowNullHeader': true
      }
    }" \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores?hl7V2StoreId=HL7V2_STORE_ID"

Se a solicitação for bem-sucedida, o servidor retornará a resposta no formato JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID",
  "parserConfig": {
    "allowNullHeader": true
  }
}

PowerShell

Para criar um armazenamento HL7v2 e armazenar mensagens que não contenham um MSH, faça uma solicitação POST e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • Um objeto parserConfig com allowNullHeader definido como true

O exemplo a seguir mostra uma solicitação POST feita com o Windows PowerShell.

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

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
      'parserConfig': {
        'nullTerminator': true
      }
  } `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores?hl7V2StoreId=HL7V2_STORE_ID" | Select-Object -Expand Content

Se a solicitação for bem-sucedida, o servidor retornará a resposta no formato JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID",
  "parserConfig": {
    "allowNullHeader": true
  }
}

Como rotular uma mensagem HL7v2

Você pode adicionar um ou mais marcadores de valor-chave a uma mensagem. Um caso de uso de marcadores é adicionar marcadores de status a uma mensagem para que um aplicativo possa consultar mensagens por status.

Os exemplos a seguir mostram como adicionar marcadores a uma mensagem HL7v2 usando o método projects.locations.datasets.hl7V2Stores.messages.patch.

curl

Para adicionar marcadores a uma mensagem HL7v2, faça uma solicitação PATCH e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • O ID da mensagem
  • Os dados do rótulo a serem atualizados
  • Uma máscara de atualização

O exemplo a seguir mostra uma solicitação PATCH usando curl.

curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data "{
      'labels': {
        'KEY' : 'VALUE'
      }
    }" "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?updateMask=labels"

Se a solicitação for bem-sucedida, o servidor retornará a resposta no formato JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "DATA",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    }
  ],
  "labels": {
    "KEY": "VALUE"
  }
}

PowerShell

Para adicionar marcadores a uma mensagem HL7v2, faça uma solicitação PATCH e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • O ID da mensagem
  • Os dados do rótulo a serem atualizados
  • Uma máscara de atualização

O exemplo a seguir mostra uma solicitação PATCH feita com o Windows PowerShell.

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

Invoke-WebRequest `
  -Method Patch `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
      'labels': {
        'KEY': 'VALUE'
      }
  }" `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?updateMask=labels" | Select-Object -Expand Content

Se a solicitação for bem-sucedida, o servidor retornará a resposta no formato JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "DATA",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    }
  ],
  "labels": {
    "KEY": "VALUE"
  }
}

Go

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

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

// patchHL7V2Message patches an HL7V2 message.
func patchHL7V2Message(w io.Writer, projectID, location, datasetID, hl7V2StoreID, hl7V2MessageID, messageFile string) error {
	ctx := context.Background()

	hl7v2message, err := ioutil.ReadFile(messageFile)
	if err != nil {
		return fmt.Errorf("ReadFile: %w", err)
	}

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

	messagesService := healthcareService.Projects.Locations.Datasets.Hl7V2Stores.Messages

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s/messages/%s", projectID, location, datasetID, hl7V2StoreID, hl7V2MessageID)
	message := &healthcare.Message{
		Data:   base64.StdEncoding.EncodeToString(hl7v2message),
		Labels: map[string]string{"my-label": "true"},
	}

	call := messagesService.Patch(name, message)
	call.UpdateMask("labels")
	resp, err := call.Do()
	if err != nil {
		return fmt.Errorf("Patch: %w", err)
	}

	fmt.Fprintf(w, "Patched HL7V2 message: %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.Hl7V2Stores.Messages;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.Message;
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;

@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class HL7v2MessagePatch {
  private static final String MESSAGE_NAME =
      "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s/messages/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void hl7v2MessagePatch(String hl7v2MessageName) throws IOException {
    // String hl7v2MessageName =
    //    String.format(
    //        MESSAGE_NAME, "project-id", "region-id", "dataset-id", "hl7v2-id", "message-id");

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

    // Fetch the initial state of the message.
    Messages.Get getRequest =
        client.projects().locations().datasets().hl7V2Stores().messages().get(hl7v2MessageName);
    Message message = getRequest.execute();

    // Update the Message fields as needed as needed. For a full list of Message fields, see:
    // https://cloud.google.com/healthcare/docs/reference/rest/v1/projects.locations.datasets.hl7V2Stores.messages
    Map<String, String> labels = new HashMap<>();
    labels.put("key1", "value1");
    labels.put("key2", "value2");
    message.setLabels(labels);

    // Create request and configure any parameters.
    Messages.Patch request =
        client
            .projects()
            .locations()
            .datasets()
            .hl7V2Stores()
            .messages()
            .patch(hl7v2MessageName, message)
            .setUpdateMask("labels");

    // Execute the request and process the results.
    message = request.execute();
    System.out.println("HL7v2 message patched: \n" + message.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 patchHl7v2Message = async () => {
  // TODO(developer): uncomment the lines beginning with 'const' before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  // The value for hl7v2MessageId is the server-generated ID returned when you
  // created or ingested the HL7v2 message in an HL7v2 store.
  // const hl7v2MessageId = 'qCnewKno44gTt3oBn4dQ0u8ZA23ibDdV9GpifD2E=';
  // const labelKey = 'status';
  // const labelValue = 'processed';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}/messages/${hl7v2MessageId}`;
  const request = {
    name,
    updateMask: 'labels',
    resource: {
      labels: {
        labelKey: labelValue,
      },
    },
  };

  await healthcare.projects.locations.datasets.hl7V2Stores.messages.patch(
    request
  );
  console.log('Patched HL7v2 message');
};

patchHl7v2Message();

Python

def patch_hl7v2_message(
    project_id,
    location,
    dataset_id,
    hl7v2_store_id,
    hl7v2_message_id,
    label_key,
    label_value,
):
    """Updates the message.

    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_message_id = '2yqbdhYHlk_ucSmWkcKOVm_N0p0OpBXgIlVG18rB-cw='  # replace with the HL7v2 message ID that was returned by the server
    # label_key = 'key1'  # replace with a key
    # label_value = 'label2'  # replace with a key value
    hl7v2_message_parent = f"projects/{project_id}/locations/{location}"
    hl7v2_message_name = "{}/datasets/{}/hl7V2Stores/{}/messages/{}".format(
        hl7v2_message_parent, dataset_id, hl7v2_store_id, hl7v2_message_id
    )

    patch = {"labels": {label_key: label_value}}

    request = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .messages()
        .patch(name=hl7v2_message_name, updateMask="labels", body=patch)
    )

    response = request.execute()
    print(
        "Patched HL7v2 message {} with labels:\n\t{}: {}".format(
            hl7v2_message_id, label_key, label_value
        )
    )
    return response

Como receber o conteúdo da mensagem HL7v2

Os exemplos a seguir mostram como receber o conteúdo de uma mensagem HL7v2 usando o método projects.locations.datasets.hl7V2Stores.messages.get. Para determinar as partes da mensagem a serem recebidas, forneça ao parâmetro de consulta view uma das seguintes opções:

  • BASIC: inclua apenas o campo name.
  • RAW_ONLY: inclua todos os campos de mensagem, exceto o campo parsedData.
  • PARSED_ONLY: inclua todos os campos de mensagem, exceto o campo data.
  • FULL: inclua todos os campos da mensagem. Esse é o padrão.

Os exemplos a seguir mostram como receber o conteúdo de uma mensagem HL7v2 usando as visualizações FULL, RAW_ONLY e PARSED_ONLY.

Como usar a visualização FULL

Não é necessário definir explicitamente a visualização FULL, já que FULL é o valor padrão. No entanto, nas amostras curl e Windows PowerShell a seguir, a visualização FULL é adicionada como um parâmetro de consulta para integridade.

curl

Para receber o conteúdo de uma mensagem HL7v2 usando a visualização FULL, faça uma solicitação GET e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • O ID da mensagem
  • FULL como view

O exemplo a seguir mostra uma solicitação GET usando curl.

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

Se a solicitação for bem-sucedida, o servidor retornará a resposta no formato JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "DATA",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    },
    {
        "value": "VALUE_3",
        "type": "TYPE_3"
    }
  ],
  "parsedData": {
    "segments": [
      {
        ""segmentId": "SEGMENT_ID_1",
        "fields": {
          FIELDS_1
        }
      },
      {
        "segmentId": "SEGMENT_ID_2",
        "fields": {
          FIELDS_2
        }
      },
      {
        "segmentId": "SEGMENT_ID_3",
        "fields": {
          FIELDS_3
        }
      }
    ]
  }
}

PowerShell

Para receber o conteúdo de uma mensagem HL7v2 usando a visualização FULL, faça uma solicitação GET e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • O ID da mensagem
  • FULL como view

O exemplo a seguir mostra uma solicitação GET feita com o Windows PowerShell.

$cred = gcloud auth application-default 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/messages/MESSAGE_ID?view=FULL" | Select-Object -Expand Content

Se a solicitação for bem-sucedida, o servidor retornará a resposta no formato JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "DATA",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    },
    {
        "value": "VALUE_3",
        "type": "TYPE_3"
    }
  ],
  "parsedData": {
    "segments": [
      {
        ""segmentId": "SEGMENT_ID_1",
        "fields": {
          FIELDS_1
        }
      },
      {
        "segmentId": "SEGMENT_ID_2",
        "fields": {
          FIELDS_2
        }
      },
      {
        "segmentId": "SEGMENT_ID_3",
        "fields": {
          FIELDS_3
        }
      }
    ]
  }
}

Go

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

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

// getHL7V2Message gets an HL7V2 message.
func getHL7V2Message(w io.Writer, projectID, location, datasetID, hl7V2StoreID, hl7V2MessageID string) error {
	ctx := context.Background()

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

	messagesService := healthcareService.Projects.Locations.Datasets.Hl7V2Stores.Messages

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s/messages/%s", projectID, location, datasetID, hl7V2StoreID, hl7V2MessageID)
	message, err := messagesService.Get(name).Do()
	if err != nil {
		return fmt.Errorf("Get: %w", err)
	}

	rawData, err := base64.StdEncoding.DecodeString(message.Data)
	if err != nil {
		return fmt.Errorf("base64.DecodeString: %w", err)
	}

	fmt.Fprintf(w, "Got HL7V2 message.\n")
	fmt.Fprintf(w, "Raw length: %d.\n", len(rawData))
	fmt.Fprintf(w, "Parsed data:\n")
	parsedJSON, _ := json.MarshalIndent(message.ParsedData, "", "  ")
	fmt.Fprintf(w, "%s", parsedJSON)
	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.Hl7V2Stores.Messages;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.Message;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class HL7v2MessageGet {
  private static final String MESSAGE_NAME =
      "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s/messages/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void hl7v2MessageGet(String hl7v2MessageName) throws IOException {
    // String hl7v2MessageName =
    //    String.format(
    //        MESSAGE_NAME, "project-id", "region-id", "dataset-id", "hl7v2-id", "message-id");

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

    // Create request and configure any parameters.
    Messages.Get request =
        client.projects().locations().datasets().hl7V2Stores().messages().get(hl7v2MessageName);

    // Execute the request and process the results.
    Message store = request.execute();
    System.out.println("HL7v2 message 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 getHl7v2Message = async () => {
  // TODO(developer): uncomment the lines beginning with 'const' before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  // The value for hl7v2MessageId is the server-generated ID returned when you
  // created or ingested the HL7v2 message in an HL7v2 store.
  // const hl7v2MessageId = 'qCnewKno44gTt3oBn4dQ0u8ZA23ibDdV9GpifD2E=';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}/messages/${hl7v2MessageId}`;
  // Use the 'FULL' enum to include all of the message fields in the response.
  const view = 'FULL';
  const request = {name, view};

  const hl7v2Message =
    await healthcare.projects.locations.datasets.hl7V2Stores.messages.get(
      request
    );
  console.log('Got HL7v2 message:\n', hl7v2Message.data);
};

getHl7v2Message();

Python

def get_hl7v2_message(
    project_id, location, dataset_id, hl7v2_store_id, hl7v2_message_id
):
    """Gets an HL7v2 message.

    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_message_id = '2yqbdhYHlk_ucSmWkcKOVm_N0p0OpBXgIlVG18rB-cw='  # replace with the HL7v2 message ID that was returned by the server
    hl7v2_parent = f"projects/{project_id}/locations/{location}"
    hl7v2_message_name = "{}/datasets/{}/hl7V2Stores/{}/messages/{}".format(
        hl7v2_parent, dataset_id, hl7v2_store_id, hl7v2_message_id
    )

    msgs = client.projects().locations().datasets().hl7V2Stores().messages()
    message = msgs.get(name=hl7v2_message_name).execute()

    print("Name: {}".format(message.get("name")))
    print("Data: {}".format(message.get("data")))
    print("Creation time: {}".format(message.get("createTime")))
    print("Sending facility: {}".format(message.get("sendFacility")))
    print("Time sent: {}".format(message.get("sendTime")))
    print("Message type: {}".format(message.get("messageType")))
    print("Patient IDs:")
    patient_ids = message.get("patientIds")
    for patient_id in patient_ids:
        print("\tPatient value: {}".format(patient_id.get("value")))
        print("\tPatient type: {}".format(patient_id.get("type")))
    print("Labels: {}".format(message.get("labels")))

    print(message)
    return message

Como usar a visualização RAW_ONLY

Os exemplos a seguir mostram como receber o conteúdo de uma mensagem HL7v2 usando a visualização RAW_ONLY, que inclui todos os campos de mensagem, exceto parsedData.

curl

Para receber o conteúdo de uma mensagem HL7v2 usando a visualização RAW_ONLY, faça uma solicitação GET e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • O ID da mensagem
  • RAW_ONLY como visualização

O exemplo a seguir mostra uma solicitação GET usando curl.

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

Se a solicitação for bem-sucedida, o servidor retornará a resposta no formato JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "DATA",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    },
    {
        "value": "VALUE_3",
        "type": "TYPE_3"
    }
  ]
}

PowerShell

Para receber o conteúdo de uma mensagem HL7v2 usando a visualização RAW_ONLY, faça uma solicitação GET e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • O ID da mensagem
  • RAW_ONLY como visualização

O exemplo a seguir mostra uma solicitação GET feita com o Windows PowerShell.

$cred = gcloud auth application-default 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/messages/MESSAGE_ID?view=RAW_ONLY" | Select-Object -Expand Content

Se a solicitação for bem-sucedida, o servidor retornará a resposta no formato JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "DATA",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    },
    {
        "value": "VALUE_3",
        "type": "TYPE_3"
    }
  ]
}

Como usar a visualização PARSED_ONLY

Os exemplos a seguir mostram como receber o conteúdo de uma mensagem HL7v2 usando a visualização PARSED_ONLY, que inclui todos os campos de mensagem, exceto data.

curl

Para receber o conteúdo de uma mensagem HL7v2 usando a visualização PARSED_ONLY, faça uma solicitação GET e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • O ID da mensagem
  • PARSED_ONLY como visualização

O exemplo a seguir mostra uma solicitação GET usando curl.

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

Se a solicitação for bem-sucedida, o servidor retornará a resposta no formato JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    },
    {
        "value": "VALUE_3",
        "type": "TYPE_3"
    }
  ],
  "parsedData": {
    "segments": [
      {
        "segmentId": "SEGMENT_ID_1",
        "fields": {
          FIELDS_1
        }
      },
      {
        "segmentId": "SEGMENT_ID_2",
        "fields": {
          FIELDS_2
        }
      },
      {
        "segmentId": "SEGMENT_ID_3",
        "fields": {
          FIELDS_3
        }
      }
    ]
  }
}

PowerShell

Para receber o conteúdo de uma mensagem HL7v2 usando a visualização PARSED_ONLY, faça uma solicitação GET e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • O ID da mensagem
  • PARSED_ONLY como visualização

O exemplo a seguir mostra uma solicitação GET feita com o Windows PowerShell.

$cred = gcloud auth application-default 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/messages/MESSAGE_ID?view=PARSED_ONLY" | Select-Object -Expand Content

Se a solicitação for bem-sucedida, o servidor retornará a resposta no formato JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    },
    {
        "value": "VALUE_3",
        "type": "TYPE_3"
    }
  ],
  "parsedData": {
    "segments": [
      {
        "segmentId": "SEGMENT_ID_1",
        "fields": {
          FIELDS_1
        }
      },
      {
        "segmentId": "SEGMENT_ID_2",
        "fields": {
          FIELDS_2
        }
      },
      {
        "segmentId": "SEGMENT_ID_3",
        "fields": {
          FIELDS_3
        }
      }
    ]
  }
}

Como usar a visualização BASIC

Os exemplos a seguir mostram como receber o conteúdo de uma mensagem HL7v2 usando a visualização BASIC, que inclui apenas o campo name.

curl

Para receber o conteúdo de uma mensagem HL7v2 usando a visualização BASIC, faça uma solicitação GET e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • O ID da mensagem
  • BASIC como visualização

O exemplo a seguir mostra uma solicitação GET usando curl.

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

Se a solicitação for bem-sucedida, o servidor retornará a resposta no formato JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID"
}

PowerShell

Para receber o conteúdo de uma mensagem HL7v2 usando a visualização BASIC, faça uma solicitação GET e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • O ID da mensagem
  • BASIC como visualização

O exemplo a seguir mostra uma solicitação GET feita com o Windows PowerShell.

$cred = gcloud auth application-default 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/messages/MESSAGE_ID?view=BASIC" | Select-Object -Expand Content

Se a solicitação for bem-sucedida, o servidor retornará a resposta no formato JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID"
}

Como listar mensagens HL7v2

Os exemplos a seguir mostram como listar as mensagens em um armazenamento HL7v2 usando o método. Para determinar as informações sobre cada mensagem a ser incluída na lista, especifique o parâmetro de consulta view com uma das seguintes opções:

  • BASIC: inclua apenas o campo name. Esse é o padrão.
  • RAW_ONLY: inclua todos os campos de mensagem, exceto o campo parsedData.
  • PARSED_ONLY: inclua todos os campos de mensagem, exceto o campo data.
  • FULL: inclua todos os campos da mensagem.

curl

Para listar as mensagens em um armazenamento HL7v2, faça uma solicitação GET e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • O view, um de BASIC, RAW_ONLY, PARSED_ONLY ou FULL, ou omitir para usar o padrão de BASIC

O exemplo a seguir mostra uma solicitação GET usando curl. A solicitação especifica ?view=FULL para incluir todos os campos da mensagem.

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

Se a solicitação for bem-sucedida, o servidor retornará um código de status HTTP 200 OK e uma matriz de mensagens chamada hl7_v2_messages. O exemplo de resposta a seguir está truncado.

{
  "hl7_v2_messages": [
    {
      "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
      "data": "DATA",
      "sendFacility": "SEND_FACILITY",
      "sendTime": "SEND_TIME",
      "messageType": "MESSAGE_TYPE",
      "createTime": "CREATE_TIME",
      ...
    },
    ...
  ]
}

PowerShell

Para listar as mensagens em um armazenamento HL7v2, faça uma solicitação GET e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • O view, um de BASIC, RAW_ONLY, PARSED_ONLY ou FULL, ou omitir para usar o padrão de BASIC

O exemplo a seguir mostra uma solicitação GET feita com o Windows PowerShell. A solicitação especifica ?view=FULL para incluir todos os campos da mensagem.

$cred = gcloud auth application-default 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/messages?view=FULL" | Select-Object -Expand Content

Se a solicitação for bem-sucedida, o servidor retornará a resposta no formato JSON. A resposta da amostra está truncada.

{
  "hl7_v2_messages": [
    {
      "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
      "data": "DATA",
      "sendFacility": "SEND_FACILITY",
      "sendTime": "SEND_TIME",
      "messageType": "MESSAGE_TYPE",
      "createTime": "CREATE_TIME",
      ...
    },
    ...
  ]
}

Go

import (
	"context"
	"fmt"
	"io"

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

// listHL7V2Messages prints a list of HL7V2 messages to w.
func listHL7V2Messages(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)
	}

	messagesService := healthcareService.Projects.Locations.Datasets.Hl7V2Stores.Messages

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

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

	fmt.Fprintln(w, "HL7V2 messages:")
	for _, s := range resp.Hl7V2Messages {
		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.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.ListMessagesResponse;
import com.google.api.services.healthcare.v1.model.Message;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class HL7v2MessageList {
  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 hl7v2MessageList(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();

    // Results are paginated, so multiple queries may be required.
    String pageToken = null;

    do {
      // Create request and execute.
      ListMessagesResponse messageResponse =
          client
              .projects()
              .locations()
              .datasets()
              .hl7V2Stores()
              .messages()
              .list(hl7v2StoreName)
              .setPageSize(100)
              .setPageToken(pageToken)
              .execute();

      if (messageResponse.getHl7V2Messages() != null) {
        // Print results.
        System.out.printf(
            "Retrieved %s HL7v2 messages: \n", messageResponse.getHl7V2Messages().size());
        for (Message message : messageResponse.getHl7V2Messages()) {
          System.out.println(message);
        }
      }
      // Update the page token for the next request.
      pageToken = messageResponse.getNextPageToken();
    } while (pageToken != null);
  }

  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 listHl7v2Messages = 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}/hl7V2Stores/${hl7v2StoreId}`;
  const request = {parent};

  const response =
    await healthcare.projects.locations.datasets.hl7V2Stores.messages.list(
      request
    );
  const hl7v2Messages = response.data.hl7V2Messages;
  console.log(`HL7v2 messages: ${hl7v2Messages.length}`);
  for (const hl7v2Message of hl7v2Messages) {
    console.log(hl7v2Message);
  }
};

listHl7v2Messages();

Python

def list_hl7v2_messages(project_id, location, dataset_id, hl7v2_store_id):
    """Lists all the messages in the given HL7v2 store with support for
    filtering.

    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_messages_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )
    hl7v2_message_path = "{}/hl7V2Stores/{}".format(
        hl7v2_messages_parent, hl7v2_store_id
    )

    hl7v2_messages = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .messages()
        .list(parent=hl7v2_message_path)
        .execute()
        .get("hl7V2Messages", [])
    )

    for hl7v2_message in hl7v2_messages:
        print(hl7v2_message)

    return hl7v2_messages

Como excluir uma mensagem HL7v2

Os exemplos a seguir mostram como excluir uma mensagem HL7v2 usando o método projects.locations.datasets.hl7V2Stores.messages.delete.

curl

Para excluir uma mensagem HL7v2, faça uma solicitação DELETE e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • O código da mensagem HL7v2

O exemplo a seguir mostra uma solicitação DELETE usando curl.

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

Se a solicitação for bem-sucedida, o servidor retornará a resposta do corpo vazio no formato JSON:

{}

PowerShell

Para excluir uma mensagem HL7v2, faça uma solicitação DELETE e especifique as seguintes informações:

  • O nome e o local do conjunto de dados pai.
  • O nome do armazenamento HL7v2
  • O código da mensagem HL7v2

O exemplo a seguir mostra uma solicitação DELETE feita com o Windows PowerShell.

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

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

Se a solicitação for bem-sucedida, o servidor retornará o corpo de resposta vazio no formato JSON:

{}

Go

import (
	"context"
	"fmt"
	"io"

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

// deleteHL7V2Message deletes an HL7V2 message.
func deleteHL7V2Message(w io.Writer, projectID, location, datasetID, hl7V2StoreID, hl7V2MessageID string) error {
	ctx := context.Background()

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

	messagesService := healthcareService.Projects.Locations.Datasets.Hl7V2Stores.Messages

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s/messages/%s", projectID, location, datasetID, hl7V2StoreID, hl7V2MessageID)
	if _, err := messagesService.Delete(name).Do(); err != nil {
		return fmt.Errorf("Delete: %w", err)
	}

	fmt.Fprintf(w, "Deleted HL7V2 message: %q\n", 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.Hl7V2Stores.Messages;
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;

@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class HL7v2MessageDelete {
  private static final String MESSAGE_NAME =
      "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s/messages/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void hl7v2MessageDelete(String hl7v2MessageName) throws IOException {
    // String hl7v2MessageName =
    //    String.format(
    //        MESSAGE_NAME, "project-id", "region-id", "dataset-id", "hl7v2-id", "message-id");

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

    // Create request and configure any parameters.
    Messages.Delete request =
        client.projects().locations().datasets().hl7V2Stores().messages().delete(hl7v2MessageName);

    // Execute the request and process the results.
    request.execute();
    System.out.println("HL7v2 message 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 deleteHl7v2Message = async () => {
  // TODO(developer): uncomment the lines beginning with 'const' before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  // The value for hl7v2MessageId is the server-generated ID returned when you
  // created or ingested the HL7v2 message in an HL7v2 store.
  // const hl7v2MessageId = 'qCnewKno44gTt3oBn4dQ0u8ZA23ibDdV9GpifD2E=';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}/messages/${hl7v2MessageId}`;
  const request = {name};

  await healthcare.projects.locations.datasets.hl7V2Stores.messages.delete(
    request
  );
  console.log('Deleted HL7v2 message');
};

deleteHl7v2Message();

Python

def delete_hl7v2_message(
    project_id, location, dataset_id, hl7v2_store_id, hl7v2_message_id
):
    """Deletes an HL7v2 message.

    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_message_id = '2yqbdhYHlk_ucSmWkcKOVm_N0p0OpBXgIlVG18rB-cw='  # replace with the HL7v2 message ID that was returned by the server
    hl7v2_parent = f"projects/{project_id}/locations/{location}"
    hl7v2_message = "{}/datasets/{}/hl7V2Stores/{}/messages/{}".format(
        hl7v2_parent, dataset_id, hl7v2_store_id, hl7v2_message_id
    )

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

    response = request.execute()
    print(f"Deleted HL7v2 message with ID: {hl7v2_message_id}")
    return response

A seguir