Originally published in Portuguese on 27 November 2026: Portuguese version.
I sent 200 defective HL7 v2 messages to hl7apy, the Python library for HL7 v2, and in its strictest mode, STRICT, it rejected 100 of 200, none of them for a content error. The 80 with content errors (a CPF with a wrong check digit, an invalid CNS, a sex code outside the table, a birth date in the future) went through: 0 rejected. CPF is the Brazilian individual taxpayer ID, and CNS is the national health card number used by the Brazilian public health system. In the default mode, TOLERANT, it was 60 of 200. On the 40 valid messages, no false positives.
There was one more I didn’t expect. The message with PV1 before PID passed in both modes. And in STRICT it came out the other side already in the right order, with no warning at all.
Code, message generator and real output: demos/19-hl7apy-validacao-v2, in nursia-research-lab. It runs on CPU, with no account and no key.
Where did the question come from?
Over the last few weeks I tested two FHIR validators against the same set of planted defects. HealthChain caught only structural ones. Firely’s caught more, but it also let the wrong CPF through.
But a lot of Brazilian hospitals still talk HL7 v2, not FHIR. Admission ADT, lab results, scheduling. It’s the pipe-delimited text message that has been running for decades between EHR, lab and PACS. And anyone integrating that in Python ends up with hl7apy, which parses, builds and validates messages against the official HL7 structures.
The question was the same: what does its validate() catch, and what does it let through?
How did I run it?
- Linux, CPU, Python 3.11.18, clean venv, hl7apy 1.3.5 (MIT license, from CRS4, published on PyPI on 13 March 2024). There is a 1.4.0b1 beta that I didn’t test.
- 240 ADT^A01 version 2.5 messages, generated with a fixed seed: MSH, EVN, PID and PV1. CPF and CNS valid by algorithm, fictitious name with “TESTE”.
- 40 valid and 200 with one defect each, 20 per type, across 10 types: 6 structural and 4 content.
- Each message goes through
parse_message()and thenvalidate(), at both levels. Any exception, in parsing or in validation, counts as a rejection.
The core is this (a short version of checa() in demo.py):
from hl7apy.consts import VALIDATION_LEVEL
from hl7apy.parser import parse_message
def checa(er7, nivel):
try:
m = parse_message(er7, validation_level=nivel, find_groups=True)
except Exception as e:
return True, "parse", str(e)
try:
m.validate()
except Exception as e:
return True, "validate", str(e)
return False, "", ""
A detail that matters: if you call parse_message(er7) without setting the level, it uses TOLERANT. I checked it in the installed code (_DEFAULT_VALIDATION_LEVEL = VALIDATION_LEVEL.TOLERANT) and in the demo output.
What did hl7apy reject?
Numbers from results/resultado.txt:
| Defect (20 messages each) | Type | TOLERANT | STRICT |
|---|---|---|---|
| No PID segment | structural | 20 | 20 |
| No patient name (PID-5) | structural | 20 | 20 |
| Invalid date in PID-7 (month 13, day 32, dd/mm/yyyy) | structural | 0 | 20 |
| Name longer than 200 characters | structural | 0 | 20 |
| Duplicate PID | structural | 20 | 20 |
| PV1 before PID | structural | 0 | 0 |
| CPF with a wrong check digit | content | 0 | 0 |
| Invalid CNS | content | 0 | 0 |
Sex outside table 0001 (X, H, Masculino) |
content | 0 | 0 |
| Birth date between 2030 and 2099 | content | 0 | 0 |
| Total rejected (of 200) | 60 | 100 | |
| Control: valid messages rejected (of 40) | 0 | 0 |
Structural in STRICT: 100 of 120. Content: 0 of 80.
The difference between the two levels is in two rows of the table. Invalid date and long field: STRICT refuses them right at parsing:
ValueError: 19681312 is not an HL7 valid date value
MaxLengthReached: The value SOUZA TESTE XXXXXXXX...
TOLERANT accepts both, validate() returns True and the report_file comes out empty, with no length warning. In other words: if your code calls parse_message() without the level, a birth date of 19681312 gets in without complaint.
What happened to the out-of-order message?
In ADT^A01, PID comes before PV1. I swapped the two in 20 messages. Both levels accepted all 20.
In TOLERANT, to_er7() returned the message as it arrived. In STRICT, it returned all 20 with PID back in its place. The file results/exemplo_fora_de_ordem.txt shows input and output side by side.
I’ll admit I was torn. If you only want to read the data, it’s convenient. If you need to know that the source system is sending non-standard messages, it’s bad: the evidence disappears along the way. It’s like a reviewer who fixes the page order of a report and never tells anyone the pages came shuffled.
What about the sex table?
This one caught me. The validate() docstring says it checks “the adherence with the HL7 table”. And it does. But reading validation.py, the table check and the length check raise ValidationWarning, not an error. The warning goes to a file, and only if you pass report_file. The return value is still True.
I measured it: of the 20 messages with a sex code outside the table, STRICT accepted all 20, and all 20 had a warning in report_file:
Warning: Value H not in table HL70001 in element PID.PID_8
On the 40 valid ones, 0 warnings. So the signal exists. It just doesn’t reach whoever looks at the True.
How much code covers what was missing?
CPF and CNS are not HL7 rules. No generic validator will know that 50684112648, one of the CPFs in the batch, has a wrong check digit. That’s on us. I wrote a 21-line function, regras_br(), that runs after the STRICT parse (shown here without the docstring):
def regras_br(er7, hoje="20261126"):
probs = []
segs = [linha.split("|")[0] for linha in er7.split("\r")]
vistos = [x for x in segs if x in ORDEM_ADT_A01]
if vistos != sorted(vistos, key=ORDEM_ADT_A01.index):
probs.append("segmentos fora de ordem")
m = parse_message(er7, validation_level=VALIDATION_LEVEL.STRICT, find_groups=True)
pid = m.pid
for rep in pid.pid_3:
num, tipo = rep.cx_1.to_er7(), rep.cx_4.to_er7()
if tipo == "CPF" and not cpf_valida(num):
probs.append(f"CPF {num} com dígito errado")
if tipo == "CNS" and not cns_valida(num):
probs.append(f"CNS {num} inválido")
if pid.pid_8.to_er7() not in SEXO_HL70001:
probs.append(f"sexo {pid.pid_8.to_er7()} fora da tabela 0001")
if pid.pid_7.to_er7()[:8] > hoje:
probs.append(f"nascimento {pid.pid_7.to_er7()} no futuro")
return probs
Order is checked on the raw text, before parsing, because after STRICT it has already been fixed. Result: of the 100 that STRICT let through, regras_br() caught 100. On the 40 valid ones, it rejected 0. With both layers together, 200 of 200.
What didn’t work?
My first bet was wrong. I thought STRICT would refuse the out-of-order message, because the ADT^A01 structure defines the sequence. It didn’t. I didn’t dig into which part of the code does the reordering; I only recorded what goes in and what comes out. I also expected the out-of-table sex code to raise an error, because the docstring mentions tables. It produced a warning, in a file I had to ask for.
And the order rule I wrote is limited. It only knows MSH, EVN, PID and PV1. It works for this batch, not for a message with 20 segments and optional groups.
Who is it for, and when wouldn’t I use it?
It’s for anyone receiving HL7 v2 in Python who wants to stop broken messages at the door: missing required segment, empty required field, a date that isn’t a date, an oversized field, a segment repeated beyond its limit. STRICT did that with 0 false positives on the 40 valid messages. In my humble opinion, the practical rule is just one: set the level explicitly.
m = parse_message(er7, validation_level=VALIDATION_LEVEL.STRICT)
m.validate(report_file="avisos.txt") # table warnings only show up here
I wouldn’t use hl7apy on its own when:
- The risk is wrong data, not a broken message. CPF, CNS and a plausible date are on you. A 21-line check handled the 4 cases I tested.
- You need to audit the source system. An out-of-order message passes, and in
STRICTit comes out reordered. If that matters, check the raw text before parsing. - Your flow decides only on the
True. A table warning doesn’t change the return value.
How far does this test go?
- The answer key is mine. 10 defect types, 20 cases each, chosen by what I see as likely in a Brazilian integration. It isn’t a sample of real traffic.
- Only ADT^A01, only version 2.5, only 4 segments. With Z-segments, optional groups and another version, results may change.
- No message profile. hl7apy accepts a profile (
message_profile=) that tightens cardinality and length. I didn’t test it. A profile doesn’t check a CPF check digit either. - The “today” date is fixed at 26 November 2026, so the result is the same on any day.
- All data is synthetic. CPF and CNS pass the algorithm, but they are drawn with a fixed seed.
Source and how to reproduce
hl7apy 1.3.5 on PyPI (MIT), repository github.com/crs4/hl7apy. The documentation (crs4.github.io/hl7apy) didn’t open when I checked, on 26 November 2026. What I state about the default level, warnings and report_file comes from reading the installed code: hl7apy/__init__.py, hl7apy/parser.py and hl7apy/validation.py.
Code and real output: demos/19-hl7apy-validacao-v2. Three commands:
git clone https://github.com/rogeriorrodrigues/nursia-research-lab
cd nursia-research-lab/demos/19-hl7apy-validacao-v2 && pip install -r requirements.txt
python demo.py && python -m pytest tests -q -s
The test checks that STRICT accepts the 4 content types and the swapped order, that it rejects the invalid date TOLERANT accepts, and that regras_br() catches 80 of 80 content defects without rejecting any valid message. The output goes to results/resultado.txt and results/resultado.json.
Do you validate HL7 v2 at the door, or trust the source system? Has anyone ever caught an out-of-order message in production?
The demo is part of the NursIA research repository (PPGINFOS/UFSC, FAPESC grant).

