hl7apy – Python HL7 v2 Library
Python library for parsing, creating, and manipulating HL7 v2.x messages. Supports HL7 versions 2.1 through 2.7, provides both high-level and low-level APIs for message construction, validation against HL7 schemas, and MLLP (Minimal Lower Layer Protocol) transport support.
Warnings
- gotcha HL7 messages use \r (carriage return) as the segment separator, not \n. Using \n will cause parse failures.
- gotcha Validation is strict by default. Setting a field to a value that doesn't match the HL7 datatype raises an exception.
- gotcha parse_message() expects the full message string including MSH segment. Passing a single segment string will raise InvalidEncodingChars or similar errors.
- gotcha Field/component access uses 1-based HL7 numbering (e.g., msh_9_1), but the MSH segment's field numbering starts at MSH-1 which is the field separator itself. MSH-3 is the sending application.
- deprecated The library has infrequent releases. Last major update was 1.3.4. Python 2 support was dropped but some legacy patterns remain in documentation.
- gotcha to_er7() returns the ER7-encoded string but does not add trailing segment separators. Concatenating multiple to_er7() outputs requires manual \r insertion.
Install
-
pip install hl7apy
Imports
- Message
from hl7apy.parser import parse_message
- Message (construction)
from hl7apy.core import Message
- Segment
from hl7apy.core import Segment
Quickstart
from hl7apy.core import Message
from hl7apy.parser import parse_message
# Create a new ADT^A01 message
m = Message('ADT_A01')
m.msh.msh_9.msh_9_1 = 'ADT'
m.msh.msh_9.msh_9_2 = 'A01'
m.msh.msh_10 = 'MSG00001'
m.msh.msh_11.msh_11_1 = 'P'
m.msh.msh_12 = '2.5'
print(m.to_er7())
# Parse an existing HL7 message
raw = 'MSH|^~\\&|SENDING|FACILITY|RECEIVING|FACILITY|20230101120000||ADT^A01|MSG00001|P|2.5\rPID|||12345||Doe^John'
parsed = parse_message(raw)
print(parsed.pid.pid_5.pid_5_1.value)