All posts

How to Connect a Legacy EHR With FHIR APIs for EHR Interoperability

Banner titled Connecting a Legacy EHR to FHIR, showing an HL7 v2.5 message today and a FHIR R4 Patient resource next, joined by the Forge by Opsera logo, under the line "One record, two ways in".

TL;DR

  • EHR interoperability means another system can find, send, receive and use your patient data without someone retyping it.
  • Most legacy EHRs still exchange data through HL7 v2 messages and C-CDA documents, while federal policy now points to FHIR APIs. ONC’s HTI-5 final rule bends certification decisively toward FHIR-based APIs, with C-CDA transitions of care kept until January 1, 2030.
  • The safe path keeps the HL7 v2 feeds running and adds a FHIR R4 API beside them, read-only first.
  • We ran LibreHealth EHR, an open-source EHR with no FHIR code, through Forge by Opsera. It scored 49 out of 100 across 7,082 files, and Forge turned the FHIR goal into a scoped intent and a PRD.

One engineer at a multi-specialty clinic group understands the HL7 v2 interfaces that send lab orders out and bring results back. The EHR behind them has served the group well for over a decade. Then a payer partner asks for patient data through an API, and a patient app vendor asks for the same.

The CIO asks a simple question: can we offer a FHIR API without breaking the lab feeds that keep clinics running? This guide answers it with a real legacy EHR, from the first assessment to a plan a coding agent can build from.

What Is EHR Interoperability?

EHR interoperability is the ability of an electronic health record to exchange patient data with other systems and use what it receives without manual entry. ONC measures it in four parts: finding, sending, receiving and integrating outside data.

Progress is real but uneven. 70% of US hospitals engaged in all four parts in 2023, up from 23% in 2014. The gap shows up by size: 53% of large hospitals often or routinely exchanged data, against 38% of small hospitals.

Bar chart titled "Progress is real, but uneven": hospitals engaged in all four interoperability domains rose from 23% in 2014 to 70% in 2023, while 53% of large hospitals and 38% of small hospitals often or routinely exchange data.

ONC data: hospitals engaged in all four domains, and routine exchange by hospital size

How Do HL7 v2, C-CDA and FHIR Compare?

A legacy EHR usually speaks the first two of these three standards:

StandardWhat it isTypical useShape of the data
HL7 v2Pipe-delimited messages, sent as events happenLab orders and results, admissions, billing feedsSegments such as MSH, PID, OBR, OBX
C-CDAXML documents that summarize a visit or a patientTransitions of care, referrals, discharge summariesOne large document per exchange
FHIRREST APIs over small, linked resourcesPatient apps, payer access, analytics, new integrationsJSON resources such as Patient, Observation, MedicationRequest

HL7 v2 is fast and widely supported, but each interface is a custom agreement between two systems. FHIR replaces those one-off agreements with a shared API, so a new partner can connect without a new interface project.

Why Is FHIR Interoperability Urgent for Legacy EHRs in 2026?

Three changes landed close together:

None of these rules switch off HL7 v2 overnight. They do mean every new partner will expect FHIR, and every year without it adds another custom interface to maintain.

What Makes a Legacy EHR Hard to Connect?

Most of the friction comes from how data leaves the system today:

  • Hand-built messages: HL7 strings are assembled field by field in application code, so every partner change is a code change.
  • Implicit contracts: Internal endpoints return whatever the database query returns, with no published shape a partner can rely on.
  • Old runtimes: The code targets PHP or framework versions that current libraries no longer support.
  • No shared vocabulary layer: Local codes for labs and problems are not mapped to LOINC or SNOMED CT in one place.
  • Ad hoc authorization: Access checks live in each page, so there is no single place to enforce app-level scopes.

Assessing LibreHealth EHR With Forge

LibreHealth EHR is a free, open-source electronic health record and practice management application, started by former OpenEMR contributors. Its GitHub repository’s last commit was in November 2022, which makes it a fair stand-in for a system that still runs but no longer gets steady investment.

We confirmed four facts in the code before running anything:

  • HL7 v2.3 orders built by hand: interface/orders/gen_hl7_order.inc.php assembles ORM^O01 messages by joining strings, with the version hard-coded as 2.3.
  • Results parsed from HL7 v2: receive_hl7_results.inc.php reads ORU and MDM messages and rejects anything that does not start with MSH.
  • C-CDA through a side service: The ccdaservice folder runs a Node.js service built on blue-button-generate to produce C-CDA documents.
  • No FHIR code at all: A search of the repository finds no FHIR endpoints, libraries or references, composer.json still declares "php": ">=5.3.0", and the project’s Docker image runs PHP 7.2.

