fhir-lite 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. fhir_lite-0.5.0/PKG-INFO +327 -0
  2. fhir_lite-0.5.0/README.md +297 -0
  3. fhir_lite-0.5.0/fhir_lite/__init__.py +242 -0
  4. fhir_lite-0.5.0/fhir_lite/__main__.py +8 -0
  5. fhir_lite-0.5.0/fhir_lite/anonymize.py +310 -0
  6. fhir_lite-0.5.0/fhir_lite/cli.py +378 -0
  7. fhir_lite-0.5.0/fhir_lite/client.py +349 -0
  8. fhir_lite-0.5.0/fhir_lite/fhirpath.py +530 -0
  9. fhir_lite-0.5.0/fhir_lite/ndjson.py +81 -0
  10. fhir_lite-0.5.0/fhir_lite/py.typed +1 -0
  11. fhir_lite-0.5.0/fhir_lite/resources.py +677 -0
  12. fhir_lite-0.5.0/fhir_lite/serializer.py +207 -0
  13. fhir_lite-0.5.0/fhir_lite/types.py +197 -0
  14. fhir_lite-0.5.0/fhir_lite/version.py +179 -0
  15. fhir_lite-0.5.0/fhir_lite.egg-info/PKG-INFO +327 -0
  16. fhir_lite-0.5.0/fhir_lite.egg-info/SOURCES.txt +34 -0
  17. fhir_lite-0.5.0/fhir_lite.egg-info/dependency_links.txt +1 -0
  18. fhir_lite-0.5.0/fhir_lite.egg-info/entry_points.txt +2 -0
  19. fhir_lite-0.5.0/fhir_lite.egg-info/requires.txt +8 -0
  20. fhir_lite-0.5.0/fhir_lite.egg-info/top_level.txt +1 -0
  21. fhir_lite-0.5.0/pyproject.toml +53 -0
  22. fhir_lite-0.5.0/setup.cfg +4 -0
  23. fhir_lite-0.5.0/tests/test_advanced_features.py +243 -0
  24. fhir_lite-0.5.0/tests/test_anonymize.py +246 -0
  25. fhir_lite-0.5.0/tests/test_cli.py +190 -0
  26. fhir_lite-0.5.0/tests/test_client.py +229 -0
  27. fhir_lite-0.5.0/tests/test_fhir_lite.py +242 -0
  28. fhir_lite-0.5.0/tests/test_fhirpath.py +292 -0
  29. fhir_lite-0.5.0/tests/test_ndjson.py +85 -0
  30. fhir_lite-0.5.0/tests/test_operation_outcome.py +203 -0
  31. fhir_lite-0.5.0/tests/test_optimization.py +117 -0
  32. fhir_lite-0.5.0/tests/test_pydantic_interop.py +125 -0
  33. fhir_lite-0.5.0/tests/test_reference_and_path.py +124 -0
  34. fhir_lite-0.5.0/tests/test_security.py +66 -0
  35. fhir_lite-0.5.0/tests/test_typing.py +148 -0
  36. fhir_lite-0.5.0/tests/test_version.py +297 -0
