Flexpa
Developer PortalFeedbackContact usSandboxTry it yourself

All docs

Schema

  • Overview

C-CDA Documents

  • Overview
  • Document Types
  • C-CDA Versions
  • Reading Content
  • Decoding and Parsing

C-CDA to FHIR Conversion

  • Overview
  • Mapped FHIR Resources
  • Why Preserve Source Documents
  • Conversion Tools and Libraries

Binary Attachments

  • How Attachments Work
  • Binary Resource
  • Content Types
  • Retrieval Best Practices

API

  • GETRead
  • GETSearch

DocumentReference

DocumentReference is a FHIR resource that provides metadata about a document so it can be discovered and managed. The document can be any type, but clinical documents are particularly common, including C-CDA (Consolidated Clinical Document Architecture) documents.

C-CDA documents are structured clinical documents that contain comprehensive patient health information including problems, medications, allergies, procedures, vital signs, social history, and more. These documents are commonly exchanged between healthcare providers and are increasingly available through nationwide health information exchange networks like TEFCA (Trusted Exchange Framework and Common Agreement).

While DocumentReference resources have historically been uncommon in payer APIs, they are becoming more prevalent through:

  • TEFCA and Nationwide Health Information Exchange - Networks like Carequality and eHealth Exchange enabling clinical document exchange across the healthcare ecosystem
  • Provider-Payer Data Exchange - Clinical documentation submitted for quality measures, prior authorization, or care coordination
  • Clinical Data Registries - Aggregated clinical information from various sources

The DocumentReference resource provides metadata about the document, including its type, author, date, and how to retrieve the actual document content. Documents are typically available in formats like:

  • C-CDA (XML) - Structured clinical documents following HL7 CDA standard
  • HTML - Human-readable clinical notes
  • PDF - Scanned or formatted clinical documents
  • Plain text - Unstructured clinical notes

This reference explains the key elements of DocumentReference resources and how to access clinical documents through the Flexpa API. Data types used in this reference are defined in the FHIR R4 Data Types specification.

FHIR API

https://api.flexpa.com/fhir/DocumentReference

New to FHIR?

Intro to FHIR

FHIR, or Fast Healthcare Interoperability Resources, is a standard for exchanging healthcare information electronically

Read introduction →

Looking for clinical data?

C-CDA documents accessed through nationwide exchange networks provide the most comprehensive clinical information available through payer APIs, including detailed provider documentation not found in claims data.


#Schema

#Overview

The FHIR R4 DocumentReference resource provides metadata about a document so it can be discovered and managed. As a FHIR resource, it follows standard FHIR patterns with common elements like resourceType, id, meta, and identifier.

DocumentReference resources are typically compliant with the US Core DocumentReference Profile, which defines specific requirements for clinical notes and documents.

The resource contains two main types of information: metadata elements that describe the document (type, author, date) and content elements that provide access to the actual document data.

Elements

metaMeta

Metadata about the resource. See also Tags defined by Flexpa.

lastUpdatedinstant

The last time the document metadata was updated

identifierIdentifier

Business identifiers assigned to the document

systemuri

The namespace for the identifier value

valuestring

The unique identifier value

statuscode

The status of the document reference

Codes
current
This is the current reference for this document
superseded
This reference has been superseded by another reference
entered-in-error
This reference was created in error
typeCodeableConcept

The type of document being referenced

Systemhttp://loinc.org
LOINC codes for document types
Example Codes
34109-9
Miscellaneous Notes
11488-4
Consultation Notes
18842-5
Discharge Summary
11506-3
Progress Notes
34133-9
Summarization of Episode Note
categoryCodeableConcept

High-level categorization of the document

Systemhttp://hl7.org/fhir/us/core/CodeSystem/us-core-documentreference-category
US Core DocumentReference Category Codes
Codes
clinical-note
Clinical notes and documentation
subjectReference(Patient)

Reference to the Patient who is the subject of the document

dateinstant

When the document reference was created or when the document was authored

authorarray

Who and/or what authored the document

identifierIdentifier

Identifier for the author (e.g., NPI number)

systemuri

The identifier system, commonly http://hl7.org/fhir/sid/us-npi for NPI numbers

valuestring

The identifier value

displaystring

Text representation of the author's name

contentarray

The document and format details

attachmentAttachment

The document content

contentTypecode

MIME type of the content - commonly text/html, text/xml, application/xml, application/pdf, or text/plain

database64Binary

Base64-encoded document data - when present, contains the actual document content

urlurl

URI where the document can be retrieved - alternative to inline data

formatCoding

Format/content standard of the document

