FHIR Lite
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 (
jsonandxml.etree.ElementTree). Nopip installbloat 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), primitivevalueattributes, and list element representations. - Extensible Object-Oriented Architecture: Base
FHIRResourceclass with dictionary/attribute access, automatic subclass registration, and custom validation hooks (includes pre-builtPatientandObservation).
Installation
Install the latest release directly from PyPI:
pip install fhir-lite
Because FHIR Lite has zero external dependencies, you can also 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.6.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fhir_lite-0.6.1.tar.gz | 63.3 kB | With provenance | Details for fhir_lite-0.6.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fhir_lite-0.6.1-py3-none-any.whl | Python 3 | none | any | Details for fhir_lite-0.6.1-py3-none-any.whl |
Total release size: 102.5 kB
Release files / fhir_lite-0.6.1.tar.gz
| Download URL | fhir_lite-0.6.1.tar.gz |
|---|---|
| Size | 63.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5469e5d647e83bfdac31b987bf33a54aa19cb3d7db6fda0d4932e855725c58b2
|
|
BLAKE2b-256 checksum How to use checksums |
645d2ad43eadd82d39ee0afa0cf70180f936e987b74c8fb950ca7e43a62330d5
|
| 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 19, 2026.
Transparency logRelease files / fhir_lite-0.6.1-py3-none-any.whl
| Download URL | fhir_lite-0.6.1-py3-none-any.whl |
|---|---|
| Size | 39.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
ed32c2ca422c004709ee14ed695ae1912c46dce938f219a61de68b2fcf524cf0
|
|
BLAKE2b-256 checksum How to use checksums |
3c21bc4b23b23259a7a2d13c0da7bd8be2039928cede63fbbb7b916181a61f8e
|
| 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 19, 2026.
Transparency logSecurity for fhir-lite 0.6.1
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.
Attestation for fhir_lite-0.6.1.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 19, 2026.
Transparency logA 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.