python-hl7 – HL7 v2.x Message Parser
A simple Python library for parsing HL7 v2.x messages. Provides segment, field, and component-level access to HL7 messages, along with MLLP (Minimal Lower Layer Protocol) client support. Does not handle HL7 FHIR (v4); it is strictly for the pipe-delimited v2.x wire format.
Warnings
- gotcha HL7 v2.x messages use \r (carriage return) as the segment separator, NOT \n. Messages with \n line endings will not parse correctly.
- breaking The synchronous MLLPClient class was removed in 0.4.0. MLLP functionality is now async-only using open_hl7_connection and start_hl7_server.
- gotcha This library only handles HL7 v2.x pipe-delimited messages. It does NOT support HL7 FHIR (v4 JSON/XML). Use fhir.resources or fhirclient for FHIR.
- gotcha Field indexing is 0-based on the segment object but MSH segment counts the field separator as MSH.1, so MSH[1] returns '|' and MSH[9] returns the message type. This 1-off confusion is common.
- gotcha Accessing a non-existent segment with message.segment('ZZZ') raises KeyError, not returning None.
Install
-
pip install hl7 -
pip install hl7[mllp]
Imports
- hl7.parse
import hl7 message = hl7.parse(raw_message_string)
- MLLPClient
from hl7.mllp import open_hl7_connection
Quickstart
import hl7
raw = 'MSH|^~\\&|SND|SND_FAC|RCV|RCV_FAC|20230101120000||ADT^A01|MSG00001|P|2.3\rPID|||12345^^^MRG||DOE^JOHN||19800101|M\r'
message = hl7.parse(raw)
# Access fields using segment(field) notation
print(message.segment('MSH')) # Full MSH segment
print(message['MSH.9']) # Message type: ADT^A01
print(message['PID.5']) # Patient name: DOE^JOHN
print(message.segment('PID')[5]) # Same: DOE^JOHN