Systemhttp://ihe.net/fhir/ValueSet/IHE.FormatCode.codesystem
IHE Format Codes
Example Codes
urn:ihe:iti:xds:2017:mimeTypeSufficient
Format specified by MIME type
Codes
cda
Clinical Document Architecture (C-CDA) - commonly used for nationwide exchange
contextBackboneElement

Clinical context of the document

encounterReference(Encounter)

Context of the document content - reference to the Encounter associated with the document

periodPeriod

Time period covered by the documentation

DocumentReference Example

{
  "resourceType": "DocumentReference",
  "id": "73747034db32edf9ab1bfbdbe0b05f764ec8c1c51874b159cd8e82e286c0becf",
  "meta": {
    "versionId": "43",
    "lastUpdated": "2021-06-23T08:30:07.826+00:00",
    "source": "https://fhir.example.com/documentation/glossary/DataSource",
    "tag": [
      {
        "system": "https://www.hl7.org/fhir/patient.html",
        "code": "Patient/example-patient-id"
      },
      {
        "system": "https://fhir.example.com/documentation/glossary/lastRefreshedOn",
        "code": "2021-06-23T08:30:07.629Z"
      }
    ]
  },
  "status": "current",
  "type": {
    "coding": [
      {
        "system": "http://loinc.org",
        "code": "34109-9",
        "display": "Misc Notes"
      },
      {
        "system": "http://loinc.org",
        "code": "11506-3",
        "display": "Progress Notes"
      }
    ]
  },
  "category": [
    {
      "coding": [
        {
          "system": "http://hl7.org/fhir/us/core/CodeSystem/us-core-documentreference-category",
          "code": "clinical-note"
        }
      ],
      "text": "Clinical Note"
    }
  ],
  "subject": {
    "reference": "Patient/example-patient-id"
  },
  "date": "2021-01-18T00:54:34.949+00:00",
  "author": [
    {
      "identifier": {
        "system": "http://hl7.org/fhir/sid/us-npi",
        "value": "1720081417"
      },
      "display": "RICHARD YOUNG, DPM"
    }
  ],
  "content": [
    {
      "attachment": {
        "contentType": "text/xml",
        "data": "PENsaW5pY2FsRG9jdW1lbnQgeG1sbnM9InVybjpobDctb3JnOnYzIj4KICA8dGl0bGU+UHJvZ3Jlc3MgTm90ZTwvdGl0bGU+CiAgPCEtLSBDLUNEQSBjb250ZW50IGhlcmUgLS0+CjwvQ2xpbmljYWxEb2N1bWVudD4="
      },
      "format": {
        "system": "http://ihe.net/fhir/ValueSet/IHE.FormatCode.codesystem",
        "code": "urn:hl7-org:sdwg:ccda-structuredBody:2.1",
        "display": "C-CDA Structured Body"
      }
    }
  ],
  "context": {
    "period": {
      "start": "2021-01-18",
      "end": "2021-01-18"
    }
  }
}

#C-CDA Documents

#Overview

C-CDA (Consolidated Clinical Document Architecture) is an XML-based standard for clinical document exchange. When accessed through nationwide health information exchange networks like TEFCA, C-CDA documents provide comprehensive clinical information that is not available in traditional claims data.

Always retrieve and store C-CDA documents. If you want maximal data extraction, you should always retrieve the original C-CDA DocumentReference regardless of what final analysis format you use. C-CDA documents contain rich clinical context that may not fully survive conversion to other formats, and you risk record loss if you don't preserve the source document.

C-CDA documents typically include structured sections for:

  • Problems/Diagnoses - Active and historical conditions with onset dates and status
  • Medications - Current and historical medications with dosing, frequency, and duration
  • Allergies and Intolerances - Documented allergies with severity and reactions
  • Procedures - Surgical and diagnostic procedures with dates and providers
  • Vital Signs - Blood pressure, heart rate, temperature, weight, height
  • Laboratory Results - Test results with reference ranges and interpretations
  • Immunizations - Vaccination history with dates and vaccine information
  • Social History - Smoking status, alcohol use, and other social determinants
  • Clinical Notes - Unstructured provider documentation and assessments

#Document Types

TEFCA and other health information exchange networks permit exchange of multiple C-CDA document types. The most common is the Continuity of Care Document (CCD), but you may encounter others:

Document TypeLOINC CodeDescription
Continuity of Care Document (CCD)34133-9Snapshot of patient's current health status including problems, medications, allergies, and recent care
Discharge Summary18842-5Summary of a hospital stay including diagnoses, procedures, and discharge instructions
Progress Note11506-3Documentation of a clinical encounter or visit
Consultation Note11488-4Documentation from a specialist consultation
History and Physical34117-2Comprehensive patient history and physical examination
Referral Note57133-1Documentation supporting a referral to another provider
Care Plan18776-5Planned care activities and goals

The Continuity of Care Document (CCD) is the most common document type and represents a core data set of the most relevant clinical information about a patient. It provides a historical tally of care over a range of time and is designed to support continuity of care when patients move between providers or care settings.

#C-CDA Versions

C-CDA documents may be produced in different versions depending on the source system:

  • C-CDA R2.1 (2015) - Most widely deployed version, aligned with Meaningful Use Stage 2
  • C-CDA R3.0 (2022) - Updated version with improved templates and US Core alignment
  • C-CDA R4.0/R5.0 (2024-2025) - Latest versions with USCDI alignment

The version can typically be identified by the templateId elements in the document header. Different facilities and EHR systems may produce documents in different versions, so your processing logic should handle version variations gracefully.

#Reading Content

The actual document content is provided in the content[].attachment element. Documents can be delivered in two ways:

  1. Inline Data - Base64-encoded content in the data element
  2. URL Reference - A URL in the url element where the document can be fetched

For C-CDA documents, the contentType is typically text/xml or application/xml, and the format element indicates the C-CDA version and profile.

When both data and url are provided, the reference should point to the same content as found in the data. Servers are required to support at least one of these elements, and client applications should support both.

#Decoding and Parsing

When document data is base64-encoded:

// Decode base64 document data
const documentData = atob(resource.content[0].attachment.data);

// For C-CDA XML documents, parse with XML parser
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(documentData, "text/xml");

// Extract structured data from C-CDA sections
const medications = xmlDoc.getElementsByTagName("medication");
const problems = xmlDoc.getElementsByTagName("problem");

C-CDA Document Example

<?xml version="1.0" encoding="UTF-8"?>
<ClinicalDocument xmlns="urn:hl7-org:v3">
  <realmCode code="US"/>
  <typeId root="2.16.840.1.113883.1.3" extension="POCD_HD000040"/>
  <templateId root="2.16.840.1.113883.10.20.22.1.1" extension="2015-08-01"/>
  <id root="2.16.840.1.113883.19.5.99999.1"/>
  <code code="34133-9" codeSystem="2.16.840.1.113883.6.1"
        displayName="Summarization of Episode Note"/>
  <title>Continuity of Care Document</title>
  <effectiveTime value="20210118005434"/>

  <recordTarget>
    <patientRole>
      <id extension="12345" root="2.16.840.1.113883.19.5.99999.2"/>
      <patient>
        <name>
          <given>John</given>
          <family>Doe</family>
        </name>
        <birthTime value="19800101"/>
      </patient>
    </patientRole>
  </recordTarget>

  <component>
    <structuredBody>
      <!-- Problems Section -->
      <component>
        <section>
          <templateId root="2.16.840.1.113883.10.20.22.2.5.1"/>
          <code code="11450-4" codeSystem="2.16.840.1.113883.6.1"
                displayName="Problem List"/>
          <title>Problems</title>
          <text>
            <list>
              <item>Type 2 Diabetes Mellitus</item>
              <item>Hypertension</item>
            </list>
          </text>
          <entry>
            <observation classCode="OBS" moodCode="EVN">
              <code code="55607006" codeSystem="2.16.840.1.113883.6.96"
                    displayName="Problem"/>
              <value xsi:type="CD" code="44054006"
                     codeSystem="2.16.840.1.113883.6.96"
                     displayName="Type 2 Diabetes Mellitus"/>
            </observation>
          </entry>
        </section>
      </component>

      <!-- Medications Section -->
      <component>
        <section>
          <templateId root="2.16.840.1.113883.10.20.22.2.1.1"/>
          <code code="10160-0" codeSystem="2.16.840.1.113883.6.1"
                displayName="Medication List"/>
          <title>Medications</title>
          <text>
            <list>
              <item>Metformin 500mg twice daily</item>
              <item>Lisinopril 10mg once daily</item>
            </list>
          </text>
        </section>
      </component>
    </structuredBody>
  </component>
</ClinicalDocument>

#C-CDA to FHIR Conversion

#Overview

The C-CDA on FHIR Implementation Guide defines how to represent C-CDA document types as FHIR resources and provides mappings between C-CDA content and FHIR resources. This enables systems to convert between the two formats while preserving clinical meaning.

