Skip to content

Itisfilipe/ccdakit

ccdakit

Python Library for HL7 C-CDA Clinical Document Generation

License: MIT Python 3.8+ Ruff Tests Coverage

ccdakit is a Python library for programmatic generation of HL7 C-CDA (Consolidated Clinical Document Architecture) documents. Built with type safety, protocol-oriented design, and multi-version support for healthcare interoperability.

from ccdakit import ClinicalDocument, ProblemsSection, CDAVersion

doc = ClinicalDocument(
    patient=patient_data,
    sections=[ProblemsSection(problems=problems_list)],
    version=CDAVersion.R2_1
)

xml = doc.to_string()  # Standards-compliant C-CDA R2.1 XML

Why ccdakit?

Existing approaches to C-CDA generation have significant limitations:

Challenge ccdakit Solution
Template engines (Jinja, XSLT) are verbose and hard to validate Pure Python builders with full type safety
String manipulation is error-prone Structured builders with IDE autocomplete
Single version support limits flexibility Multi-version support (R2.1, R2.0)
Vendor lock-in to specific EHR systems Protocol-based design works with any data model
Manual validation catches errors late Built-in XSD validation at generation time
Difficult to compose and reuse logic Composable section builders

ccdakit provides a modern, Pythonic approach to C-CDA document generation suitable for EHR systems, health information exchanges, and healthcare applications.


Installation

Standard Installation

pip install ccdakit

With Optional Dependencies

# Include validation tools
pip install ccdakit[validation]

# Include development dependencies
pip install ccdakit[dev]

# All extras
pip install ccdakit[dev,validation,docs]

For Contributors

This project uses uv for dependency management:

# Install uv
curl -LsSf https://astral.sh/uv/install.sh | sh

# Clone repository
git clone https://github.com/Itisfilipe/ccdakit.git
cd ccdakit

# Install dependencies
uv sync --all-extras

# Run test suite
uv run pytest

See Development Setup for complete instructions.


Quick Start

Basic Document Generation

from ccdakit import ClinicalDocument, ProblemsSection, CDAVersion
from datetime import date

# Define your data model (or use existing models)
class Problem:
    name = "Type 2 Diabetes Mellitus"
    code = "44054006"
    code_system = "SNOMED"
    status = "active"
    onset_date = date(2020, 3, 15)

# Generate C-CDA document
doc = ClinicalDocument(
    patient=patient,
    sections=[ProblemsSection(problems=[Problem()])],
    version=CDAVersion.R2_1
)

# Output XML
xml_string = doc.to_string(pretty=True)

Multiple Sections

from ccdakit import (
    ClinicalDocument,
    ProblemsSection,
    MedicationsSection,
    AllergiesSection,
    VitalSignsSection,
)

doc = ClinicalDocument(
    patient=patient_data,
    author=provider_data,
    custodian=organization_data,
    sections=[
        ProblemsSection(problems=problems_list),
        MedicationsSection(medications=medications_list),
        AllergiesSection(allergies=allergies_list),
        VitalSignsSection(vital_signs_organizers=vitals_list),
    ],
    version=CDAVersion.R2_1
)

Validation

from ccdakit.validators import XSDValidator, SchematronValidator

# XSD structural validation
xsd_validator = XSDValidator()
result = xsd_validator.validate(xml_string)

# Schematron business rule validation (auto-downloads on first use)
schematron_validator = SchematronValidator()
result = schematron_validator.validate(xml_string)

if result.is_valid:
    print("Document is valid")
else:
    for issue in result.errors:
        print(f"Error: {issue.message}")

Complete examples: examples/generate_ccda.py


Key Features

Comprehensive Section Support

39 complete C-CDA sections organized by clinical purpose:

Core Clinical Sections (9)

  • Problems, Medications, Allergies, Immunizations, Vital Signs, Procedures, Results, Social History, Encounters

Extended Clinical Sections (9)

  • Family History, Functional Status, Mental Status, Goals, Health Concerns, Health Status Evaluations, Past Medical History, Physical Exam, Assessment and Plan

Specialized/Administrative Sections (11)

  • Plan of Treatment, Advance Directives, Medical Equipment, Admission/Discharge Medications, Hospital Discharge Instructions, Payers, Nutrition, Reason for Visit, Chief Complaint, Interventions

