Creating and managing HL7v2 messages

This page explains how to ingest, create, label, view, and delete HL7v2 messages.

Overview of creating and ingesting HL7v2 messages

A created message originates from Google Cloud Platform and is sent to a care system (such as a hospital). To create a message, use the messages.create method. In contrast, an ingested message comes from a care system and is ingested into GCP. To ingest a message, use the messages.ingest method.

When the Cloud Healthcare API ingests a message from a care system, the Cloud Healthcare API sends an acknowledgment message (ACK) to the remote care system and generates a response. This response contains an hl7Ack field and value, which verifies that the message was accepted. Note the following important information about the hl7ack field's value:

  • The value contains a response type. An AA response type indicates Application Accept, meaning that the message was validated and successfully ingested.
  • The sending facility and the receiving facility are reversed.
  • The value contains the original message's control ID.

After a message is created and sent to a care system, the Cloud Healthcare API expects the care system to return an ACK. Note that ACKs are not persisted in HL7v2 stores.

Message ingestion and creation with an MLLP adapter

See MLLP and the Google Cloud Platform MLLP adapter for information on the minimal lower layer protocol (MLLP), which is the protocol over which HL7v2 messages are delivered. If you are ingesting and creating HL7v2 messages, you will need to use an MLLP adapter to communicate with the Cloud Healthcare API.

A tutorial is provided that gives instructions on how to configure an MLLP adapter to communicate securely with the Cloud Healthcare API.

Ingesting and creating an HL7v2 message

The following samples show how to ingest an HL7v2 message and how to create one. For more information, see projects.locations.datasets.hl7V2Stores.messages.ingest for ingestion and projects.locations.datasets.hl7V2Stores.messages.create for creation.

curl command

To ingest an HL7v2 message, make a POST request and provide the name of the parent dataset, the name of the HL7v2 store, a message, and an access token. The following sample shows a POST request using curl and an example JSON file called hl7v2-sample.json.

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

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "hl7Ack": "TVNIfF5+XCZ8QXxBfEF8U0VORF9GQUNJTElUWXwyMDE4MDczMTIxMjUyM3x8QUNLfDIwMTgwNzMxMjEyNTIzfFR8MC4wDU1TQXxBQXwyMDE4MDEwMTAwMDAwMA==",
  "message": {
    "name": "projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
    "data": "TVNIfF5+XCZ8QXxTRU5EX0ZBQ0lMSVRZfEF8QXwyMDE4MDEwMTAwMDAwMHx8VFlQRV5BfDIwMTgwMTAxMDAwMDAwfFR8MC4wfHx8QUF8fDAwfEFTQ0lJDUVWTnxBMDB8MjAxODAxMDEwMDAwMDANUElEfHwxMTExMTFeXl5eTVJOfDExMTExMTExXl5eXk1STn4xMTExMTExMTExXl5eXk5IU05NQlINCg==",
    "sendFacility": "SEND_FACILITY",
    "sendTime": "SEND_TIME",
    "messageType": "TYPE",
    "createTime": "CREATE_TIME",
    "patientIds": [
      {
        "value": "111111",
        "type": "MRN"
      },
      {
        "value": "1111111111",
        "type": "HNMBR"
      }
    ]
  }
}

PowerShell

To ingest an HL7v2 message, make a POST request and provide the name of the parent dataset, the name of the HL7v2 store, a message, and an access token. The following sample shows a POST request using Windows PowerShell and an example JSON file called hl7v2-sample.json.

