Skip to main content

FHIR Lite

Python Dependencies codecov License

FHIR Lite is an ultra-lightweight, zero-dependency Python library designed to parse, modify, validate, and convert medical resources under the HL7 FHIR (Fast Healthcare Interoperability Resources) standard.

Built specifically for high-throughput, low-latency, and package-size-critical environments (e.g., AWS Lambda, Google Cloud Run, Cloud Functions, and Apache Beam / Dataflow pipelines), it enables seamless interoperability between modern systems (JSON) and legacy healthcare systems (XML).


Features

  • Zero Dependencies: Relies exclusively on Python's standard library (json and xml.etree.ElementTree). No pip install bloat or supply-chain baggage.
  • Serverless-Friendly: Weighs only a few kilobytes with near-zero cold-start overhead.
  • Lossless Bidirectional Conversion: Accurately converts between FHIR JSON and FHIR XML, honoring FHIR namespaces (http://hl7.org/fhir), primitive value attributes, and list element representations.
  • Extensible Object-Oriented Architecture: Base FHIRResource class with dictionary/attribute access, automatic subclass registration, and custom validation hooks (includes pre-built Patient and Observation).

Installation

Because FHIR Lite has zero external dependencies, you can simply vendor the fhir_lite directory into your project, or install locally:

# Clone the repository
git clone https://github.com/BuhoZurdo/fhir-lite.git

# Or copy `fhir_lite/` directly into your AWS Lambda layer or service package

Quick Start

1. Direct JSON $\leftrightarrow$ XML Conversion

Transform payloads directly without instantiating resource classes—ideal for proxy microservices, API gateways, and ETL pipelines:

from fhir_lite import json_to_xml, xml_to_json

# Convert FHIR JSON to formatted FHIR XML
fhir_json = '''{
  "resourceType": "Patient",
  "id": "pat-001",
  "active": true,
  "gender": "male"
}'''

xml_output = json_to_xml(fhir_json, pretty=True)
print(xml_output)
# Output:
# <Patient xmlns="http://hl7.org/fhir">
#   <id value="pat-001" />
#   <active value="true" />
#   <gender value="male" />
# </Patient>

# Convert back from XML to JSON
json_output = xml_to_json(xml_output, indent=2)

2. Working with Resources (Patient, Observation)

Access fields via attributes or dictionary keys with built-in validation:

from fhir_lite import Patient, Observation

# Initialize with keyword arguments or dictionaries
patient = Patient(
    id="pat-100",
    active=True,
    gender="female",
    name=[{"use": "official", "family": "Smith", "given": ["Jane"]}]
)

# Access fields seamlessly
print(patient.id)             # "pat-100"
print(patient["gender"])      # "female"
print(patient.is_valid)       # True

# Safe deep path traversal (dot-notation or key sequences)
print(patient.get_path("name.0.family"))               # "Smith"
print(patient.get_path("name.0.given.0"))              # "Jane"
print(patient.get_path("missing.field", default="N/A")) # "N/A"

# Semantic extractors for identifiers and medical codes
print(patient.get_identifier(system="http://hospital.org/mrn")) # "MRN-123"
# print(obs.get_coding(system="http://loinc.org"))               # "883-9"

# Export to JSON or XML
print(patient.to_json())
print(patient.to_xml())

3. Dynamic Deserialization (from_json / from_xml)

The library automatically detects the resourceType and instantiates the registered subclass:

from fhir_lite import from_json, from_xml, Patient, Observation

# Automatically instantiates a Patient
res = from_json('{"resourceType": "Patient", "id": "p1", "gender": "male"}')
assert isinstance(res, Patient)

# Automatically instantiates an Observation
xml_data = '<Observation xmlns="http://hl7.org/fhir"><id value="obs-1"/><status value="final"/><code/></Observation>'
obs = from_xml(xml_data)
assert isinstance(obs, Observation)

4. Creating Custom Resources

Inheriting from FHIRResource automatically registers the new resource type with the dynamic deserializer and validator:

from fhir_lite import FHIRResource

class CarePlan(FHIRResource):
    resource_type = "CarePlan"
    array_fields = {"category", "activity", "note"}

    def validate(self) -> list[str]:
        errors = super().validate()
        if "status" not in self.data:
            errors.append("CarePlan requires 'status'")
        return errors

# Usage
plan = CarePlan(id="cp-01", status="active")
print(plan.is_valid)  # True
print(plan.to_xml())

5. FHIR Bulk Data (NDJSON Streaming)

Process massive clinical datasets (e.g. from AWS HealthLake, Google Cloud Healthcare, or Athena) line-by-line with $O(1)$ constant memory overhead and transparent .gz decompression:

from fhir_lite import iter_ndjson, write_ndjson

# Stream resources from plain or gzipped NDJSON
for resource in iter_ndjson("patients.ndjson.gz"):
    if resource.is_valid:
        print(f"Processed: {resource.resource_type}/{resource.id}")

# Stream write resources to a compressed file
write_ndjson([patient, observation], "export.ndjson.gz")

6. Zero-Dependency REST Client (FHIRClient)

Interact with FHIR servers (e.g. HAPI, AWS HealthLake, Google Healthcare) using Python's standard library urllib without installing requests or httpx:

from fhir_lite import FHIRClient, Patient, Bundle

client = FHIRClient(
    base_url="https://hapi.fhir.org/baseR4",
    auth="my-bearer-token",  # or auth=("user", "password")
    max_retries=3,           # Automatic retry on 429 (rate limit), 502, 503, 504
    backoff_factor=0.5,      # Exponential backoff + Retry-After header parsing
)

# Fetch a resource by ID (auto-instantiates typed Patient)
patient = client.read(Patient, "12345")

# Conditional Create (If-None-Exist) & Idempotent get_or_create
patient, created = client.get_or_create(patient, identifier="http://hospital.org/mrn|12345")

# FHIR JSON Patch (partial updates without race conditions)
client.patch(Patient, patient.id, [
    {"op": "replace", "path": "/active", "value": False}
])

# Automatic multi-page search iterator (follows bundle.link 'next')
for pat in client.iter_search(Patient, family="Smith", max_pages=5):
    print(pat.id)

# Fluent Transaction & Batch Builder (POST [base])
tx = Bundle.transaction()
tx.add_create(Patient(gender="female", active=True))
tx.add_delete(Patient, "old-patient-id")
tx_response = client.transaction(tx)

7. Optional Pydantic Interoperability (Soft Dependency)

fhir-lite has zero required dependencies, but if you or your framework (e.g., FastAPI) uses Pydantic (v1 or v2), you can seamlessly convert models back and forth:

from pydantic import BaseModel
from fhir_lite import FHIRResource

class MyPatientModel(BaseModel):
    resourceType: str = "Patient"
    id: str
    active: bool = True
    gender: str

# 1. Convert any Pydantic model into a typed FHIRResource
pyd_patient = MyPatientModel(id="pat-pyd-1", gender="female")
resource = FHIRResource.from_pydantic(pyd_patient)

# Now enjoy all fhir-lite features: lossless XML conversion, validation, NDJSON streaming
xml_data = resource.to_xml()

# 2. Convert a FHIRResource back into your Pydantic model
pyd_again = resource.to_pydantic(MyPatientModel)

8. FHIR Reference Helpers (Reference)

Parse and build FHIR reference strings and dictionaries with ease:

from fhir_lite import Reference, Patient

# Parse string, absolute URL, or dictionary
ref = Reference.parse("Patient/12345")
print(ref.resource_type)  # "Patient"
print(ref.id)             # "12345"

# Create valid reference dictionaries
ref_dict = Reference.create(Patient, "12345", display="Jane Doe")
# {"reference": "Patient/12345", "display": "Jane Doe"}

Testing

Run the included standalone test suites (no third-party test runners needed):

python -m tests.test_fhir_lite
python -m tests.test_security
python -m tests.test_ndjson
python -m tests.test_client
python -m tests.test_typing
python -m tests.test_version
python -m tests.test_operation_outcome
python -m tests.test_optimization
python -m tests.test_pydantic_interop
python -m tests.test_reference_and_path
python -m tests.test_advanced_features

Project Structure

fhir-lite/
├── fhir_lite/
│   ├── __init__.py       # Public package interface
│   ├── client.py         # Zero-dependency FHIR REST client (urllib) & FHIRError
│   ├── ndjson.py         # Streaming NDJSON Bulk Data reader/writer (gzip support)
│   ├── py.typed          # PEP 561 inline typing marker
│   ├── resources.py      # Core resources (Patient, Observation, Bundle, OperationOutcome, etc.)
│   ├── serializer.py     # Fast ElementTree/JSON converter (XXE/DoS protected, primitive extensions)
│   ├── types.py          # TypedDict definitions for common FHIR structures
│   └── version.py        # FHIRVersion (R4, R4B, R5) declarations and context manager
├── tests/
│   ├── test_client.py            # Mocked FHIR REST client tests
│   ├── test_fhir_lite.py         # Core resource, validation, and extension test suite
│   ├── test_ndjson.py            # Streaming & gzip bulk data tests
│   ├── test_operation_outcome.py # OperationOutcome & error integration tests
│   ├── test_security.py          # XXE, DTD, and parser security tests
│   ├── test_typing.py            # PEP 561 & TypedDict tests
│   └── test_version.py           # FHIR R4/R5 version context & alias tests
├── pyproject.toml        # PEP 517/621 packaging metadata
└── README.md

License

MIT

Metadata

Release files for fhir-lite 0.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fhir-lite 0.5.0
File Size Uploaded Provenance Actions
fhir_lite-0.5.0.tar.gz 57.0 kB With provenance Details for fhir_lite-0.5.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fhir-lite 0.5.0
File Interpreter ABI Platform Actions
fhir_lite-0.5.0-py3-none-any.whl Python 3 none any Details for fhir_lite-0.5.0-py3-none-any.whl

Total release size: 93.2 kB

Release files / fhir_lite-0.5.0.tar.gz

Download URL fhir_lite-0.5.0.tar.gz
Size 57.0 kB
Tags Source
SHA-256 checksum
How to use checksums
50947e0e8aa75300fc00135117aa4949350fa65b92ca6232a2dc80cf5a1132d8
BLAKE2b-256 checksum
How to use checksums
69c2da23b02a26e20ab7e27481f81699bca0fb6e37e20fa095d6a5ca917cf451
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

Release files / fhir_lite-0.5.0-py3-none-any.whl

Download URL fhir_lite-0.5.0-py3-none-any.whl
Size 36.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9f4961d7a73e2ace2d5571a940b9cc6925fec5a6307931f24ff973fa5b934f59
BLAKE2b-256 checksum
How to use checksums
33207b0a967e4a940573c6a050a6cceed9b65616eb40eb0cd43aebe66b4dd16b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

Security for fhir-lite 0.5.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for fhir_lite-0.5.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page