The lab says, “Order 17, platelet result 220.” The medical record system already has a patient whose family name is Lin. The hardest line in a few lines of code that save 220 may be this one: whose record do I write it to? The lab sends back medical record number P42, but the records API wants a reference like Patient/91fb…. The result was first entered at 10:30. A quarter of an hour later, the lab corrects 220 to 218, and the program must find that same result again.
While researching hospital systems in 2025, I first asked how HL7 and FHIR were related, then how to integrate a HIS and LIS in Python. A HIS is a hospital information system. Here its roles are registering patients and receiving results. A LIS is a laboratory information system. It receives orders, records results, and releases them. Let’s run through the missing adapter using fictional data.
How does a lab result correspond to a patient in the medical record system?
Take one of Lin’s blood counts. The lab sends a message, while the medical record system stores a patient record. Besides creating and reading patient records, the receiver needs to support searching by issuing authority and medical record number, and saving a measurement under a specified ID. First, look at the identifiers each side uses.
The records system creates Lin’s patient resource with POST /Patient. A resource is a record using standard fields. Here POST means submitting a new record to a web service. The records system assigns its own ID and also stores medical record number P42 and the issuing authority. Here’s the create request body:
{"resourceType":"Patient","identifier":[{"system":"https://demo.example/mrn/DEMO","value":"P42"}],"name":[{"family":"Lin"}]}
HL7 is the organization that develops healthcare information exchange standards. It developed both HL7 v2 and FHIR. In this example the lab sends a message following v2 conventions, and the records system uses FHIR conventions to store records that can be read by address. The same result needs two representations, and the adapter translates between them.
sequenceDiagram
participant L as 检验科系统
participant A as Python 适配程序
participant F as 病历系统的 FHIR 接口
L->>A: 发来病历号 P42、检验单 L91、血小板计数 220
A->>F: 按发号机构 DEMO 和 P42 查患者
F-->>A: 返回唯一匹配的患者档案及其 ID
A->>F: 写入 L91 的血小板结果 220,关联该患者
L->>A: 更正同一项结果为 218
A->>F: 向同一结果地址写入 218,标记为已更正
Follow two identifiers in the diagram. P42 and the issuing authority identify the person. L91, together with the lab, test item, and sub-ID, identifies this particular result. Let’s read them from the original message.
The 10:30 message has four segments. MSH identifies the sender, receiver, and event type. PID identifies the patient. OBR contains the order and lab identifiers. OBX contains an individual measurement. Vertical bars separate fields and carets separate components within a field. This is the file the exercise actually reads.1
MSH|^~\&|LAB|DEMO|EHR|DEMO|202508141030||ORU^R01|MSG17|P|2.5.1
PID|1||P42^^^DEMO^MR
OBR|1|17^EHR|L91^LAB|CBC^Blood count^L||||||||||||||||||20250814103000
OBX|1|NM|PLT^Platelets^L|1|220|10*9/L^10*9/L^UCUM|||||F
To try it locally, save the four lines above exactly as shown in result.hl7. In a Python 3.12 environment run python -m pip install hl7apy==1.3.5. Save the following code beside the file as parse_result.py and run python parse_result.py. It prints P42 17 L91 PLT 220. HL7 v2 separates on-wire segments with carriage returns. The teaching file uses separate lines for readability and restores carriage returns when reading.2
from pathlib import Path
from hl7apy.parser import parse_message
text = Path("result.hl7").read_text()
msg = parse_message("\r".join(text.splitlines()), find_groups=False)
print(msg.pid.pid_3.cx_1.value, msg.obr.obr_2.ei_1.value,
msg.obr.obr_3.ei_1.value, msg.obx.obx_3.ce_1.value, msg.obx.obx_5.value)
| What to identify | What the message contains | What the adapter does with it |
|---|---|---|
| A person | P42 issued by DEMO in PID | Map local issuer DEMO to the full identifier above and search for the patient |
| An order | Placer order 17 and lab order L91 in OBR | Each department can quote its own system’s number when reconciling |
| One result on the order | Local test PLT and sub-ID 1 in OBX | Identify the result together with the lab and its order number. These fields stay constant when a value is corrected |
| What was released this time | 220 billion per liter, status F | Write a FHIR measurement. F means final. This example also accepts C for a correction |
📓 Note: A blood count contains several measurements. PLT is just the platelet item. Two institutions can issue P42 to different people. A network connection solves transport. Both sides must still agree on how to match issuers, test items, and units.
Finding the correct Patient from P42
FHIR R4 is the healthcare exchange standard version used here. It supports finding patients by business identifier. A server supporting that search can take system|value. In this excerpt, client is the HTTP client connected to the records service, and msg is the parsed message. Python’s params encodes characters such as the vertical bar in the URL. The teaching service returns all matches at once. The collection it returns is called a Bundle.3
token = f"https://demo.example/mrn/DEMO|{msg.pid.pid_3.cx_1.value}"
matches = client.get("/Patient", params={"identifier": token}).raise_for_status().json()
if matches["total"] != 1:
raise ValueError("需要先核对病历号")
patient_id = matches["entry"][0]["resource"]["id"]
Zero matches may mean the patient has not yet been registered or the issuer has been mapped incorrectly. Two matches need review by whoever manages patient identity. In neither case should the adapter simply write to the first array element. For other servers, follow their pagination capabilities. If they don’t provide an exact total, check for a second match before concluding that the patient is unique.
When the lab corrects a platelet count from 220 to 218, how does the record system update the original result?
We have found Lin’s record. Now we need the platelet count on lab order 17. The lab reported 220 at 10:30 and sent a corrected value of 218 at 10:45 for the same test, both in billions per liter. When the doctor reopens order 17, they should see 218 and be able to tell the result was corrected.
FHIR stores this measurement as an Observation. The code below writes the initial 220. subject.reference points to Lin’s patient record, and rid identifies the platelet result on this order. When 218 arrives, the program reuses the same rid, updates the value, and changes the status from final to corrected.4
result = {
"resourceType": "Observation", "id": rid, "status": "final",
"subject": {"reference": f"Patient/{patient_id}"},
"code": {"coding": [{"system": "https://lab.example/codes", "code": "PLT"}]},
"valueQuantity": {"value": float(msg.obx.obx_5.value), "unit": msg.obx.obx_6.ce_1.value}
}
client.put(f"/Observation/{rid}", json=result,
headers={"X-Lab-Revision": "20250814103000"}).raise_for_status()
There are two senses of “the same”. The first is the same result. The example derives a reproducible ID (UUID v5) from lab LAB, lab order L91, the test coding system and code, and sub-ID 1. The value and display name are excluded from the key. Changing 220 to 218 still writes to the same address. The second is the same revision arriving twice. The two sides additionally agree to use the result status change time in OBR-22 as a source revision. It must strictly increase with each correction to the same result. The backend compares revisions and saves the result in one SQLite write transaction, as follows.
| Delivery order | Server behavior | What the doctor reads at the same address |
|---|---|---|
| The 10:30 result of 220 arrives for the first time | Creates the result and returns 201 | 220, final |
| The exact same message arrives again | Returns 200 and skips a duplicate write and change event | Still 220 |
| The 10:45 result of 218 arrives with status C | Updates the original resource and emits a correction event | 218, corrected |
| The old 10:30 revision arrives late | Returns 409 for a revision conflict | Still 218 |
PUT writes the resource to the specified address. This server supports creation with a client-assigned ID. A real FHIR server’s capability statement tells you whether it supports this kind of creation. X-Lab-Revision is a private convention between these two experimental endpoints. If the LIS can issue two corrections in one second, roll its clock back, or omit this field, choose a different sortable revision number. Equal revisions with different content require reconciliation.5
How can I check that correcting 220 to 218 writes to the same address?
Use the lab message above for a small exercise. Save the following code as result_id.py and run python3 result_id.py. It uses only the Python standard library. To show where the ID comes from, the example extracts only the OBX segment of a known format. A complete interface also needs the earlier message-type and patient-matching checks.
import json
from uuid import NAMESPACE_URL, uuid5
def result_address(obx):
fields = obx.split("|")
code, label, system = fields[3].split("^")
# LAB、L91 来自同一单的 OBR;最后一项是 OBX 的子编号。
key = ["LAB", "L91", system, code, fields[4]]
return "/Observation/" + uuid5(NAMESPACE_URL, json.dumps(key)).hex
first = "OBX|1|NM|PLT^Platelets^L|1|220|10*9/L^10*9/L^UCUM|||||F"
correction = first.replace("|220|", "|218|").replace("|||||F", "|||||C")
print(result_address(first))
print(result_address(first) == result_address(correction))
The first line prints /Observation/f0ba1de8862e562ba8a4888df3f7e699 and the second prints True. Change the sub-ID in the correction message from 1 to 2 and compare again. Now you’ll get False. Once two messages resolve to the same address, the server still has to compare source revisions to decide whether to overwrite or reject.
In the complete experiment with a local records service, I sent the first result, duplicate, correction, and late old revision in sequence, then read the same address. The results are below. I then changed the patient to unregistered P99 and added another record with the same identifier as P42. Both attempts stopped at patient lookup. The record system still contained just one lab result and two effective writes.
首次 201 | 重发 200 | 更正 200 | 旧版迟到 409 | 当前 218 corrected
This exercise accepts one numeric PLT result from the agreed sender. It stops on a different message type or multiple results so you can write a separate mapping for the relevant message structure. At this point the medical record contains 218. If an analyst still sees 220 in another table, there’s a second question: Who tells the analytics program when a resource changes, and what happens if the notification is lost?
Footnotes
-
Health Level Seven International. (2007). HL7 v2.5.1, Chapter 7: Observation reporting. HL7 Europe. §7.4,OBR 与 OBX 的字段及结果状态。 ↩
-
CRS4. (n.d.). Parser. HL7apy Documentation. 见 parse_message 的 find_groups 参数和消息示例。 ↩
-
Health Level Seven International. (2019). Search. FHIR R4 v4.0.1. Token 参数中 system 和 value 的组合。 ↩
-
Health Level Seven International. (2019). Observation. FHIR R4 v4.0.1. status、code、subject 和 value 的结构。 ↩
-
Health Level Seven International. (2019). RESTful API. FHIR R4 v4.0.1. Update 与 update as create。 ↩