Forge by Opsera reads a repository and writes the plan and specs a coding agent then builds from. It does not write the code itself. Its assessment produces a ForgeScore, a 0 to 100 score across eight dimensions, plus a NIST CSF 2.0 rating of how well the code covers govern, identify, protect, detect, respond and recover.

What the Score Shows

Forge analyzed all 7,082 files and gave LibreHealth EHR a ForgeScore of 49 with a NIST CSF rating of D, labeled Partial. Its security scorecard shows 0 exposed secrets, 19 end-of-life packages and 1 circular dependency.

ForgeScore Dashboard for LibreHealthIO/lh-ehr showing a composite score of 49 across 7,082 files, NIST CSF rating D (Partial), 0 secrets, 2 CVEs, 19 end-of-life packages and 1 circular dependency.

The ForgeScore dashboard Overview tab for LibreHealthIO/lh-ehr

The scorecard also lists 2 CVEs, and Forge is careful about them. It explains they are weakness patterns, database errors returned to the caller (CWE-209) and obsolete SSH key exchange (CWE-327), not verified CVE identifiers.

The strongest dimensions were Code Excellence at 61, Logic Narrative at 51 and Semantic Clarity at 51. The weakest were System Gravity and Future-Proofing, both at 39. Forge’s roadmap points to concentrated dependencies and about 250 reported layer violations as the main friction.

Forge’s verdict on the stack was blunt: out of sync, with modernization needed. It lists PHP 7.2, MariaDB 10.3, Laravel 5.4, AngularJS 1.5.8 and Bootstrap 3, and says the FHIR feature is not implementation-ready until clinical schemas, route protection and SMART support are verified.

Forge Assessment phase for LibreHealth EHR FHIR Interoperability showing a ForgeScore of 49 (Developing) with eight dimension scores, a security snapshot, and an "Out of Sync, Modernization Needed" verdict.

The assessment verdict, with the stack Forge flagged as out of sync

What the Score Means for a FHIR API

A FHIR API exposes the same data as the app, so its weak spots become the API’s weak spots. Forge’s first quick win is a good example. The encounter service in modules/merge_encounters/service/JSON-Encounters.php runs SELECT *, returns every row and places database exception messages into its JSON response.

That is fine inside one app, but it is the opposite of a FHIR contract, which defines exactly which fields come back and how errors look. Forge also credits what to keep: the same service binds pid and date as query parameters, and checkAdmin() gives a clear authorization checkpoint to build on.

From Score to a Scoped Intent

A score does not tell a team what to build. So we described the goal in plain words: a read-only FHIR R4 API on US Core profiles, SMART on FHIR authorization, and the HL7 v2.3 lab interfaces left untouched. Forge turned that into an intent, a short document that fixes the scope before anyone plans work, at 93% confidence.

Forge Intent Document for LibreHealth EHR FHIR Interoperability showing the intent profile, goal and vision for a separate read-only FHIR R4 API, with target personas listed and the chat panel announcing the intent profile is complete.

The approved Intent document for the FHIR read API

The intent ranks ten core features. The first five carry most of the interoperability work:

  • US Core read API: A versioned FHIR entry point for Patient, Encounter, Condition, MedicationRequest, AllergyIntolerance and lab Observation, returning Bundle results and OperationOutcome errors.
  • Mapping matrix: A reviewed map from source tables and columns to each FHIR resource, with local codes normalized to LOINC, SNOMED CT and RxNorm in one place.
  • SMART authorization: A maintained SMART-capable authorization product instead of home-grown token issuance, with checks on every read, search and page.
  • Separate read-service: New controllers, services and mappers behind their own boundary, plus a hardened encounter retrieval path that the FHIR Encounter reads can rely on.
  • Bounded search: Allow-listed parameters, capped pages and index-friendly date filters, so outside clients cannot overload the clinical database.

The rest covers a supported PHP 8.4 baseline for the new boundary, CI gates that also regression-test the HL7 feeds, protected deployment, PHI-safe audit logging, and an upgrade of the bundled SSH library.

