Week 4 practice

FHIR APIs · 2 exercises

The full text of every practice problem that fits week 4, grouped by lecture section. Set up the two sets first: the commands are on the practice problems page. Each reference solution is collapsed under its exercise; run the tests before you open it.

The week 3 bridge's output

Lecture: The week 3 bridge's output.

hl7-practice 18: ORU → FHIR (lite)

Hard

INT-302: A new downstream only accepts FHIR. Convert ORU into Patient + Observations.

oru_to_fhir(message: str) -> dict → {"patient": {...}, "observations": [...]}

Patient (from PID): | key | from | |---|---| | resourceType | "Patient" | | identifier | each PID-3 repeat → {"system": PID-3.4, "value": PID-3.1} | | name | [{"family": PID-5.1.1, "given": [PID-5.2, PID-5.3 if present]}] | | birthDate | first 8 chars of PID-7 → YYYY, YYYY-MM, or YYYY-MM-DD; empty → omit the key | | gender | M→male, F→female, O→other, anything else→unknown |

Observation (one per OBX, in order): | key | from | |---|---| | resourceType | "Observation" | | status | OBX-11: F→final, P→preliminary, C→corrected, X→cancelled, anything else→unknown | | subject | {"reference": "Patient/<PID-3.1 of the first repeat>"} | | code | {"coding": [{"system": ..., "code": OBX-3.1, "display": OBX-3.2}]}; system = http://loinc.org if OBX-3.3 = LN, otherwise keep OBX-3.3 as-is | | valueQuantity | if OBX-2 = NM: {"value": float(OBX-5), "unit": OBX-6.1} (unit may be mmol/L^mmol/L^UCUM) | | valueString | if OBX-2 is not NM: OBX-5 | | interpretation | if OBX-8 is not empty: [{"coding": [{"code": OBX-8}]}]; empty → omit the key |

Write it in p18_oru_to_fhir.py, then run python3 test_practice.py p18.

Reference solution

It imports solutions/_hl7.py.

from solutions._hl7 import all_of, field, first, part

GENDER = {"M": "male", "F": "female", "O": "other"}
STATUS = {"F": "final", "P": "preliminary", "C": "corrected", "X": "cancelled"}


def _patient(pid: list[str]) -> dict:
    identifiers = [{"system": part(r, "^", 4), "value": part(r, "^", 1)} for r in field(pid, 3).split("~")]
    name = field(pid, 5)
    given = [g for g in (part(name, "^", 2), part(name, "^", 3)) if g]
    patient = {
        "resourceType": "Patient",
        "identifier": identifiers,
        "name": [{"family": part(part(name, "^", 1), "&", 1), "given": given}],
    }
    dob = field(pid, 7)[:8]
    if dob:
        patient["birthDate"] = "-".join(p for p in (dob[:4], dob[4:6], dob[6:8]) if p)
    patient["gender"] = GENDER.get(field(pid, 8), "unknown")
    return patient


def _observation(obx: list[str], patient_id: str) -> dict:
    code = field(obx, 3)
    system = part(code, "^", 3)
    obs = {
        "resourceType": "Observation",
        "status": STATUS.get(field(obx, 11), "unknown"),
        "subject": {"reference": f"Patient/{patient_id}"},
        "code": {"coding": [{"system": "http://loinc.org" if system == "LN" else system,
                             "code": part(code, "^", 1), "display": part(code, "^", 2)}]},
    }
    if field(obx, 2) == "NM":
        obs["valueQuantity"] = {"value": float(field(obx, 5)), "unit": part(field(obx, 6), "^", 1)}
    else:
        obs["valueString"] = field(obx, 5)
    if field(obx, 8):
        obs["interpretation"] = [{"coding": [{"code": field(obx, 8)}]}]
    return obs


def oru_to_fhir(message: str) -> dict:
    patient = _patient(first(message, "PID"))
    patient_id = patient["identifier"][0]["value"]
    return {"patient": patient, "observations": [_observation(o, patient_id) for o in all_of(message, "OBX")]}

mellp 34: Results Bundle

Medium · fhir · bundle · observation · python-hl7

One ORU^R01 carries a patient and a handful of results. In FHIR that is several resources that must land together, so the usual answer is a transaction Bundle: one POST, all or nothing. Inside the bundle the resources do not have server IDs yet, so they point at each other with temporary urn:uuid: addresses that the server rewrites when it stores them.

STATUSES = {"F": "final", "P": "preliminary", "C": "corrected"}

def to_bundle(raw: str) -> dict