$cred = gcloud auth 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/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages:ingest" | Select-Object -Expand Content

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "hl7Ack": "TVNIfF5+XCZ8QXxBfEF8U0VORF9GQUNJTElUWXwyMDE4MDczMTIxMjUyM3x8QUNLfDIwMTgwNzMxMjEyNTIzfFR8MC4wDU1TQXxBQXwyMDE4MDEwMTAwMDAwMA==",
  "message": {
    "name": "projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
    "data": "TVNIfF5+XCZ8QXxTRU5EX0ZBQ0lMSVRZfEF8QXwyMDE4MDEwMTAwMDAwMHx8VFlQRV5BfDIwMTgwMTAxMDAwMDAwfFR8MC4wfHx8QUF8fDAwfEFTQ0lJDUVWTnxBMDB8MjAxODAxMDEwMDAwMDANUElEfHwxMTExMTFeXl5eTVJOfDExMTExMTExXl5eXk1STn4xMTExMTExMTExXl5eXk5IU05NQlINCg==",
    "sendFacility": "SEND_FACILITY",
    "sendTime": "SEND_TIME",
    "messageType": "TYPE",
    "createTime": "CREATE_TIME",
    "patientIds": [
      {
        "value": "111111",
        "type": "MRN"
      },
      {
        "value": "1111111111",
        "type": "HNMBR"
      }
    ]
  }
}

Go

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

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

// 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: %v", err)
	}

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", 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: %v", err)
	}

	fmt.Fprintf(w, "Ingested HL7V2 message: %q\n", resp.Message.Name)
	return nil
}

Java

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare.Projects.Locations.Datasets.Hl7V2Stores.Messages;
import com.google.api.services.healthcare.v1beta1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1beta1.model.IngestMessageRequest;
import com.google.api.services.healthcare.v1beta1.model.IngestMessageResponse;
import com.google.api.services.healthcare.v1beta1.model.Message;
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;

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 JacksonFactory();
  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
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          credential.initialize(request);
          request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
          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');
const healthcare = google.healthcare('v1beta1');
const fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);

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

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const 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(
        service_account_json,
        project_id,
        cloud_region,
        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.
    """
    client = get_client(service_account_json)
    hl7v2_parent = 'projects/{}/locations/{}'.format(project_id, cloud_region)
    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)

    try:
        response = request.execute()
        print('Ingested HL7v2 message from file: {}'.format(
            hl7v2_message_file))
        return response
    except HttpError as e:
        print('Error, HL7v2 message not ingested: {}'.format(e))
        return ""

The following samples show how to create an HL7v2 message.

curl command

To create an HL7v2 message, make a POST request and provide the name of the parent dataset, the name of the HL7v2 store, a message, and an access token. The following sample shows a POST request using curl and an example JSON file called hl7v2-sample.json.

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

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "name": "projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "TVNIfF5+XCZ8QXxTRU5EX0ZBQ0lMSVRZfEF8QXwyMDE4MDEwMTAwMDAwMHx8VFlQRV5BfDIwMTgwMTAxMDAwMDAwfFR8MC4wfHx8QUF8fDAwfEFTQ0lJDUVWTnxBMDB8MjAxODAxMDEwMDAwMDANUElEfHwxMTExMTFeXl5eTVJOfDExMTExMTExXl5eXk1STn4xMTExMTExMTExXl5eXk5IU05NQlINCg==",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "SEND_TIME",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
      "value": "111111",
      "type": "MRN"
    },
    {
      "value": "1111111111",
      "type": "HNMBR"
    }
  ]
}

PowerShell

To create an HL7v2 message, make a POST request and provide the name of the parent dataset, the name of the HL7v2 store, a message, and an access token. The following sample shows a POST request using Windows PowerShell and an example JSON file called hl7v2-sample.json.

$cred = gcloud auth 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/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages" | Select-Object -Expand Content

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "name": "projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "TVNIfF5+XCZ8QXxTRU5EX0ZBQ0lMSVRZfEF8QXwyMDE4MDEwMTAwMDAwMHx8VFlQRV5BfDIwMTgwMTAxMDAwMDAwfFR8MC4wfHx8QUF8fDAwfEFTQ0lJDUVWTnxBMDB8MjAxODAxMDEwMDAwMDANUElEfHwxMTExMTFeXl5eTVJOfDExMTExMTExXl5eXk1STn4xMTExMTExMTExXl5eXk5IU05NQlINCg==",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "SEND_TIME",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
      "value": "111111",
      "type": "MRN"
    },
    {
      "value": "1111111111",
      "type": "HNMBR"
    }
  ]
}

Go

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

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

// 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: %v", err)
	}

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", 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: %v", err)
	}

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

Java

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare.Projects.Locations.Datasets.Hl7V2Stores.Messages;
import com.google.api.services.healthcare.v1beta1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1beta1.model.CreateMessageRequest;
import com.google.api.services.healthcare.v1beta1.model.Message;
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;

public class HL7v2MessageCreate {
  private static final String HL7v2_NAME = "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  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
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          credential.initialize(request);
          request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
          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');
const healthcare = google.healthcare('v1beta1');
const fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);

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

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const 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(
        service_account_json,
        project_id,
        cloud_region,
        dataset_id,
        hl7v2_store_id,
        hl7v2_message_file):
    """Creates an HL7v2 message and sends a notification to the
    Cloud Pub/Sub topic.
    """
    client = get_client(service_account_json)
    hl7v2_parent = 'projects/{}/locations/{}'.format(project_id, cloud_region)
    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)

    try:
        response = request.execute()
        print('Created HL7v2 message from file: {}'.format(hl7v2_message_file))
        return response
    except HttpError as e:
        print('Error, HL7v2 message not created: {}'.format(e))
        return ""

Setting the segment terminator

The HL7v2 message format requires that segments be terminated using the return character, \r, but you can configure the HL7v2 store to accept HL7v2 messages with a non-standard terminator, such as \r\n.

Consider the following HL7v2 message, which uses the default \r as the segment terminator. This message will be accepted by default when you create an HL7v2 store.

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

The following message is identical to the message shown above, except that it uses \r\n as the segment terminator:

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

To store the message, configure the ParserConfig object in the HL7v2 store and set the segmentTerminator field to a base64-encoded version of \r\n. The following samples show how to configure segmentTerminator in ParserConfig when you create an HL7v2 store. If you have an existing HL7v2 store, you can edit it and provide the ParserConfig body. After setting the segment terminator, you can create or ingest the message as shown above.

curl command

To create an HL7v2 store and set the segment terminator to \r\n, make a POST request and provide the name of the parent dataset, the name of the HL7v2 store, a parserConfig object with the segmentTerminator set to DQo= (the base64-encoded version of \r\n), and an access token. The following sample shows a POST request using curl.

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

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "name": "projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID",
  "parserConfig": {
    "segmentTerminator": "DQo="
  }
}

PowerShell

To create an HL7v2 store and set the segment terminator to \r\n, make a POST request and provide the name of the parent dataset, the name of the HL7v2 store, a parserConfig object with the segmentTerminator set to DQo= (the base64-encoded version of \r\n), and an access token. The following sample shows a POST request using Windows PowerShell.

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

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

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "name": "projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID",
  "parserConfig": {
    "segmentTerminator": "DQo="
  }
}

Using a null segment header

Typically, an HL7v2 message will contain a message header segment (MSH) that defines the message's source, intent, purpose, destination, and other specifics of the message. The MSH is particularly useful for searching and filtering messages. However, you can store messages that do not contain an MSH by configuring the ParserConfig object in the HL7v2 store and setting the allowNullHeader field to true.

The folllowing sample message contains a Patient Identification (PID) segment, but no MSH:

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

The following samples show how to configure allowNullHeader in ParserConfig when you create an HL7v2 store. If you have an existing HL7v2 store, you can edit it and provide the ParserConfig body. After setting allowNullHeader to true, you can create or ingest the message as shown above.

curl command

To create an HL7v2 store and store messages that don't contain an MSH, make a POST request and provide the name of the parent dataset, the name of the HL7v2 store, a parserConfig object with allowNullHeader set to true, and an access token. The following sample shows a POST request using curl.

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

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

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

PowerShell

To create an HL7v2 store and store messages that don't contain an MSH, make a POST request and provide the name of the parent dataset, the name of the HL7v2 store, a parserConfig object with allowNullHeader set to true, and an access token. The following sample shows a POST request using Windows PowerShell.

$cred = gcloud auth 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/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores?hl7V2StoreId=HL7V2_STORE_ID" | Select-Object -Expand Content

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

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

Labeling an HL7v2 message

You can add one or more key-value labels to a message. One use case for this could be adding status labels to a message so that an application can query for messages with a specific status. For example, if you are doing batch processing (ETL), and you label some messages with Status: Processed and leave other messages without any label, you could then query for only the processed messages.

The following samples show how to add labels to an HL7v2 message. For more information, see projects.locations.datasets.hl7V2Stores.messages.patch.

curl command

To add labels to an HL7v2 message, make a PATCH request and provide the name of the parent dataset, the name of the HL7v2 store, the message ID, the label data to update, an update mask, and an access token. The following sample shows a PATCH request using curl.

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

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "name": "projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "TVNIfF5+XCZ8QXxTRU5EX0ZBQ0lMSVRZfEF8QXwyMDE4MDEwMTAwMDAwMHx8VFlQRV5BfDIwMTgwMTAxMDAwMDAwfFR8MC4wfHx8QUF8fDAwfEFTQ0lJDUVWTnxBMDB8MjAxODAxMDEwMDAwMDANUElEfHwxMTExMTFeXl5eTVJOfDExMTExMTExXl5eXk1STn4xMTExMTExMTExXl5eXk5IU05NQlINCg==",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "SEND_TIME",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
      "value": "111111",
      "type": "MRN"
    },
    {
      "value": "1111111111",
      "type": "HNMBR"
    }
  ],
  "labels": {
    "KEY": "VALUE"
  }
}

PowerShell

To add labels to an HL7v2 message, make a PATCH request and provide the name of the parent dataset, the name of the HL7v2 store, the message ID, the label data to update, an update mask, and an access token. The following sample shows a PATCH request using Windows PowerShell.

$cred = gcloud auth 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/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?updateMask=labels" | Select-Object -Expand Content

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "name": "projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "TVNIfF5+XCZ8QXxTRU5EX0ZBQ0lMSVRZfEF8QXwyMDE4MDEwMTAwMDAwMHx8VFlQRV5BfDIwMTgwMTAxMDAwMDAwfFR8MC4wfHx8QUF8fDAwfEFTQ0lJDUVWTnxBMDB8MjAxODAxMDEwMDAwMDANUElEfHwxMTExMTFeXl5eTVJOfDExMTExMTExXl5eXk1STn4xMTExMTExMTExXl5eXk5IU05NQlINCg==",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "SEND_TIME",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
      "value": "111111",
      "type": "MRN"
    },
    {
      "value": "1111111111",
      "type": "HNMBR"
    }
  ],
  "labels": {
    "KEY": "VALUE"
  }
}

Go

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

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

// 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: %v", err)
	}

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", 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: %v", err)
	}

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

Java

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare.Projects.Locations.Datasets.Hl7V2Stores.Messages;
import com.google.api.services.healthcare.v1beta1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1beta1.model.Message;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

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 JacksonFactory();
  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/v1beta1/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
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          credential.initialize(request);
          request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
          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');
const healthcare = google.healthcare('v1beta1');

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

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-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(
        service_account_json,
        project_id,
        cloud_region,
        dataset_id,
        hl7v2_store_id,
        hl7v2_message_id,
        label_key,
        label_value):
    """Updates the message."""
    client = get_client(service_account_json)
    hl7v2_message_parent = 'projects/{}/locations/{}'.format(
        project_id, cloud_region, dataset_id, hl7v2_store_id)
    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)

    try:
        response = request.execute()
        print(
            'Patched HL7v2 message {} with labels:\n\t{}: {}'.format(
                hl7v2_message_id,
                label_key,
                label_value))
        return response
    except HttpError as e:
        print('Error, HL7v2 message not patched: {}'.format(e))
        return ""

Getting HL7v2 message contents

The following samples show how to get the contents of an HL7v2 message. To determine what parts of the message to return, supply the view query parameter with one of the following options:

  • MESSAGE_VIEW_UNSPECIFIED: Not specified, equivalent to FULL.
  • RAW_ONLY: Server responses include all the message fields except parsedData field.
  • PARSED_ONLY: Server responses include all the message fields except data field.
  • FULL: (Default) Server responses include all the message fields.

The following samples show how to get the contents of an HL7v2 message using the FULL, RAW_ONLY, and PARSED_ONLY views.

For more information, see projects.locations.datasets.hl7V2Stores.messages.get.

Using the FULL view

You do not need to explicitly set the FULL view, as FULL is the default value. However, in the following curl and Windows PowerShell samples, the FULL view is added as a query parameter for completeness.

curl command

To get the contents of an HL7v2 message using the FULL view, make a GET request and provide the name of the parent dataset, the name of the HL7v2 store, the message ID, the view, and an access token. The following sample shows a GET request using curl.

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

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "name": "projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "TVNIfF5+XCZ8QXxTRU5EX0ZBQ0lMSVRZfEF8QXwyMDE4MDEwMTAwMDAwMHx8VFlQRV5BfDIwMTgwMTAxMDAwMDAwfFR8MC4wfHx8QUF8fDAwfEFTQ0lJDUVWTnxBMDB8MjAxODAxMDEwMDAwMDANUElEfHwxMTExMTFeXl5eTVJOfDExMTExMTExXl5eXk1STn4xMTExMTExMTExXl5eXk5IU05NQlINCg==",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "SEND_TIME",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
      "value": "14\u0001111",
      "type": "MRN"
    },
    {
      "value": "11111111",
      "type": "MRN"
    },
    {
      "value": "1111111111",
      "type": "ORGNMBR"
    }
  ],
  "parsedData": {
    "segments": [
      {
        "segmentId": "MSH",
        "fields": {
          "1": "^~\\&",
          "17": "ASCII",
          "10": "T",
          "5": "A",
          "16": "00",
          "9": "20180101000000",
          "0": "MSH",
          "6": "20180101000000",
          "3": "SEND_FACILITY",
          "4": "A",
          "8.2": "A",
          "11": "0.0",
          "8.1": "TYPE",
          "2": "A",
          "14": "AA"
        }
      },
      {
        "segmentId": "EVN",
        "fields": {
          "0": "EVN",
          "1": "A00",
          "2": "20180101040000"
        }
      },
      {
        "segmentId": "PID",
        "fields": {
          "2.1": "14\u0001111",
          "2.5": "MRN",
          "3[0].1": "11111111",
          "3[0].5": "MRN",
          "3[1].1": "1111111111",
          "3[1].5": "ORGNMBR",
          "0": "PID"
        }
      }
    ]
  }
}

PowerShell

To get the contents of an HL7v2 message using the FULL view, make a GET request and provide the name of the parent dataset, the name of the HL7v2 store, the message ID, the view, and an access token. The following sample shows a GET request using Windows PowerShell.

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

Invoke-WebRequest `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=FULL" | Select-Object -Expand Content

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "name": "projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "TVNIfF5+XCZ8QXxTRU5EX0ZBQ0lMSVRZfEF8QXwyMDE4MDEwMTAwMDAwMHx8VFlQRV5BfDIwMTgwMTAxMDAwMDAwfFR8MC4wfHx8QUF8fDAwfEFTQ0lJDUVWTnxBMDB8MjAxODAxMDEwMDAwMDANUElEfHwxMTExMTFeXl5eTVJOfDExMTExMTExXl5eXk1STn4xMTExMTExMTExXl5eXk5IU05NQlINCg==",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "SEND_TIME",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
      "value": "14\u0001111",
      "type": "MRN"
    },
    {
      "value": "11111111",
      "type": "MRN"
    },
    {
      "value": "1111111111",
      "type": "ORGNMBR"
    }
  ],
  "parsedData": {
    "segments": [
      {
        "segmentId": "MSH",
        "fields": {
          "1": "^~\\&",
          "17": "ASCII",
          "10": "T",
          "5": "A",
          "16": "00",
          "9": "20180101000000",
          "0": "MSH",
          "6": "20180101000000",
          "3": "SEND_FACILITY",
          "4": "A",
          "8.2": "A",
          "11": "0.0",
          "8.1": "TYPE",
          "2": "A",
          "14": "AA"
        }
      },
      {
        "segmentId": "EVN",
        "fields": {
          "0": "EVN",
          "1": "A00",
          "2": "20180101040000"
        }
      },
      {
        "segmentId": "PID",
        "fields": {
          "2.1": "14\u0001111",
          "2.5": "MRN",
          "3[0].1": "11111111",
          "3[0].5": "MRN",
          "3[1].1": "1111111111",
          "3[1].5": "ORGNMBR",
          "0": "PID"
        }
      }
    ]
  }
}

Go

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

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

// 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: %v", 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: %v", err)
	}

	rawData, err := base64.StdEncoding.DecodeString(message.Data)
	if err != nil {
		return fmt.Errorf("base64.DecodeString: %v", 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.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare.Projects.Locations.Datasets.Hl7V2Stores.Messages;
import com.google.api.services.healthcare.v1beta1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1beta1.model.Message;
import java.io.IOException;
import java.util.Collections;

public class HL7v2MessageGet {
  private static final String MESSAGE_NAME =
      "projects/%s/locations/%s/datasets/%s/hl7C2Store/%s/messages/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  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
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          credential.initialize(request);
          request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
          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');
const healthcare = google.healthcare('v1beta1');

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

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  // const hl7v2MessageId = 'qCnewKno44gTt3oBn4dQ0u8ZA23ibDdV9GpifD2E=';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}/messages/${hl7v2MessageId}`;
  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(
        service_account_json,
        project_id,
        cloud_region,
        dataset_id,
        hl7v2_store_id,
        hl7v2_message_id):
    """Gets an HL7v2 message."""
    client = get_client(service_account_json)
    hl7v2_parent = 'projects/{}/locations/{}'.format(project_id, cloud_region)
    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

Using the RAW_ONLY view

The following samples show how to get the contents of an HL7v2 message using the RAW_ONLY view, which includes all of the message fields except for parsedData.

curl command

To get the contents of an HL7v2 message using the RAW_ONLY view, make a GET request and provide the name of the parent dataset, the name of the HL7v2 store, the message ID, the view, and an access token. The following sample shows a GET request using curl.

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

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "name": "projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "TVNIfF5+XCZ8QXxTRU5EX0ZBQ0lMSVRZfEF8QXwyMDE4MDEwMTAwMDAwMHx8VFlQRV5BfDIwMTgwMTAxMDAwMDAwfFR8MC4wfHx8QUF8fDAwfEFTQ0lJDUVWTnxBMDB8MjAxODAxMDEwMDAwMDANUElEfHwxMTExMTFeXl5eTVJOfDExMTExMTExXl5eXk1STn4xMTExMTExMTExXl5eXk5IU05NQlINCg==",
  "sendTime": "SEND_TIME",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
      "value": "14\u0001111",
      "type": "MRN"
    },
    {
      "value": "11111111",
      "type": "MRN"
    },
    {
      "value": "1111111111",
      "type": "ORGNMBR"
    }
  ]
}

PowerShell

To get the contents of an HL7v2 message using the RAW_ONLY view, make a GET request and provide the name of the parent dataset, the name of the HL7v2 store, the message ID, the view, and an access token. The following sample shows a GET request using Windows PowerShell.

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

Invoke-WebRequest `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=RAW_ONLY" | Select-Object -Expand Content

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "name": "projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "TVNIfF5+XCZ8QXxTRU5EX0ZBQ0lMSVRZfEF8QXwyMDE4MDEwMTAwMDAwMHx8VFlQRV5BfDIwMTgwMTAxMDAwMDAwfFR8MC4wfHx8QUF8fDAwfEFTQ0lJDUVWTnxBMDB8MjAxODAxMDEwMDAwMDANUElEfHwxMTExMTFeXl5eTVJOfDExMTExMTExXl5eXk1STn4xMTExMTExMTExXl5eXk5IU05NQlINCg==",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "SEND_TIME",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
      "value": "14\u0001111",
      "type": "MRN"
    },
    {
      "value": "11111111",
      "type": "MRN"
    },
    {
      "value": "1111111111",
      "type": "ORGNMBR"
    }
  ]
}

Using the PARSED_ONLY view

The following samples show how to get the contents of an HL7v2 message using the PARSED_ONLY view, which includes all of the message fields except for data.

curl command

To get the contents of an HL7v2 message using the PARSED_ONLY view, make a GET request and provide the name of the parent dataset, the name of the HL7v2 store, the message ID, the view, and an access token. The following sample shows a GET request using curl.

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

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "name": "projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "SEND_TIME",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
      "value": "14\u0001111",
      "type": "MRN"
    },
    {
      "value": "11111111",
      "type": "MRN"
    },
    {
      "value": "1111111111",
      "type": "ORGNMBR"
    }
  ],
  "parsedData": {
    "segments": [
      {
        "segmentId": "MSH",
        "fields": {
          "6": "20180101000000",
          "14": "AA",
          "5": "A",
          "10": "T",
          "16": "00",
          "0": "MSH",
          "2": "A",
          "3": "SEND_FACILITY",
          "9": "20180101000000",
          "8.1": "TYPE",
          "17": "ASCII",
          "11": "0.0",
          "4": "A",
          "1": "^~\\&",
          "8.2": "A"
        }
      },
      {
        "segmentId": "EVN",
        "fields": {
          "0": "EVN",
          "1": "A00",
          "2": "20180101040000"
        }
      },
      {
        "segmentId": "PID",
        "fields": {
          "3[0].5": "MRN",
          "3[1].1": "1111111111",
          "3[1].5": "ORGNMBR",
          "0": "PID",
          "2.1": "14\u0001111",
          "2.5": "MRN",
          "3[0].1": "11111111"
        }
      }
    ]
  }
}

PowerShell

To get the contents of an HL7v2 message using the PARSED_ONLY view, make a GET request and provide the name of the parent dataset, the name of the HL7v2 store, the message ID, the view, and an access token. The following sample shows a GET request using Windows PowerShell.

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

Invoke-WebRequest `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=PARSED_ONLY" | Select-Object -Expand Content

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "name": "projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "SEND_TIME",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
      "value": "14\u0001111",
      "type": "MRN"
    },
    {
      "value": "11111111",
      "type": "MRN"
    },
    {
      "value": "1111111111",
      "type": "ORGNMBR"
    }
  ],
  "parsedData": {
    "segments": [
      {
        "segmentId": "MSH",
        "fields": {
          "6": "20180101000000",
          "14": "AA",
          "5": "A",
          "10": "T",
          "16": "00",
          "0": "MSH",
          "2": "A",
          "3": "SEND_FACILITY",
          "9": "20180101000000",
          "8.1": "TYPE",
          "17": "ASCII",
          "11": "0.0",
          "4": "A",
          "1": "^~\\&",
          "8.2": "A"
        }
      },
      {
        "segmentId": "EVN",
        "fields": {
          "0": "EVN",
          "1": "A00",
          "2": "20180101040000"
        }
      },
      {
        "segmentId": "PID",
        "fields": {
          "3[0].5": "MRN",
          "3[1].1": "1111111111",
          "3[1].5": "ORGNMBR",
          "0": "PID",
          "2.1": "14\u0001111",
          "2.5": "MRN",
          "3[0].1": "11111111"
        }
      }
    ]
  }
}

Listing HL7v2 messages

The following samples show how to list the messages in an HL7v2 store. For more information, see projects.locations.datasets.hl7V2Stores.messages.list.

curl command

To list the messages in an HL7v2 store, make a GET request and provide the name of the parent dataset, the name of the HL7v2 store, and an access token. The following sample shows a GET request using curl.

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

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "messages": [
    "projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID"
  ]
}

PowerShell

To list the messages in an HL7v2 store, make a GET request and provide the name of the parent dataset, the name of the HL7v2 store, and an access token. The following sample shows a GET request using Windows PowerShell.

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

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

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "messages": [
    "projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID"
  ]
}

Go

import (
	"context"
	"fmt"
	"io"

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

// 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: %v", 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("Create: %v", err)
	}

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

Java

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare.Projects.Locations.Datasets.Hl7V2Stores.Messages;
import com.google.api.services.healthcare.v1beta1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1beta1.model.ListMessagesResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HL7v2MessageList {
  private static final String HL7v2_NAME = "projects/%s/locations/%s/datasets/%s/hl7C2Store/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  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;
    List<String> messages = new ArrayList<>();

    do {
      // Create request and configure any parameters.
      Messages.List request =
          client
              .projects()
              .locations()
              .datasets()
              .hl7V2Stores()
              .messages()
              .list(hl7v2StoreName)
              .setPageSize(100) // Specify pageSize up to 1000
              .setPageToken(pageToken);

      // Execute response and collect results.
      ListMessagesResponse response = request.execute();
      messages.addAll(response.getMessages());

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

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

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

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          credential.initialize(request);
          request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
          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');
const healthcare = google.healthcare('v1beta1');

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

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const 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.messages;
  console.log(`HL7v2 messages: ${hl7v2Messages.length}`);
  for (const hl7v2Message of hl7v2Messages) {
    console.log(hl7v2Message);
  }
};

listHl7v2Messages();

Python

def list_hl7v2_messages(
        service_account_json,
        project_id,
        cloud_region,
        dataset_id,
        hl7v2_store_id):
    """Lists all the messages in the given HL7v2 store with support for
    filtering.
    """
    client = get_client(service_account_json)
    hl7v2_messages_parent = 'projects/{}/locations/{}/datasets/{}'.format(
        project_id, cloud_region, 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('messages', [])

    for hl7v2_message in hl7v2_messages:
        print(hl7v2_message)

    return hl7v2_messages

Deleting an HL7v2 message

The following samples show how to delete an HL7v2 message. For more information, see projects.locations.datasets.hl7V2Stores.messages.delete.

curl command

To delete an HL7v2 message, make a DELETE request and provide the name of the parent dataset, the HL7v2 message ID, and an access token. The following sample shows a DELETE request using curl.

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

If the request is successful, the server returns a 200 OK HTTP status code and the empty body response in JSON format:

200 OK
{}

PowerShell

To delete an HL7v2 message, make a DELETE request and provide the name of the parent dataset, the HL7v2 message ID, and an access token. The following sample shows a DELETE request using Windows PowerShell.

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

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

If the request is successful, the server returns a 200 OK HTTP status code and the empty response body in JSON format:

200 OK
{}

Go

import (
	"context"
	"fmt"
	"io"

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

// 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: %v", 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: %v", err)
	}

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

Java


import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare.Projects.Locations.Datasets.Hl7V2Stores.Messages;
import com.google.api.services.healthcare.v1beta1.CloudHealthcareScopes;
import java.io.IOException;
import java.util.Collections;

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 JacksonFactory();
  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
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          credential.initialize(request);
          request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
          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');
const healthcare = google.healthcare('v1beta1');

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

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-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(
        service_account_json,
        project_id,
        cloud_region,
        dataset_id,
        hl7v2_store_id,
        hl7v2_message_id):
    """Deletes an HL7v2 message."""
    client = get_client(service_account_json)
    hl7v2_parent = 'projects/{}/locations/{}'.format(project_id, cloud_region)
    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)

    try:
        response = request.execute()
        print('Deleted HL7v2 message with ID: {}'.format(hl7v2_message_id))
        return response
    except HttpError as e:
        print('Error, HL7v2 message not deleted: {}'.format(e))
        return ""

What's next

Hat Ihnen diese Seite weitergeholfen? Teilen Sie uns Ihr Feedback mit:

Feedback geben zu...

Cloud Healthcare API