Forge Intent Document on the Out of Scope tab, listing excluded work such as FHIR write operations, Bulk Data export and replacing HL7 v2 interfaces, followed by technical constraints including read-only access and SMART on FHIR authorization.

Out of scope and technical constraints in the same intent

Out of scope does as much work as in scope. It rules out FHIR writes, Bulk Data export, replacing HL7 v2 or C-CDA, a UI redesign and a framework migration. It also forbids exposing existing PHP handlers directly as the external API.

From Intent to a PRD Your Coding Agent Can Use

Before writing the PRD, Forge asked five pre-flight questions and suggested an answer for each. We kept its suggestions:

  • Launch scope: All six resources ship in the first release, each with SMART and US Core conformance.
  • Access model: Patient-level access only, so an app reads data only for patients it is authorized for.
  • Error behavior: Strict for authorization and profile-required elements, best-effort for optional ones.
  • Compliance: HIPAA and SOC 2.
  • Success metrics: A balanced set of adoption, developer efficiency and reliability.
Forge PRD-Spec pre-flight clarifications screen asking which capability set is in P0 scope for the read-only FHIR API and which SMART on FHIR access model to require, with a recommended option selected for each.

Forge’s pre-flight questions, with its suggested answers selected

The PRD-Spec came back at 94% confidence. It holds 12 user stories, seven of them P0, and each has acceptance criteria a reviewer can test. One P0 story protects the lab feed directly: if a release candidate fails the HL7 coexistence checks, rollout is blocked.

Forge Product Requirements Specification for LibreHealth EHR at 94% confidence, showing the executive summary of a separate read-only FHIR R4 API aligned to US Core and protected by SMART on FHIR, with HL7 v2.3 lab workflows unchanged.

The PRD-Spec executive summary at 94% confidence

The success measures are specific enough to hold a team to:

  • Adoption: At least two external applications in production within 180 days of launch.
  • Developer efficiency: A median of 10 business days or less from approved access to a first successful sandbox read.
  • Reliability: 95th percentile response time of 2 seconds or less and an error rate under 1% in the first 90 days.
  • Continuity: Zero Sev-1 incidents from the FHIR rollout that interrupt lab result intake.

The PRD also names what is still undecided, such as which US Core release to pin and which SMART authorization product to use. Its rollout plan runs in five phases, from contract and mapping work through a canary pilot to general availability, with parallel running of the HL7 feeds the whole way.

Forge PRD-Spec screen for LibreHealth EHR FHIR Interoperability showing go/no-go and rollback rules, a FHIR Read API rollout plan Gantt chart, and a "PRD-Spec Complete" prompt with an Approve and Continue button.

The PRD rollout plan, with go/no-go rules and a five-phase timeline

The next stage cuts the PRD into work orders, small testable tasks a coding agent can pick up one at a time while your team reviews each change.

How Do You Add FHIR Without Breaking the HL7 v2 Feeds?

The safest pattern adds a FHIR layer beside the existing interfaces and reads from the same database:

Diagram titled "A FHIR layer beside the HL7 v2 feeds": HL7 v2 lab feeds and C-CDA documents are kept on one side of the EHR database, the source of truth, while a FHIR R4 API and SMART on FHIR are added on the other side.

A FHIR layer beside the HL7 v2 feeds, reading from the same database

In practice, the work runs in five steps:

  1. Inventory every interface. List each HL7 v2 feed, its partner, message types and volume, so nothing is switched off by surprise.
  2. Start read-only with US Core. Expose Patient, Encounter, Condition, MedicationRequest, AllergyIntolerance and Observation before any write operation.
  3. Map codes once. Build one mapping layer from local codes to LOINC, SNOMED CT and RxNorm, and use it for both FHIR and HL7 v2.
  4. Add SMART on FHIR authorization. Give each app OAuth 2.0 scopes, so access is enforced in one place instead of page by page.
  5. Prove parity before moving partners. Compare FHIR responses with the HL7 v2 messages for the same patients, then move partners one at a time.

What Does the First FHIR API Endpoint Look Like?

Forge stops at the spec, so the sketch below shows what a coding agent might write for the first read endpoint. It maps a row from LibreHealth’s patient_data table to a US Core Patient and returns a FHIR error shape instead of a database message:

function toFhirPatient(array $row): array {return ['resourceType' => 'Patient','id' => (string) $row['pid'],'meta' => ['profile' => ['http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient']],'identifier' => [['system' => 'urn:librehealth:pid', 'value' => (string) $row['pid']]],'name' => [['family' => row['fname']]]],'gender' => strtolower($row['sex'] ?? 'unknown'),'birthDate' => $row['DOB'],];}function notFound(string $id): array {return ['resourceType' => 'OperationOutcome','issue' => [['severity' => 'error', 'code' => 'not-found','diagnostics' => "Patient/$id was not found"]],];}

Gender values need a real mapping to FHIR’s male, female, other and unknown, and the endpoint needs SMART scopes before it goes live. The point of the sketch is the contract: fixed fields, a declared profile, and errors that never leak the database.

How Do You Prove the Interoperability Work Landed?

Interoperability is easy to claim and easy to test. Track a small set of measures for each wave:

MeasureHow to check itWhat good looks like
FHIR conformanceRun the Inferno US Core and SMART test kitsRequired tests pass for each resource
HL7 v2 parityCompare FHIR results with the HL7 v2 messages for the same patientsValues match for every sampled patient
Error handlingSend unknown IDs and malformed requestsOperationOutcome responses, no database text
AuthorizationRequest data outside an app’s scopesAccess refused
Code healthRe-score the repository after each waveTrust Boundaries and Future-Proofing rise

For the clinic group in our example, the first wave ends when one partner reads live data through FHIR while the lab feeds run untouched. That gives the CIO a working connection to show, plus a re-score that shows the code got easier to change.

What Mistakes Derail EHR Interoperability Projects?

  • Replacing HL7 v2 first: Lab partners move on their own schedules. Add FHIR beside the feeds and retire them only when partners move.
  • Exposing tables as APIs: A FHIR API that mirrors SELECT * inherits every quirk of the schema. Map to US Core profiles instead.
  • Skipping the code mapping: Without LOINC and SNOMED CT mapping, FHIR resources look standard but do not mean the same thing elsewhere.
  • Leaving authorization for later: Patient data over an open API is a breach waiting to happen. Build SMART scopes into the first endpoint.
  • Treating a projection as a result: Forge’s roadmap projects a higher score after three refactors. It stays a target until a re-score confirms it.

Conclusion: Grow FHIR Beside the HL7 v2 Feeds

The clinic group in our example keeps its decade-old EHR and its lab feeds. What changes is how new partners connect: through one FHIR API with clear contracts, instead of another custom interface.

Getting there starts with knowing the code. Score the EHR, scope the FHIR work in writing, build read-only US Core first, and re-score after each wave to show the system got easier to connect. See how Forge approaches legacy modernization, or read our healthcare IT modernization guide for the wider picture. Try it on your own repository with Forge by Opsera, or book a demo to see how Forge scopes the FHIR work on your EHR.

Questions.

What is EHR interoperability?

EHR interoperability is the ability of an electronic health record to find, send, receive and use patient data from other systems without manual entry.

How is HL7 v2 different from FHIR?

HL7 v2 sends pipe-delimited messages between two systems that agree on a custom interface. FHIR exposes small, linked resources through a standard REST API, so new partners can connect without a new interface project.

Do I have to replace HL7 v2 to support FHIR?

No. A FHIR API can sit beside the HL7 v2 feeds and read from the same database. HL7 v2 interfaces can retire later, partner by partner.

What FHIR standards should a legacy EHR start with?

Start with FHIR R4 and the US Core profiles for patients, encounters, problems, medications, allergies and lab results, with SMART on FHIR for authorization. These are the standards ONC’s certification tests check.

How do you improve EHR interoperability?

Start by inventorying every HL7 v2 interface, then add a read-only FHIR R4 API beside them using US Core profiles. Map local codes to LOINC, SNOMED CT and RxNorm once, add SMART on FHIR authorization, and prove parity with the HL7 v2 messages before moving partners. Re-score the code after each wave to confirm it got easier to connect.

Does Forge write the FHIR API code?

No. Forge assesses the codebase, writes the intent and the PRD, and cuts the work into work orders. Your coding agent builds from those, and your team reviews each change.

Two people at work on code, seen from behind their monitors.

See it running on your own pipelines.

Forty-five minutes with our engineers. Bring a pipeline you are unhappy with.

Book a demoNo install required