Hospital and Surgical Sections (10)

  • Admission/Discharge Diagnosis, Hospital Course, Instructions, Anesthesia, Pre/Postoperative Diagnosis, Complications, Hospital Discharge Studies, Medications Administered

See complete section documentation for details.

Protocol-Oriented Design

Works with existing data models without inheritance requirements. Uses Python's structural typing (protocols):

from typing import Protocol

# ccdakit defines the interface
class ProblemProtocol(Protocol):
    @property
    def name(self) -> str: ...
    @property
    def code(self) -> str: ...
    @property
    def status(self) -> str: ...

# Your existing models automatically satisfy the protocol
class DatabaseProblem:
    def __init__(self, db_record):
        self._record = db_record

    @property
    def name(self):
        return self._record.diagnosis_name

    @property
    def code(self):
        return self._record.snomed_code

    @property
    def status(self):
        return self._record.status

# Use directly with ccdakit builders
section = ProblemsSection(problems=[DatabaseProblem(record)])

Multi-Version Support

Generate documents for different C-CDA releases:

# C-CDA R2.1 (current standard)
doc_v21 = ClinicalDocument(..., version=CDAVersion.R2_1)

# C-CDA R2.0 (backward compatibility)
doc_v20 = ClinicalDocument(..., version=CDAVersion.R2_0)

Built-in Validation

XSD schema validation integrated into the generation process:

  • Official HL7 schemas
  • Configurable validation rules
  • Detailed error reporting with line numbers
  • Schematron support with auto-download and cleaning

Automatic Narrative Generation

Generates human-readable narrative text alongside structured data:

section = ProblemsSection(problems=problems_list)

# Automatically generates both:
# 1. Structured <entry> elements with coded data
# 2. Narrative <text> element with HTML table

Architecture

┌──────────────────────────────────────┐
│     Healthcare Application           │
│     (EHR, HIE, Health Platform)      │
└───────────────┬──────────────────────┘
                │ provides data
                ▼
┌──────────────────────────────────────┐
│     ccdakit Protocols                │
│     (Data Contracts)                 │
└───────────────┬──────────────────────┘
                │ implemented by
                ▼
┌──────────────────────────────────────┐
│     Section Builders                 │
│     (Problems, Medications, etc.)    │
└───────────────┬──────────────────────┘
                │ assembled by
                ▼
┌──────────────────────────────────────┐
│     Clinical Document Builder        │
└───────────────┬──────────────────────┘
                │ generates
                ▼
┌──────────────────────────────────────┐
│     Standards-Compliant XML          │
│     (HL7 C-CDA R2.1 / R2.0)         │
└──────────────────────────────────────┘

Design Principles:

  • Separation of Concerns: Data models remain independent of generation logic
  • Type Safety: Full type hints enable static analysis and IDE support
  • Composability: Build complex documents from reusable components
  • Standards Compliance: Follows HL7 C-CDA specifications exactly
  • Testability: Protocol-based design simplifies unit testing

See Architecture Documentation for detailed design decisions.


Project Status

Current Release: 0.1.0-alpha (MVP Complete)

Metric Status
Sections 39 of 82 C-CDA sections implemented (47.6%)
Test Suite 3,825 comprehensive tests
Code Coverage 28%
Documentation Complete API reference + 40-page HL7 guide
Validation XSD validation complete, Schematron validation complete (with auto-cleaning)

Implementation Status

Phase 1: MVP ✓ Complete

  • Core infrastructure and protocols
  • 39 clinical sections (Core, Extended, Specialized, Hospital & Surgical)
  • XSD validation framework
  • Multi-version support (R2.1, R2.0)
  • Comprehensive test coverage
  • Complete documentation

Phase 2: Hospital & Surgical Sections ✓ Complete

  • Admission/Discharge Diagnosis Sections
  • Hospital Course Section
  • Instructions Section
  • Anesthesia Section
  • Pre/Postoperative Diagnosis Sections
  • Complications Section
  • Hospital Discharge Studies Section
  • Medications Administered Section

Phase 3: Enhanced Validation (In Progress)

  • Schematron validation with auto-download and IDREF error fixing
  • ONC C-CDA Validator integration
  • Custom validation rules API
  • Performance optimization

