CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-fhir--resources

FHIR Resources as Model Classes - Python classes for all FHIR resources with validation and serialization

Pending
Overview
Eval results
Files

serialization.mddocs/

Serialization

Multi-format serialization supporting JSON, XML, and YAML with flexible parsing from strings, bytes, or files. All FHIR resources support comprehensive serialization capabilities for data exchange and storage.

Capabilities

JSON Serialization

Native JSON serialization with support for FHIR-compliant JSON format and optional high-performance processing.

# Instance methods for JSON serialization
def json(self, **kwargs) -> str:
    """
    Serialize FHIR resource to JSON string.
    
    Parameters:
    - by_alias: bool - Use field aliases in output (default: None)
    - exclude_none: bool - Exclude None/null values (default: None)
    - exclude_comments: bool - Exclude comment fields (default: False)
    - encoder: Callable - Custom JSON encoder function (default: None)
    - return_bytes: bool - Return bytes instead of string (default: False)
    
    Returns:
    str - JSON representation of the resource
    """

# Class methods for JSON parsing
@classmethod
def parse_raw(cls, data: Union[str, bytes], content_type: str = None):
    """
    Parse FHIR resource from JSON string or bytes.
    
    Parameters:
    - data: Union[str, bytes] - JSON data to parse
    - content_type: str - Content type hint (default: application/json)
    
    Returns:
    FHIRAbstractModel - Parsed and validated FHIR resource
    
    Raises:
    ValidationError - If data doesn't conform to FHIR specification
    """

@classmethod
def parse_obj(cls, data: Dict[str, Any]):
    """
    Parse FHIR resource from Python dictionary.
    
    Parameters:
    - data: Dict[str, Any] - Dictionary representation of FHIR resource
    
    Returns:
    FHIRAbstractModel - Parsed and validated FHIR resource
    """

Usage Examples:

from fhir.resources.patient import Patient
from fhir.resources.humanname import HumanName
import json

# Create patient resource
patient = Patient(
    id="patient-001",
    active=True,
    name=[HumanName(family="Doe", given=["John"])]
)

# Serialize to JSON
json_compact = patient.json()
json_pretty = patient.json(indent=2)

# Parse from JSON string
json_data = '{"resourceType": "Patient", "id": "123", "active": true}'
patient_from_json = Patient.parse_raw(json_data)

# Parse from dictionary
patient_dict = {
    "resourceType": "Patient",
    "id": "456",
    "active": True,
    "name": [{"family": "Smith", "given": ["Jane"]}]
}
patient_from_dict = Patient.parse_obj(patient_dict)

# Handle validation errors
try:
    invalid_patient = Patient.parse_raw('{"invalid": "data"}')
except ValidationError as e:
    print(f"Validation error: {e}")

XML Serialization

XML serialization supporting FHIR XML format with full compliance to FHIR specification.

def xml(self, **kwargs) -> str:
    """
    Serialize FHIR resource to XML string.
    
    Parameters:
    - exclude_comments: bool - Exclude comment fields (default: False)
    - pretty_print: bool - Format XML with indentation (default: False)
    - xml_declaration: bool - Include XML declaration (default: True)
    
    Returns:
    str - XML representation of the resource
    
    Requires:
    lxml - Install with 'pip install fhir.resources[xml]'
    """

@classmethod
def parse_raw(cls, data: Union[str, bytes], content_type: str = "application/xml"):
    """
    Parse FHIR resource from XML string or bytes.
    
    Parameters:
    - data: Union[str, bytes] - XML data to parse
    - content_type: str - Must be 'application/xml' or 'text/xml'
    
    Returns:
    FHIRAbstractModel - Parsed and validated FHIR resource
    """

Usage Examples:

from fhir.resources.patient import Patient

# Create patient
patient = Patient(
    id="patient-001",
    active=True
)

# Serialize to XML (requires lxml)
try:
    xml_compact = patient.xml()
    xml_pretty = patient.xml(pretty_print=True)
    print(xml_pretty)
except ImportError:
    print("Install lxml: pip install fhir.resources[xml]")

# Parse from XML
xml_data = '''<?xml version="1.0" encoding="UTF-8"?>
<Patient xmlns="http://hl7.org/fhir">
    <id value="123"/>
    <active value="true"/>
</Patient>'''

try:
    patient_from_xml = Patient.parse_raw(xml_data, content_type="application/xml")
except ImportError:
    print("XML parsing requires lxml")

YAML Serialization

YAML serialization for human-readable configuration and data files.

def yaml(self, **kwargs) -> str:
    """
    Serialize FHIR resource to YAML string.
    
    Parameters:
    - by_alias: bool - Use field aliases in output (default: None)
    - exclude_none: bool - Exclude None/null values (default: None)
    - exclude_comments: bool - Exclude comment fields (default: False)
    
    Returns:
    str - YAML representation of the resource
    
    Requires:
    PyYAML - Install with 'pip install fhir.resources[yaml]'
    """

@classmethod
def parse_raw(cls, data: Union[str, bytes], content_type: str = "application/yaml"):
    """
    Parse FHIR resource from YAML string or bytes.
    
    Parameters:
    - data: Union[str, bytes] - YAML data to parse
    - content_type: str - Must be 'application/yaml' or 'text/yaml'
    
    Returns:
    FHIRAbstractModel - Parsed and validated FHIR resource
    """