@@ -0,0 +1,327 @@
1
+ Metadata-Version: 2.4
2
+ Name: fhir-lite
3
+ Version: 0.5.0
4
+ Summary: Ultra-lightweight, zero-dependency FHIR library for Python.
5
+ Author-email: Juan Rael Corrales <raelcorrales@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/BuhoZurdo/fhir-lite
8
+ Project-URL: Repository, https://github.com/BuhoZurdo/fhir-lite.git
9
+ Project-URL: Bug Tracker, https://github.com/BuhoZurdo/fhir-lite/issues
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Healthcare Industry
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ Provides-Extra: pydantic
25
+ Requires-Dist: pydantic>=2.0; extra == "pydantic"
26
+ Provides-Extra: all
27
+ Requires-Dist: pydantic>=2.0; extra == "all"
28
+ Requires-Dist: pytest>=7.0; extra == "all"
29
+ Requires-Dist: pytest-cov>=4.0; extra == "all"
30
+
31
+ # FHIR Lite
32
+
33
+ [![Python](https://img.shields.io/badge/Python-3.9%2B-blue.svg)](https://www.python.org/)
34
+ [![Dependencies](https://img.shields.io/badge/Dependencies-Zero%20(stdlib%20only)-success.svg)]()
35
+ [![codecov](https://codecov.io/gh/buhozurdo/fhir-lite/branch/main/graph/badge.svg)](https://codecov.io/gh/buhozurdo/fhir-lite)
36
+ [![License](https://img.shields.io/badge/License-MIT-green.svg)]()
37
+
38
+ **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.
39
+
40
+ 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).
41
+
42
+ ---
43
+
44
+ ## Features
45
+
46
+ * **Zero Dependencies:** Relies exclusively on Python's standard library (`json` and `xml.etree.ElementTree`). No `pip install` bloat or supply-chain baggage.
47
+ * **Serverless-Friendly:** Weighs only a few kilobytes with near-zero cold-start overhead.
48
+ * **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.
49
+ * **Extensible Object-Oriented Architecture:** Base `FHIRResource` class with dictionary/attribute access, automatic subclass registration, and custom validation hooks (includes pre-built `Patient` and `Observation`).
50
+
51
+ ---
52
+
53
+ ## Installation
54
+
55
+ Because **FHIR Lite** has zero external dependencies, you can simply vendor the `fhir_lite` directory into your project, or install locally:
56
+
57
+ ```bash
58
+ # Clone the repository
59
+ git clone https://github.com/BuhoZurdo/fhir-lite.git
60
+
61
+ # Or copy `fhir_lite/` directly into your AWS Lambda layer or service package
62
+ ```
63
+
64
+ ---
65
+
66
+ ## Quick Start
67
+
68
+ ### 1. Direct JSON $\leftrightarrow$ XML Conversion
69
+
70
+ Transform payloads directly without instantiating resource classes—ideal for proxy microservices, API gateways, and ETL pipelines:
71
+
72
+ ```python
73
+ from fhir_lite import json_to_xml, xml_to_json
74
+
75
+ # Convert FHIR JSON to formatted FHIR XML
76
+ fhir_json = '''{
77
+ "resourceType": "Patient",
78
+ "id": "pat-001",
79
+ "active": true,
80
+ "gender": "male"
81
+ }'''
82
+
83
+ xml_output = json_to_xml(fhir_json, pretty=True)
84
+ print(xml_output)
85
+ # Output:
86
+ # <Patient xmlns="http://hl7.org/fhir">
87
+ # <id value="pat-001" />
88
+ # <active value="true" />
89
+ # <gender value="male" />
90
+ # </Patient>
91
+
92
+ # Convert back from XML to JSON
93
+ json_output = xml_to_json(xml_output, indent=2)
94
+ ```
95
+
96
+ ---
97
+
98
+ ### 2. Working with Resources (`Patient`, `Observation`)
99
+
100
+ Access fields via attributes or dictionary keys with built-in validation:
101
+
102
+ ```python
103
+ from fhir_lite import Patient, Observation
104
+
105
+ # Initialize with keyword arguments or dictionaries
106
+ patient = Patient(
107
+ id="pat-100",
108
+ active=True,
109
+ gender="female",
110
+ name=[{"use": "official", "family": "Smith", "given": ["Jane"]}]
111
+ )
112
+
113
+ # Access fields seamlessly
114
+ print(patient.id) # "pat-100"
115
+ print(patient["gender"]) # "female"
116
+ print(patient.is_valid) # True
117
+
118
+ # Safe deep path traversal (dot-notation or key sequences)
119
+ print(patient.get_path("name.0.family")) # "Smith"
120
+ print(patient.get_path("name.0.given.0")) # "Jane"
121
+ print(patient.get_path("missing.field", default="N/A")) # "N/A"
122
+
123
+ # Semantic extractors for identifiers and medical codes
124
+ print(patient.get_identifier(system="http://hospital.org/mrn")) # "MRN-123"
125
+ # print(obs.get_coding(system="http://loinc.org")) # "883-9"
126
+
127
+ # Export to JSON or XML
128
+ print(patient.to_json())
129
+ print(patient.to_xml())
130
+ ```
131
+
132
+ ---
133
+
134
+ ### 3. Dynamic Deserialization (`from_json` / `from_xml`)
135
+
136
+ The library automatically detects the `resourceType` and instantiates the registered subclass:
137
+
138
+ ```python
139
+ from fhir_lite import from_json, from_xml, Patient, Observation
140
+
141
+ # Automatically instantiates a Patient
142
+ res = from_json('{"resourceType": "Patient", "id": "p1", "gender": "male"}')
143
+ assert isinstance(res, Patient)
144
+
145
+ # Automatically instantiates an Observation
146
+ xml_data = '<Observation xmlns="http://hl7.org/fhir"><id value="obs-1"/><status value="final"/><code/></Observation>'
147
+ obs = from_xml(xml_data)
148
+ assert isinstance(obs, Observation)
149
+ ```
150
+
151
+ ---
152
+
153
+ ### 4. Creating Custom Resources
154
+
155
+ Inheriting from `FHIRResource` automatically registers the new resource type with the dynamic deserializer and validator:
156
+
157
+ ```python
158
+ from fhir_lite import FHIRResource
159
+
160
+ class CarePlan(FHIRResource):
161
+ resource_type = "CarePlan"
162
+ array_fields = {"category", "activity", "note"}
163
+
164
+ def validate(self) -> list[str]:
165
+ errors = super().validate()
166
+ if "status" not in self.data:
167
+ errors.append("CarePlan requires 'status'")
168
+ return errors
169
+
170
+ # Usage
171
+ plan = CarePlan(id="cp-01", status="active")
172
+ print(plan.is_valid) # True
173
+ print(plan.to_xml())
174
+ ```
175
+
176
+ ---
177
+
178
+ ### 5. FHIR Bulk Data (NDJSON Streaming)
179
+
180
+ 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:
181
+
182
+ ```python
183
+ from fhir_lite import iter_ndjson, write_ndjson
184
+
185
+ # Stream resources from plain or gzipped NDJSON
186
+ for resource in iter_ndjson("patients.ndjson.gz"):
187
+ if resource.is_valid:
188
+ print(f"Processed: {resource.resource_type}/{resource.id}")
189
+
190
+ # Stream write resources to a compressed file
191
+ write_ndjson([patient, observation], "export.ndjson.gz")
192
+ ```
193
+
194
+ ---
195
+
196
+ ### 6. Zero-Dependency REST Client (`FHIRClient`)
197
+
198
+ Interact with FHIR servers (e.g. HAPI, AWS HealthLake, Google Healthcare) using Python's standard library `urllib` without installing `requests` or `httpx`:
199
+
200
+ ```python
201
+ from fhir_lite import FHIRClient, Patient, Bundle
202
+
203
+ client = FHIRClient(
204
+ base_url="https://hapi.fhir.org/baseR4",
205
+ auth="my-bearer-token", # or auth=("user", "password")
206
+ max_retries=3, # Automatic retry on 429 (rate limit), 502, 503, 504
207
+ backoff_factor=0.5, # Exponential backoff + Retry-After header parsing
208
+ )
209
+
210
+ # Fetch a resource by ID (auto-instantiates typed Patient)
211
+ patient = client.read(Patient, "12345")
212
+
213
+ # Conditional Create (If-None-Exist) & Idempotent get_or_create
214
+ patient, created = client.get_or_create(patient, identifier="http://hospital.org/mrn|12345")
215
+
216
+ # FHIR JSON Patch (partial updates without race conditions)
217
+ client.patch(Patient, patient.id, [
218
+ {"op": "replace", "path": "/active", "value": False}
219
+ ])
220
+
221
+ # Automatic multi-page search iterator (follows bundle.link 'next')
222
+ for pat in client.iter_search(Patient, family="Smith", max_pages=5):
223
+ print(pat.id)
224
+
225
+ # Fluent Transaction & Batch Builder (POST [base])
226
+ tx = Bundle.transaction()
227
+ tx.add_create(Patient(gender="female", active=True))
228
+ tx.add_delete(Patient, "old-patient-id")
229
+ tx_response = client.transaction(tx)
230
+ ```
231
+
232
+ ---
233
+
234
+ ### 7. Optional Pydantic Interoperability (Soft Dependency)
235
+
236
+ `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:
237
+
238
+ ```python
239
+ from pydantic import BaseModel
240
+ from fhir_lite import FHIRResource
241
+
242
+ class MyPatientModel(BaseModel):
243
+ resourceType: str = "Patient"
244
+ id: str
245
+ active: bool = True
246
+ gender: str
247
+
248
+ # 1. Convert any Pydantic model into a typed FHIRResource
249
+ pyd_patient = MyPatientModel(id="pat-pyd-1", gender="female")
250
+ resource = FHIRResource.from_pydantic(pyd_patient)
251
+
252
+ # Now enjoy all fhir-lite features: lossless XML conversion, validation, NDJSON streaming
253
+ xml_data = resource.to_xml()
254
+
255
+ # 2. Convert a FHIRResource back into your Pydantic model
256
+ pyd_again = resource.to_pydantic(MyPatientModel)
257
+ ```
258
+
259
+ ---
260
+
261
+ ### 8. FHIR Reference Helpers (`Reference`)
262
+
263
+ Parse and build FHIR reference strings and dictionaries with ease:
264
+
265
+ ```python
266
+ from fhir_lite import Reference, Patient
267
+
268
+ # Parse string, absolute URL, or dictionary
269
+ ref = Reference.parse("Patient/12345")
270
+ print(ref.resource_type) # "Patient"
271
+ print(ref.id) # "12345"
272
+
273
+ # Create valid reference dictionaries
274
+ ref_dict = Reference.create(Patient, "12345", display="Jane Doe")
275
+ # {"reference": "Patient/12345", "display": "Jane Doe"}
276
+ ```
277
+
278
+ ---
279
+
280
+ ## Testing
281
+
282
+ Run the included standalone test suites (no third-party test runners needed):
283
+
284
+ ```bash
285
+ python -m tests.test_fhir_lite
286
+ python -m tests.test_security
287
+ python -m tests.test_ndjson
288
+ python -m tests.test_client
289
+ python -m tests.test_typing
290
+ python -m tests.test_version
291
+ python -m tests.test_operation_outcome
292
+ python -m tests.test_optimization
293
+ python -m tests.test_pydantic_interop
294
+ python -m tests.test_reference_and_path
295
+ python -m tests.test_advanced_features
296
+ ```
297
+
298
+ ---
299
+
300
+ ## Project Structure
301
+
302
+ ```text
303
+ fhir-lite/
304
+ ├── fhir_lite/
305
+ │ ├── __init__.py # Public package interface
306
+ │ ├── client.py # Zero-dependency FHIR REST client (urllib) & FHIRError
307
+ │ ├── ndjson.py # Streaming NDJSON Bulk Data reader/writer (gzip support)
308
+ │ ├── py.typed # PEP 561 inline typing marker
309
+ │ ├── resources.py # Core resources (Patient, Observation, Bundle, OperationOutcome, etc.)
310
+ │ ├── serializer.py # Fast ElementTree/JSON converter (XXE/DoS protected, primitive extensions)
311
+ │ ├── types.py # TypedDict definitions for common FHIR structures
312
+ │ └── version.py # FHIRVersion (R4, R4B, R5) declarations and context manager
313
+ ├── tests/
314
+ │ ├── test_client.py # Mocked FHIR REST client tests
315
+ │ ├── test_fhir_lite.py # Core resource, validation, and extension test suite
316
+ │ ├── test_ndjson.py # Streaming & gzip bulk data tests
317
+ │ ├── test_operation_outcome.py # OperationOutcome & error integration tests
318
+ │ ├── test_security.py # XXE, DTD, and parser security tests
319
+ │ ├── test_typing.py # PEP 561 & TypedDict tests
320
+ │ └── test_version.py # FHIR R4/R5 version context & alias tests
321
+ ├── pyproject.toml # PEP 517/621 packaging metadata
322
+ └── README.md
323
+ ```
324
+
325
+ ## License
326
+
327
+ MIT
@@ -0,0 +1,297 @@
1
+ # FHIR Lite
2
+
3
+ [![Python](https://img.shields.io/badge/Python-3.9%2B-blue.svg)](https://www.python.org/)
4
+ [![Dependencies](https://img.shields.io/badge/Dependencies-Zero%20(stdlib%20only)-success.svg)]()
5
+ [![codecov](https://codecov.io/gh/buhozurdo/fhir-lite/branch/main/graph/badge.svg)](https://codecov.io/gh/buhozurdo/fhir-lite)
6
+ [![License](https://img.shields.io/badge/License-MIT-green.svg)]()
7
+
8
+ **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.
9
+
10
+ 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).
11
+
12
+ ---
13
+
14
+ ## Features
15
+
16
+ * **Zero Dependencies:** Relies exclusively on Python's standard library (`json` and `xml.etree.ElementTree`). No `pip install` bloat or supply-chain baggage.
17
+ * **Serverless-Friendly:** Weighs only a few kilobytes with near-zero cold-start overhead.
18
+ * **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.
19
+ * **Extensible Object-Oriented Architecture:** Base `FHIRResource` class with dictionary/attribute access, automatic subclass registration, and custom validation hooks (includes pre-built `Patient` and `Observation`).
20
+
21
+ ---
22
+
23
+ ## Installation
24
+
25
+ Because **FHIR Lite** has zero external dependencies, you can simply vendor the `fhir_lite` directory into your project, or install locally:
26
+
27
+ ```bash
28
+ # Clone the repository
29
+ git clone https://github.com/BuhoZurdo/fhir-lite.git
30
+
31
+ # Or copy `fhir_lite/` directly into your AWS Lambda layer or service package
32
+ ```
33
+
34
+ ---
35
+
36
+ ## Quick Start
37
+
38
+ ### 1. Direct JSON $\leftrightarrow$ XML Conversion
39
+
40
+ Transform payloads directly without instantiating resource classes—ideal for proxy microservices, API gateways, and ETL pipelines:
41
+
42
+ ```python
43
+ from fhir_lite import json_to_xml, xml_to_json
44
+
45
+ # Convert FHIR JSON to formatted FHIR XML
46
+ fhir_json = '''{
47
+ "resourceType": "Patient",
48
+ "id": "pat-001",
49
+ "active": true,
50
+ "gender": "male"
51
+ }'''
52
+
53
+ xml_output = json_to_xml(fhir_json, pretty=True)
54
+ print(xml_output)
55
+ # Output:
56
+ # <Patient xmlns="http://hl7.org/fhir">
57
+ # <id value="pat-001" />
58
+ # <active value="true" />
59
+ # <gender value="male" />
60
+ # </Patient>
61
+
62
+ # Convert back from XML to JSON
63
+ json_output = xml_to_json(xml_output, indent=2)
64
+ ```
65
+
66
+ ---
67
+
68
+ ### 2. Working with Resources (`Patient`, `Observation`)
69
+
70
+ Access fields via attributes or dictionary keys with built-in validation:
71
+
72
+ ```python
73
+ from fhir_lite import Patient, Observation
74
+
75
+ # Initialize with keyword arguments or dictionaries
76
+ patient = Patient(
77
+ id="pat-100",
78
+ active=True,
79
+ gender="female",
80
+ name=[{"use": "official", "family": "Smith", "given": ["Jane"]}]
81
+ )
82
+
83
+ # Access fields seamlessly
84
+ print(patient.id) # "pat-100"
85
+ print(patient["gender"]) # "female"
86
+ print(patient.is_valid) # True
87
+
88
+ # Safe deep path traversal (dot-notation or key sequences)
89
+ print(patient.get_path("name.0.family")) # "Smith"
90
+ print(patient.get_path("name.0.given.0")) # "Jane"
91
+ print(patient.get_path("missing.field", default="N/A")) # "N/A"
92
+
93
+ # Semantic extractors for identifiers and medical codes
94
+ print(patient.get_identifier(system="http://hospital.org/mrn")) # "MRN-123"
95
+ # print(obs.get_coding(system="http://loinc.org")) # "883-9"
96
+
97
+ # Export to JSON or XML
98
+ print(patient.to_json())
99
+ print(patient.to_xml())
100
+ ```
101
+
102
+ ---
103
+
104
+ ### 3. Dynamic Deserialization (`from_json` / `from_xml`)
105
+
106
+ The library automatically detects the `resourceType` and instantiates the registered subclass:
107
+
108
+ ```python
109
+ from fhir_lite import from_json, from_xml, Patient, Observation
110
+
111
+ # Automatically instantiates a Patient
112
+ res = from_json('{"resourceType": "Patient", "id": "p1", "gender": "male"}')
113
+ assert isinstance(res, Patient)
114
+
115
+ # Automatically instantiates an Observation
116
+ xml_data = '<Observation xmlns="http://hl7.org/fhir"><id value="obs-1"/><status value="final"/><code/></Observation>'
117
+ obs = from_xml(xml_data)
118
+ assert isinstance(obs, Observation)
119
+ ```
120
+
121
+ ---
122
+
123
+ ### 4. Creating Custom Resources
124
+
125
+ Inheriting from `FHIRResource` automatically registers the new resource type with the dynamic deserializer and validator:
126
+
127
+ ```python
128
+ from fhir_lite import FHIRResource
129
+
130
+ class CarePlan(FHIRResource):
131
+ resource_type = "CarePlan"
132
+ array_fields = {"category", "activity", "note"}
133
+
134
+ def validate(self) -> list[str]:
135
+ errors = super().validate()
136
+ if "status" not in self.data:
137
+ errors.append("CarePlan requires 'status'")
138
+ return errors
139
+
140
+ # Usage
141
+ plan = CarePlan(id="cp-01", status="active")
142
+ print(plan.is_valid) # True
143
+ print(plan.to_xml())
144
+ ```
145
+
146
+ ---
147
+
148
+ ### 5. FHIR Bulk Data (NDJSON Streaming)
149
+
150
+ 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:
151
+
152
+ ```python
153
+ from fhir_lite import iter_ndjson, write_ndjson
154
+
155
+ # Stream resources from plain or gzipped NDJSON
156
+ for resource in iter_ndjson("patients.ndjson.gz"):
157
+ if resource.is_valid:
158
+ print(f"Processed: {resource.resource_type}/{resource.id}")
159
+
160
+ # Stream write resources to a compressed file
161
+ write_ndjson([patient, observation], "export.ndjson.gz")
162
+ ```
163
+
164
+ ---
165
+
166
+ ### 6. Zero-Dependency REST Client (`FHIRClient`)
167
+
168
+ Interact with FHIR servers (e.g. HAPI, AWS HealthLake, Google Healthcare) using Python's standard library `urllib` without installing `requests` or `httpx`:
169
+
170
+ ```python
171
+ from fhir_lite import FHIRClient, Patient, Bundle
172
+
173
+ client = FHIRClient(
174
+ base_url="https://hapi.fhir.org/baseR4",
175
+ auth="my-bearer-token", # or auth=("user", "password")
176
+ max_retries=3, # Automatic retry on 429 (rate limit), 502, 503, 504
177
+ backoff_factor=0.5, # Exponential backoff + Retry-After header parsing
178
+ )
179
+
180
+ # Fetch a resource by ID (auto-instantiates typed Patient)
181
+ patient = client.read(Patient, "12345")
182
+
183
+ # Conditional Create (If-None-Exist) & Idempotent get_or_create
184
+ patient, created = client.get_or_create(patient, identifier="http://hospital.org/mrn|12345")
185
+
186
+ # FHIR JSON Patch (partial updates without race conditions)
187
+ client.patch(Patient, patient.id, [
188
+ {"op": "replace", "path": "/active", "value": False}
189
+ ])
190
+
191
+ # Automatic multi-page search iterator (follows bundle.link 'next')
192
+ for pat in client.iter_search(Patient, family="Smith", max_pages=5):
193
+ print(pat.id)
194
+
195
+ # Fluent Transaction & Batch Builder (POST [base])
196
+ tx = Bundle.transaction()
197
+ tx.add_create(Patient(gender="female", active=True))
198
+ tx.add_delete(Patient, "old-patient-id")
199
+ tx_response = client.transaction(tx)
200
+ ```
201
+
202
+ ---
203
+
204
+ ### 7. Optional Pydantic Interoperability (Soft Dependency)
205
+
206
+ `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:
207
+
208
+ ```python
209
+ from pydantic import BaseModel
210
+ from fhir_lite import FHIRResource
211
+
212
+ class MyPatientModel(BaseModel):
213
+ resourceType: str = "Patient"
214
+ id: str
215
+ active: bool = True
216
+ gender: str
217
+
218
+ # 1. Convert any Pydantic model into a typed FHIRResource
219
+ pyd_patient = MyPatientModel(id="pat-pyd-1", gender="female")
220
+ resource = FHIRResource.from_pydantic(pyd_patient)
221
+
222
+ # Now enjoy all fhir-lite features: lossless XML conversion, validation, NDJSON streaming
223
+ xml_data = resource.to_xml()
224
+
225
+ # 2. Convert a FHIRResource back into your Pydantic model
226
+ pyd_again = resource.to_pydantic(MyPatientModel)
227
+ ```
228
+
229
+ ---
230
+
231
+ ### 8. FHIR Reference Helpers (`Reference`)
232
+
233
+ Parse and build FHIR reference strings and dictionaries with ease:
234
+
235
+ ```python
236
+ from fhir_lite import Reference, Patient
237
+
238
+ # Parse string, absolute URL, or dictionary
239
+ ref = Reference.parse("Patient/12345")
240
+ print(ref.resource_type) # "Patient"
241
+ print(ref.id) # "12345"
242
+
243
+ # Create valid reference dictionaries
244
+ ref_dict = Reference.create(Patient, "12345", display="Jane Doe")
245
+ # {"reference": "Patient/12345", "display": "Jane Doe"}
246
+ ```
247
+
248
+ ---
249
+
250
+ ## Testing
251
+
252
+ Run the included standalone test suites (no third-party test runners needed):
253
+
254
+ ```bash
255
+ python -m tests.test_fhir_lite
256
+ python -m tests.test_security
257
+ python -m tests.test_ndjson
258
+ python -m tests.test_client
259
+ python -m tests.test_typing
260
+ python -m tests.test_version
261
+ python -m tests.test_operation_outcome
262
+ python -m tests.test_optimization
263
+ python -m tests.test_pydantic_interop
264
+ python -m tests.test_reference_and_path
265
+ python -m tests.test_advanced_features
266
+ ```
267
+
268
+ ---
269
+
270
+ ## Project Structure
271
+
272
+ ```text
273
+ fhir-lite/
274
+ ├── fhir_lite/
275
+ │ ├── __init__.py # Public package interface
276
+ │ ├── client.py # Zero-dependency FHIR REST client (urllib) & FHIRError
277
+ │ ├── ndjson.py # Streaming NDJSON Bulk Data reader/writer (gzip support)
278
+ │ ├── py.typed # PEP 561 inline typing marker
279
+ │ ├── resources.py # Core resources (Patient, Observation, Bundle, OperationOutcome, etc.)
280
+ │ ├── serializer.py # Fast ElementTree/JSON converter (XXE/DoS protected, primitive extensions)
281
+ │ ├── types.py # TypedDict definitions for common FHIR structures
282
+ │ └── version.py # FHIRVersion (R4, R4B, R5) declarations and context manager
283
+ ├── tests/
284
+ │ ├── test_client.py # Mocked FHIR REST client tests
285
+ │ ├── test_fhir_lite.py # Core resource, validation, and extension test suite
286
+ │ ├── test_ndjson.py # Streaming & gzip bulk data tests
287
+ │ ├── test_operation_outcome.py # OperationOutcome & error integration tests
288
+ │ ├── test_security.py # XXE, DTD, and parser security tests
289
+ │ ├── test_typing.py # PEP 561 & TypedDict tests
290
+ │ └── test_version.py # FHIR R4/R5 version context & alias tests
291
+ ├── pyproject.toml # PEP 517/621 packaging metadata
292
+ └── README.md
293
+ ```
294
+
295
+ ## License
296
+
297
+ MIT