What is HAPI?
HAPI (HL7 Application Programming Interface) is an open-source Java API for parsing and encoding HL7 V2 messages. It provides:
- Type-safe access to message components
- Automatic validation
- Version-specific implementations
- Utilities for message manipulation
Core Classes
Parser
The Parser class is responsible for converting between HL7 message strings and their Java object representations. HAPI provides two main parser implementations: PipeParser for traditional pipe-delimited messages (most common), and DefaultXMLParser for XML-encoded HL7 messages. When parsing incoming messages, the parser automatically detects the HL7 version and creates the appropriate message object.
import ca.uhn.hl7v2.parser.Parser;
import ca.uhn.hl7v2.parser.PipeParser;
import ca.uhn.hl7v2.parser.DefaultXMLParser;
Message
The Message interface is the base type for all HL7 messages in HAPI. Concrete message classes are organized in version-specific packages (e.g., ca.uhn.hl7v2.model.v25.message). Each message type like ADT_A01 or ORU_R01 has its own class with type-safe accessors for segments and groups. When you parse an incoming message, HAPI returns the appropriate concrete class, which you can cast to access specific segments.
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.v25.message.ADT_A01;
import ca.uhn.hl7v2.model.v25.message.ORU_R01;
Segment
Segment classes represent individual segments within a message such as MSH, PID, OBR, and OBX. Each segment class provides getter methods for accessing fields and components in a type-safe manner. Segments are version-specific because field definitions can vary between HL7 versions. Use segment classes to read or populate data within messages.
import ca.uhn.hl7v2.model.v25.segment.MSH;
import ca.uhn.hl7v2.model.v25.segment.PID;
import ca.uhn.hl7v2.model.v25.segment.OBX;
HapiContext
HapiContext serves as the central factory and configuration hub for HAPI operations. It creates parsers, manages validation settings, and provides thread-safe access to HAPI components. Always create a HapiContext instance and use it to obtain parsers rather than instantiating parsers directly. The context should be closed when finished to release resources properly.
import ca.uhn.hl7v2.HapiContext;
import ca.uhn.hl7v2.DefaultHapiContext;
Related Articles
Deep dive into HAPI library usage:
- HL7 Programming using Java and HAPI - Creating HL7 Messages - Detailed message creation
- HL7 Programming using Java and HAPI - Parsing HL7 Messages - Parsing techniques
- HL7 Programming using Java and HAPI - Using Tersers - Advanced data access
- HL7 Programming using Java and HAPI - Sending HL7 Messages - Network communication