Return {"resourceType": "Bundle", "type": "transaction", "entry": [...]}. Raise ValueError when MSH-9 is not ORU^R01.

  1. The patient comes first.
  2. fullUrl: "urn:uuid:" + a fresh uuid.uuid4()
  3. resource: {"resourceType": "Patient", "identifier": [{"value": PID-3.1}], "name": [{"family": PID-5.1, "given": [PID-5.2]}]}
  4. request: {"method": "POST", "url": "Patient", "ifNoneExist": "identifier=<PID-3.1>"}. This is a conditional create: the server only creates the patient if no patient with that identifier exists.
  5. Then one entry per OBX, in message order.
  6. fullUrl: its own fresh urn:uuid:
  7. request: {"method": "POST", "url": "Observation"}
  8. resource:
    • resourceType: "Observation"
    • status: from OBX-11 through STATUSES, anything else "unknown"
    • code: {"coding": [{"code": OBX-3.1, "display": OBX-3.2, "system": "http://loinc.org"}]}, with system only when OBX-3.3 is LN
    • subject: {"reference": <the patient entry's fullUrl>}
    • effectiveDateTime: the date part of OBR-7 as YYYY-MM-DD
    • OBX-2 NM: valueQuantity = {"value": float(OBX-5), "unit": OBX-6.1}, with no unit key when OBX-6 is empty. Any other OBX-2: valueString = OBX-5.
  9. No empty values anywhere, as in problem 33: no "", [], {} or None. The number 0.0 is a value.

Why only the date: a FHIR dateTime that has a time must also carry a timezone offset. An HL7 v2 timestamp without an offset is in the sender's local time, which this message does not tell you, so a date is the most this mapping can state truthfully.

Example 1:

bundle = to_bundle(oru_r01())    # PID 12345 DOE^JANE, OBR-7 20260105074500, three OBX

bundle["entry"][0]["request"]
    -> {"method": "POST", "url": "Patient", "ifNoneExist": "identifier=12345"}

bundle["entry"][1]["resource"]
    -> {"resourceType": "Observation",
        "status": "final",
        "code": {"coding": [{"system": "http://loinc.org", "code": "2345-7", "display": "Glucose"}]},
        "subject": {"reference": "urn:uuid:5f0c..."},     # entry 0's fullUrl
        "effectiveDateTime": "2026-01-05",
        "valueQuantity": {"value": 182.0, "unit": "mg/dL"}}

Example 2:

Input:  "...OBX|3|ST|5778-6^Color of Urine^LN||YELLOW||||||F\r"
Output: the third observation has "valueString": "YELLOW" and no valueQuantity.

Example 3:

Input:  an ADT^A01
Output: ValueError

Constraints:

Follow-up: you want to send the full time after all. Where should the offset come from, and what should happen when the clocks change and a local time occurs twice?

Hint 1

[line.split("|") for line in raw.split("\r") if line] gives every segment as a list where index n is field n (for MSH, index n is MSH-(n+1)). With python-hl7 the same reads are msg["OBX.F3.R1.C1"] style keys, and msg.segments("OBX") raises KeyError when there is none.

Hint 2

Generate the patient's fullUrl before building any observation; every observation needs it.

Write it in problems/34-results-bundle/solution.py, then run:

uv run pytest problems/34-*
Reference solution
import uuid

STATUSES = {"F": "final", "P": "preliminary", "C": "corrected"}


def entry(resource: dict) -> dict:
    request = {"method": "POST", "url": resource["resourceType"]}
    return {"fullUrl": f"urn:uuid:{uuid.uuid4()}", "resource": resource, "request": request}


def to_observation(obx: list[str], subject: str, effective: str) -> dict:
    code, display, coding_system = obx[3].split("^")[:3]
    coding = {"code": code, "display": display}
    if coding_system == "LN":
        coding["system"] = "http://loinc.org"
    observation = {
        "resourceType": "Observation",
        "status": STATUSES.get(obx[11], "unknown"),
        "code": {"coding": [coding]},
        "subject": {"reference": subject},
        "effectiveDateTime": effective,
    }
    if obx[2] == "NM":
        quantity = {"value": float(obx[5])}
        if obx[6]:
            quantity["unit"] = obx[6].split("^")[0]
        observation["valueQuantity"] = quantity
    else:
        observation["valueString"] = obx[5]
    return observation


def to_bundle(raw: str) -> dict:
    segments = [line.split("|") for line in raw.split("\r") if line]
    if segments[0][8].split("^")[:2] != ["ORU", "R01"]:
        raise ValueError(f"not an ORU^R01: {segments[0][8]}")
    pid = next(segment for segment in segments if segment[0] == "PID")
    obr = next(segment for segment in segments if segment[0] == "OBR")
    mrn = pid[3].split("^")[0]
    family, given = pid[5].split("^")[:2]
    name = {"family": family, "given": [given]}
    patient = entry({"resourceType": "Patient", "identifier": [{"value": mrn}], "name": [name]})
    patient["request"]["ifNoneExist"] = f"identifier={mrn}"
    effective = f"{obr[7][0:4]}-{obr[7][4:6]}-{obr[7][6:8]}"
    entries = [patient]
    for segment in segments:
        if segment[0] == "OBX":
            entries.append(entry(to_observation(segment, patient["fullUrl"], effective)))
    return {"resourceType": "Bundle", "type": "transaction", "entry": entries}

mellp statements and solutions are copied from mellp at commit 5d8e459.


Course content © 2026 HeyItWorked. All rights reserved.

Site design adapted from The Missing Semester of Your CS Education under CC BY-NC-SA 4.0. See copyright and license.