Important limitation: The C-CDA to FHIR conversion does not aim for 100% coverage of all scenarios. The Implementation Guide explicitly targets approximately 80% coverage of common use cases. Some clinical nuances, local extensions, or edge cases may not survive the conversion process. For maximal data extraction, always preserve the original C-CDA document.

#Mapped FHIR Resources

When converting a C-CDA document to FHIR, the clinical content maps to standard FHIR resources. The US Core Implementation Guide represents the FHIR side of this mapping and covers the majority of coded entries found in CCDs, Care Plans, and Discharge Summaries.

C-CDA SectionFHIR ResourceNotes
ProblemsConditionActive and historical diagnoses
MedicationsMedicationRequestCurrent medication orders
AllergiesAllergyIntoleranceDocumented allergies and intolerances
ProceduresProcedurePerformed procedures
ResultsObservationLaboratory and other test results
Vital SignsObservationHeight, weight, blood pressure, etc.
ImmunizationsImmunizationVaccination records
EncountersEncounterClinical visits and admissions
Care TeamCareTeamProviders involved in care
GoalsGoalPatient care goals
Social HistoryObservationSmoking status, social determinants

#Why Preserve Source Documents

While C-CDA to FHIR conversion is valuable for working with clinical data in modern systems, there are important reasons to always preserve the original C-CDA documents:

  1. Data fidelity - The original document contains the complete clinical context as authored by the provider
  2. Legal record - The C-CDA may serve as the authoritative clinical record for legal or compliance purposes
  3. Conversion limitations - Not all C-CDA content maps cleanly to FHIR resources; some information may be lost or simplified
  4. Version handling - Different C-CDA versions may have different mappings or unsupported templates
  5. Local extensions - Facilities may include custom sections or extensions that don't have FHIR equivalents

#Conversion Tools and Libraries

Several open-source tools are available for converting C-CDA documents to FHIR:

  • cda2fhir - Java library supporting C-CDA R2.1 to FHIR R4
  • cda2r4 - JavaScript library for C-CDA to FHIR R4 conversion
  • HL7 FHIR Mapping Language - Official HL7 approach for defining data transformations

These tools implement the mappings defined in the C-CDA on FHIR Implementation Guide but may have varying levels of coverage and accuracy.

Conversion Example

// Example: Extract FHIR-like data from C-CDA
function extractProblemsFromCCDA(xmlDoc) {
  const problems = [];
  const problemSection = xmlDoc.querySelector(
    'section[code="11450-4"]'
  );

  if (problemSection) {
    const entries = problemSection.querySelectorAll('entry observation');

    for (const entry of entries) {
      const value = entry.querySelector('value');
      if (value) {
        problems.push({
          resourceType: 'Condition',
          code: {
            coding: [{
              system: 'http://snomed.info/sct',
              code: value.getAttribute('code'),
              display: value.getAttribute('displayName')
            }]
          },
          clinicalStatus: {
            coding: [{
              system: 'http://terminology.hl7.org/CodeSystem/condition-clinical',
              code: 'active'
            }]
          }
        });
      }
    }
  }

  return problems;
}

For production use, consider using established C-CDA parsing libraries rather than implementing custom XML parsing. The document structure can vary significantly between sources and versions.


#Binary Attachments

#How Attachments Work

DocumentReference resources contain document metadata, but the actual document content is stored in the content[].attachment element. This attachment can contain the document data in two ways:

  1. Inline base64 data - The attachment.data element contains the document encoded as base64
  2. URL reference - The attachment.url element contains a URL where the document can be retrieved

When the URL points to a FHIR Binary resource (e.g., Binary/12345), you can retrieve the raw document content using a separate API call.

#Binary Resource

The Binary resource is a special FHIR resource type used to store raw binary content like documents, images, or other non-FHIR data. When a DocumentReference points to a Binary resource:

GET /Binary/12345
Accept: application/pdf

The server returns the raw document content directly, or you can request the Binary as a FHIR resource:

GET /Binary/12345
Accept: application/fhir+json

This returns a FHIR Binary resource with the content in the data element as base64.

#Content Types

The attachment.contentType indicates the MIME type of the document:

Content TypeFormatDescription
text/xml or application/xmlC-CDAStructured clinical document (XML)
application/pdfPDFPortable document format
text/htmlHTMLHuman-readable clinical notes
text/plainPlain textUnstructured text notes
image/jpeg, image/pngImageScanned documents or clinical images

#Retrieval Best Practices