Phase 4: Production Release (Planned)

  • Plugin architecture
  • CLI tooling
  • Performance benchmarks
  • 1.0 stable release

See Roadmap for detailed plans.


Documentation

Comprehensive documentation is available:

Resource Description
Getting Started Installation and first document
HL7/C-CDA Implementation Guide 40-page guide to C-CDA standards
API Reference Complete API documentation
Examples Working code for all sections
Architecture Design decisions and patterns
Contributing Development setup and guidelines

HL7/C-CDA Implementation Guide

We've created a comprehensive implementation guide (40 pages) that bridges official HL7 specifications and practical implementation:

  • Foundation (5 pages): HL7 basics, CDA architecture, templates, code systems
  • Section Guides (30 pages): Complete documentation for all 29 implemented sections
  • Appendices (5 pages): OID reference, conformance rules, glossary

This guide complements official HL7 documentation with practical examples and implementation patterns.

Read the complete guide →


Use Cases

ccdakit is designed for:

Electronic Health Records (EHR)

  • Generate discharge summaries, continuity of care documents, referral notes
  • Support ONC certification requirements
  • Enable standards-based data exchange

Health Information Exchanges (HIE)

  • Create compliant documents for cross-organization data sharing
  • Support multiple C-CDA versions for interoperability
  • Validate documents before transmission

Healthcare Applications

  • Export patient data in C-CDA format
  • Integrate with existing health IT systems
  • Support FHIR-to-CDA conversion workflows

Testing and Validation

  • Generate test documents for validator testing
  • Create synthetic patient data for QA
  • Support conformance testing

Data Migration

  • Convert legacy formats to C-CDA
  • Support system migrations and upgrades
  • Enable data preservation

Testing

Comprehensive test suite with 3,825 tests:

# Run all tests
uv run pytest

# Run with coverage report
uv run pytest --cov=ccdakit --cov-report=html

# Run specific test suite
uv run pytest tests/test_builders/

# Parallel execution for speed
uv run pytest -n auto

See Testing Guide for details.


Contributing

Contributions are welcome. Please review our guidelines:

Before Contributing:

Development Setup:

  1. Fork the repository
  2. Clone your fork
  3. Install dependencies: uv sync --all-extras
  4. Download C-CDA references (see references/README.md)
  5. Create a feature branch
  6. Make changes with tests
  7. Run test suite: uv run pytest
  8. Submit pull request

See Development Setup Guide for complete instructions.


⚠️ Important Disclaimers

Not an Official HL7 Publication

This is NOT an official HL7 product. ccdakit is an independent, community-driven project that is not affiliated with, endorsed by, or officially recognized by HL7 International.

AI-Assisted Development

This project was developed extensively with AI assistance using Claude Code. While we strive for accuracy and standards compliance, this tool should be thoroughly tested and validated before production use.

Validation Required

⚠️ Do not use in production without thorough validation. All generated documents must be:

  • Tested against official HL7 specifications
  • Validated using official validators (e.g., NIST C-CDA Validator)
  • Reviewed by qualified healthcare IT professionals
  • Verified for regulatory compliance requirements

Not a Substitute for Official Specifications

This library complements but does not replace official HL7 documentation. For authoritative guidance, regulatory compliance, and certification requirements, always consult:

No Warranty

See LICENSE for complete warranty disclaimer and terms of use.

Official Resources

Trademarks

HL7® and C-CDA® are registered trademarks of Health Level Seven International. This project is not affiliated with or endorsed by Health Level Seven International.


Requirements

  • Python 3.8 or higher
  • lxml >= 4.9.0 (only required dependency)

Optional dependencies for development:

  • pytest (testing)
  • ruff (linting)
  • mkdocs-material (documentation)

License

MIT License - See LICENSE file for details.


Acknowledgments

This project follows the HL7 C-CDA Release 2.1 Implementation Guide and is designed to support ONC Health IT Certification requirements.

Developed with assistance from Claude Code.


Support


Current Status: Alpha release - MVP complete and ready for validation testing. Production use should be preceded by thorough validation against your specific requirements.

About

Python library for generating HL7 C-CDA clinical documents

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages