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": "2018-01-01T00:00:00Z",
    "messageType": "TYPE",
    "createTime": "2018-01-01T00:00:00Z",
    "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": "2018-01-01T00:00:00Z",
    "messageType": "TYPE",
    "createTime": "2018-01-01T00:00:00Z",
    "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
}

Node.js

function ingestHl7v2Message(
  client,
  projectId,
  cloudRegion,
  datasetId,
  hl7v2StoreId,
  messageFile
) {
  // Client retrieved in callback
  // getClient(serviceAccountJson, function(cb) {...});
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  // const messageFile = './hl7-sample-ingest.json';
  const hl7v2MessageParent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}`;

  const hl7v2Message = fs.readFileSync(messageFile);
  const hl7v2MessageJson = JSON.parse(hl7v2Message);

  const request = {
    parent: hl7v2MessageParent,
    resource: hl7v2MessageJson,
  };

  client.projects.locations.datasets.hl7V2Stores.messages
    .ingest(request)
    .then(() => {
      console.log(`Ingested HL7v2 message`);
    })
    .catch(err => {
      console.error(err);
    });
}

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": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "1970-01-01T00:00:00Z",
  "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": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "1970-01-01T00:00:00Z",
  "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
}

Node.js

function createHl7v2Message(
  client,
  projectId,
  cloudRegion,
  datasetId,
  hl7v2StoreId,
  messageFile
) {
  // Client retrieved in callback
  // getClient(serviceAccountJson, function(cb) {...});
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  // const messageFile = './hl7-sample-ingest.json';
  const hl7v2MessageParent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}`;

  const hl7v2Message = fs.readFileSync(messageFile);
  const hl7v2MessageJson = JSON.parse(hl7v2Message);

  const request = {
    parent: hl7v2MessageParent,
    resource: hl7v2MessageJson,
  };

  client.projects.locations.datasets.hl7V2Stores.messages
    .create(request)
    .then(() => {
      console.log(`Created HL7v2 message`);
    })
    .catch(err => {
      console.error(err);
    });
}

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 ""

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": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "1970-01-01T00:00:00Z",
  "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": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "1970-01-01T00:00:00Z",
  "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
}

Node.js

function patchHl7v2Message(
  client,
  projectId,
  cloudRegion,
  datasetId,
  hl7v2StoreId,
  messageId,
  labelKey,
  labelValue
) {
  // Client retrieved in callback
  // getClient(serviceAccountJson, function(cb) {...});
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  // const messageId = 'E9_pxOBKhmlxiFxE4cg8zwJKUHMlOzIfeLBrZPf0Zg=';
  // const labelKey = 'my-key';
  // const labelValue = 'my-value';
  const hl7v2Message = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}/messages/${messageId}`;

  const request = {
    name: hl7v2Message,
    updateMask: 'labels',
    labels: {
      labelKey: labelValue,
    },
  };

  client.projects.locations.datasets.hl7V2Stores.messages
    .patch(request)
    .then(() => {
      console.log('Patched HL7v2 message');
    })
    .catch(err => {
      console.error(err);
    });
}

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. For more information, see projects.locations.datasets.hl7V2Stores.messages.get.

curl command

To get the contents of an HL7v2 message, make a GET request and provide the name of the parent dataset, the name of the HL7v2 store, the message ID, 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"

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": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "2018-07-31T21:25:23.650618Z",
  "patientIds": [
    {
      "value": "111111",
      "type": "MRN"
    },
    {
      "value": "1111111111",
      "type": "HNMBR"
    }
  ]
}

PowerShell

To get the contents of an HL7v2 message, make a GET request and provide the name of the parent dataset, the name of the HL7v2 store, the message ID, 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" | 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": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "2018-07-31T21:25:23.650618Z",
  "patientIds": [
    {
      "value": "111111",
      "type": "MRN"
    },
    {
      "value": "1111111111",
      "type": "HNMBR"
    }
  ]
}

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
}

Node.js

function getHl7v2Message(
  client,
  projectId,
  cloudRegion,
  datasetId,
  hl7v2StoreId,
  messageId
) {
  // Client retrieved in callback
  // getClient(serviceAccountJson, function(cb) {...});
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  // const messageId = 'E9_pxOBKhmlxiFxE4cg8zwJKUHMlOzIfeLBrZPf0Zg=';
  const hl7v2Message = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}/messages/${messageId}`;

  const request = {name: hl7v2Message};

  client.projects.locations.datasets.hl7V2Stores.messages
    .get(request)
    .then(results => {
      console.log('Got HL7v2 message:');
      console.log(JSON.stringify(results.data, null, 2));
    })
    .catch(err => {
      console.error(err);
    });
}

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

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
}

Node.js

function listHl7v2Messages(
  client,
  projectId,
  cloudRegion,
  datasetId,
  hl7v2StoreId
) {
  // Client retrieved in callback
  // getClient(serviceAccountJson, function(cb) {...});
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  const hl7v2StoreName = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}`;

  const request = {parent: hl7v2StoreName};

  client.projects.locations.datasets.hl7V2Stores.messages
    .list(request)
    .then(results => {
      console.log('HL7v2 messages:\n', results['data']['messages']);
    })
    .catch(err => {
      console.error(err);
    });
}

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
}

Node.js

function deleteHl7v2Message(
  client,
  projectId,
  cloudRegion,
  datasetId,
  hl7v2StoreId,
  messageId
) {
  // Client retrieved in callback
  // getClient(serviceAccountJson, function(cb) {...});
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  // const messageId = 'E9_pxOBKhmlxiFxE4cg8zwJKUHMlOzIfeLBrZPf0Zg=';
  const hl7v2Message = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}/messages/${messageId}`;

  const request = {name: hl7v2Message};

  client.projects.locations.datasets.hl7V2Stores.messages
    .delete(request)
    .then(() => {
      console.log(`Deleted HL7v2 message with ID ${messageId}`);
    })
    .catch(err => {
      console.error(err);
    });
}

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

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Healthcare API