When working with document attachments:

  1. Check for inline data first - If attachment.data is present, the document content is already available
  2. Handle both patterns - Your application should support both inline data and URL references
  3. Use appropriate Accept headers - When fetching Binary resources, set the Accept header based on whether you want raw content or a FHIR resource
  4. Consider document size - Large documents like scanned PDFs may be megabytes in size; plan for this in your architecture
  5. Store original documents - Always persist the original document content for future reference and compliance

Retrieving Attachments

async function getDocumentContent(documentReference, accessToken) {
  const attachment = documentReference.content?.[0]?.attachment;

  if (!attachment) {
    throw new Error('No attachment found');
  }

  // Option 1: Inline base64 data
  if (attachment.data) {
    const decoded = atob(attachment.data);
    return {
      content: decoded,
      contentType: attachment.contentType
    };
  }

  // Option 2: URL reference
  if (attachment.url) {
    const response = await fetch(attachment.url, {
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Accept': attachment.contentType || '*/*'
      }
    });

    if (!response.ok) {
      throw new Error(`Failed to fetch document: ${response.status}`);
    }

    return {
      content: await response.text(),
      contentType: response.headers.get('Content-Type')
    };
  }

  throw new Error('No data or url in attachment');
}

Check Content Type

function isCCDADocument(documentReference) {
  const attachment = documentReference.content?.[0]?.attachment;
  const contentType = attachment?.contentType?.toLowerCase();

  return (
    contentType === 'text/xml' ||
    contentType === 'application/xml' ||
    contentType?.includes('ccda')
  );
}

function isPDFDocument(documentReference) {
  const attachment = documentReference.content?.[0]?.attachment;
  return attachment?.contentType === 'application/pdf';
}

#API

GEThttps://api.flexpa.com/fhir/DocumentReference/:id

#Read

A read is the most basic operation in FHIR. It allows you to retrieve the current version of a single resource by its ID.

For a full list of available Resources, please refer to the FHIR Resources documentation.

Request headers

AuthorizationstringRequired

An Authorization: Bearer header value must presented with a Patient Access Token or an Application Access Token

Request path parameters

identifierstring

The identifier of the resource to be retrieved - used in the last part of the URL path segment

Error codes

transient429 status code

The API is expected to return a 429 status code until the data is ready to be retrieved. This error is returned by the API while in the initial sync period, which typically lasts less than 1 minute.

You will need to implement retry logic to handle this error. If you are using the Node SDK which we demonstrate in our Quickstart guide, retry logic is already built in and you don't need to implement it yourself.

processing422 status code
The API is expected to return a 422 when Flexpa fails to synchronize any resources from the payer for the requested Patient. Please re-authorize or reach out to support.

Request

GET
/fhir/DocumentReference/:id
ACCESS_TOKEN=flexpa-link-access-token

curl https://api.flexpa.com/fhir/DocumentReference/73747034db32edf9ab1bfbdbe0b05f764ec8c1c51874b159cd8e82e286c0becf \
  -H "Authorization: Bearer $ACCESS_TOKEN"

GEThttps://api.flexpa.com/fhir/DocumentReference

#Search

Searches on Flexpa API follow the RESTful style of the FHIR specification by submitting a GET HTTP request to the base URL of the resource with parameters to define the exact search criteria to filter the response.

Request headers

AuthorizationstringRequired

An Authorization: Bearer header value must presented with a Patient Access Token or an Application Access Token

Search parameters

Flexpa supports all DocumentReference SearchParameter values defined in the FHIR R4 specification

patientreference

The patient the document is about - recommended to use with the $PATIENT_ID wildcard

typetoken

Kind of document (LOINC code for document type)

categorytoken

Categorization of document (e.g., clinical-note)

datedate

When the document reference was created

perioddate

Time period covered by the documentation

authorreference

Who and/or what authored the document

statustoken

Current status of the document reference (current, superseded, entered-in-error)

contenttypetoken

MIME type of the document content

Error codes

transient429 status code

The API is expected to return a 429 status code until the data is ready to be retrieved. This error is returned by the API while in the initial sync period, which typically lasts less than 1 minute.

You will need to implement retry logic to handle this error. If you are using the Node SDK which we demonstrate in our Quickstart guide, retry logic is already built in and you don't need to implement it yourself.

processing422 status code
The API is expected to return a 422 when Flexpa fails to synchronize any resources from the payer for the requested Patient. Please re-authorize or reach out to support.

Request

GET
/fhir/DocumentReference
ACCESS_TOKEN=flexpa-link-access-token

curl "https://api.flexpa.com/fhir/DocumentReference?patient=$PATIENT_ID" \
  -H "Authorization: Bearer $ACCESS_TOKEN"
Status TwitterGitHub

© 2026 Flexpa. All rights reserved.