Usage Examples:

from fhir.resources.patient import Patient

patient = Patient(
    id="patient-001",
    active=True,
    name=[HumanName(family="Doe", given=["John"])]
)

# Serialize to YAML (requires PyYAML)
try:
    yaml_output = patient.yaml()
    print(yaml_output)
except ImportError:
    print("Install PyYAML: pip install fhir.resources[yaml]")

# Parse from YAML
yaml_data = """
resourceType: Patient
id: patient-123
active: true
name:
  - family: Smith
    given:
      - Jane
"""

try:
    patient_from_yaml = Patient.parse_raw(yaml_data, content_type="application/yaml")
except ImportError:
    print("YAML parsing requires PyYAML")

File Operations

Direct file parsing and writing with automatic format detection based on file extension.

@classmethod
def parse_file(cls, path: Union[str, Path], **kwargs):
    """
    Parse FHIR resource from file.
    
    Parameters:
    - path: Union[str, Path] - File path to parse
    - content_type: str - Override content type detection
    - encoding: str - File encoding (default: utf-8)
    
    Returns:
    FHIRAbstractModel - Parsed and validated FHIR resource
    
    Supported formats:
    - .json - JSON format
    - .xml - XML format (requires lxml)
    - .yaml, .yml - YAML format (requires PyYAML)
    """

def write_file(self, path: Union[str, Path], format: str = None, **kwargs):
    """
    Write FHIR resource to file.
    
    Parameters:
    - path: Union[str, Path] - Output file path
    - format: str - Override format detection ('json', 'xml', 'yaml')
    - encoding: str - File encoding (default: utf-8)
    - **kwargs: Format-specific options
    """

Usage Examples:

from fhir.resources.patient import Patient
from pathlib import Path

patient = Patient(
    id="patient-001",
    active=True
)

# Parse from files
patient_json = Patient.parse_file("patient.json")
patient_xml = Patient.parse_file("patient.xml")  # requires lxml
patient_yaml = Patient.parse_file("patient.yaml")  # requires PyYAML

# Write to files with automatic format detection
patient.write_file("output.json")
patient.write_file("output.xml", pretty=True)  # requires lxml
patient.write_file("output.yaml")  # requires PyYAML

# Explicit format specification
patient.write_file("patient_data.txt", format="json", indent=2)

# Using pathlib
output_path = Path("data") / "patient.json"
patient.write_file(output_path)

Dictionary Conversion

Convert FHIR resources to and from Python dictionaries for programmatic manipulation.

def dict(self, **kwargs) -> Dict[str, Any]:
    """
    Convert FHIR resource to Python dictionary.
    
    Parameters:
    - include_defaults: bool - Include fields with default values
    - exclude_none: bool - Exclude None/null values (default: True)
    - by_alias: bool - Use field aliases (default: True)
    
    Returns:
    Dict[str, Any] - Dictionary representation of the resource
    """

@classmethod
def from_dict(cls, data: Dict[str, Any], **kwargs):
    """
    Create FHIR resource from Python dictionary.
    
    Parameters:
    - data: Dict[str, Any] - Dictionary data
    
    Returns:
    FHIRAbstractModel - FHIR resource instance
    """

Usage Examples:

from fhir.resources.patient import Patient

patient = Patient(
    id="patient-001",
    active=True
)

# Convert to dictionary
patient_dict = patient.dict()
patient_dict_full = patient.dict(include_defaults=True)

# Create from dictionary
new_patient = Patient.from_dict(patient_dict)

# Modify dictionary and recreate
patient_dict["active"] = False
modified_patient = Patient.from_dict(patient_dict)

Performance Options

High-performance JSON processing with optional orjson library for faster serialization.

# Enhanced JSON performance (optional)
# Install with: pip install fhir.resources[orjson]

def json(self, use_orjson: bool = True, **kwargs) -> str:
    """
    Serialize with optional orjson for better performance.
    
    Parameters:
    - use_orjson: bool - Use orjson if available (default: True)
    
    Performance benefits:
    - Up to 3x faster JSON serialization
    - Lower memory usage
    - Better handling of datetime objects
    """

Usage Example:

from fhir.resources.patient import Patient
import time

patient = Patient(id="test", active=True)

# Benchmark JSON serialization
start = time.time()
for _ in range(1000):
    json_data = patient.json()  # Uses orjson if available
end = time.time()

print(f"Serialization time: {end - start:.3f}s")

Types

from typing import Union, Dict, Any, Optional
from pathlib import Path
from pydantic import ValidationError

# Type aliases for serialization methods
DataInput = Union[str, bytes, Dict[str, Any], Path]
SerializationFormat = Literal["json", "xml", "yaml"]
ContentType = Literal["application/json", "application/xml", "text/xml", "application/yaml", "text/yaml"]

# Common serialization errors
class SerializationError(Exception):
    """Base exception for serialization errors"""

class ValidationError(Exception):
    """Pydantic validation error for invalid FHIR data"""

Install with Tessl CLI

npx tessl i tessl/pypi-fhir--resources

docs

administrative-resources.md

clinical-resources.md

core-functions.md

data-types.md

financial-resources.md

index.md

patient-resources.md

serialization.md

version-support.md

tile.json