Building CDS Hooks services with HAPI FHIR

A CDS Hooks service built with HAPI FHIR answers a clinician's workflow hook with cards, using data the EHR sends or the service fetches. This page covers the build decisions, setup sequence, security controls and sandbox testing that decide whether it works in production.

On this page

Building CDS Hooks services with HAPI FHIR: when your team needs one

A CDS Hooks service is the component that receives a hook call from the EHR at a defined workflow point and returns cards that the EHR displays to the clinician. If your EHR vendor or clinical team wants decision support to appear inside the EHR at a specific step, such as opening a chart or placing an order, you need a service that answers those calls. HAPI FHIR does not replace that service. It is the FHIR platform you already run, and the JPA server is the part that stores and serves the clinical data the service may read, using a database you operate.

On the HAPI FHIR side, the JPA server provides a complete RESTful FHIR server backed by a database and supports FHIR DSTU2, DSTU3, R4, R4B and R5. Your service can read resources from it, and the security building blocks documented by HAPI FHIR, including authentication interceptors, the AuthorizationInterceptor, consent and search narrowing interceptors, CORS support and BALP audit logging, are the controls you would combine to limit what the service and the EHR can access. HAPI FHIR states that it does not provide a single one-size-fits-all security layer, so the access rules for each hook and each caller must be designed by your team.

Outside HAPI's scope are the decisions about which EHR workflow points trigger a hook, which clinical logic the cards represent, who approves that logic, how the service is authenticated against each EHR, and how card content is reviewed for clinical safety. Confirm with your EHR vendor which hooks and card behaviors its sandbox supports before you commit to a design, and confirm which identity provider and audit retention your organization requires, since those settings sit around the FHIR server rather than inside it.

Configuration options and when each one fits

This table compares the main build, data access and deployment choices for a CDS Hooks service on HAPI FHIR. Read each row as a decision: when the option fits, and what it costs in coupling, scaling and upgrade effort.

ChoiceWhen it fitsCost in coupling, scaling and upgrades
Service inside the JPA server applicationA small set of services that need direct access to the stored resources and a single team that owns both the server and the hooksHigh coupling: a service change means rebuilding and redeploying the server, and CDS load competes with FHIR API traffic for the same resources and database
Separate service applicationServices with their own release cycle, separate scaling needs or a team that does not own the FHIR serverMore moving parts: you own a second deployment, its authentication to the FHIR server, and its own upgrade track, but failures and load stay isolated
Read data with the HAPI FHIR clientServices that need data beyond what the EHR sends, such as related resources or history, and where the FHIR server holds that dataExtra round trips and query load on the server; access rules must cover every read the client makes, and the client version must match the server's FHIR release
Rely on prefetch from the EHRServices that need only the context the EHR sends with each hook, which keeps the service stateless and avoids a server dependencyLess control over what arrives: the service must handle missing or partial prefetch data, and the EHR decides which fields are available
Auto-prefetch with a FHIR server fallbackServices that want the EHR to send common data while still reading gaps from the server when neededTwo data paths to test and secure; confirm with the EHR sandbox and your EHR vendor which prefetch templates and resources each system supports
Docker image (hapiproject/hapi or a custom image)Teams that want a containerized, repeatable build for a single host or Compose-based environmentSimple to start; you manage image rebuilds for each service release and any JDK 17 requirement of HAPI FHIR 8.2.0 in your base image
WAR on Tomcat, Jetty or WildflyOrganizations with an existing application server standard that must run the service beside other Java applicationsShared server lifecycle with other apps; confirm the servlet container version against your HAPI FHIR release before you deploy
Kubernetes with the Helm chartServices that need horizontal scaling, health checks, rolling upgrades and secrets management across several environmentsMost operational overhead: cluster, ingress, TLS and secrets must be operated, but scaling and rollback are easiest to control

How a hook call becomes a card

A CDS Hooks call starts when the EHR reaches a defined workflow point, such as opening a patient chart or signing a medication order, and sends a request to every service subscribed to that hook. The request carries a hook name, a context block with the identifiers the workflow already has (for example the patient and the encounter), and optionally a prefetch object holding FHIR resources the EHR has already gathered. Your @CdsService method receives that payload as a request object, and its return value is a list of cards. The EHR renders each card as a suggestion, an informational alert or a link to an app, and it may act on a suggested action only when the clinician accepts it. The service does not write the result back into the chart on its own. Before you write any code, confirm the hook names, the request fields and the card structure against the CDS Hooks specification and the exact HAPI FHIR library version you plan to use, because field names and required properties are where integrations most often break.

The question that shapes the design is whether the service can answer from the request alone. If the EHR supplies every resource the logic needs through prefetch, the method can compute its cards without calling the server. If it needs anything else, such as a recent observation the EHR did not prefetch or a Library resource for CQL logic, the method must query the HAPI FHIR JPA server through an IGenericClient or a DAO, and that call adds latency to a request the clinician is waiting on. Each extra lookup therefore has a cost in response time, and the reader should measure it during testing rather than assume it is small. The service also needs the FHIR base URL and credentials for that server, which should come from secured configuration, and the access it uses should be scoped to what the hook requires. Those access rules are covered in the access control section, so here the decision is only where each data need is met: in the prefetch, in a server query, or in both.

Plan the response path as carefully as the request path. A card that arrives late, is malformed or cites data the clinician cannot see will be ignored or reported as a defect, so the service should return an empty card list when it has nothing useful to say and should log the request identifier, hook name and outcome for each call. Ask the EHR vendor which hooks it fires, whether it sends prefetch templates or expects the service to request data, and what timeout applies to a service response. Those answers decide how much server work the method can safely do. Test the full loop in an EHR sandbox with real hook invocations before any clinical user sees a card.

Request flow between the EHR, the CDS service and the HAPI FHIR server

The flow starts when the EHR fires a hook at the CDS service, sending the hook name, context and any prefetch bundle the EHR already assembled. The CDS service first checks that the caller is trusted, then reads only the extra data it needs from the HAPI FHIR server through its own authorized client. It writes an audit record for the request and returns cards to the EHR. Check that the trust boundary is crossed only by authenticated calls, and that the service never relies on data it did not verify.

Generic illustration of a CDS Hooks request path, not a vendor-verified flow.

Setup sequence: from a running HAPI FHIR server to a working service

This sequence takes a team from a HAPI FHIR JPA server in a non-production environment to a CDS Hooks service that answers a sample request with expected cards. Each step closes with a check, so problems surface before the service touches a live EHR connection.

  1. Stand up a non-production HAPI FHIR JPA server

    Deploy the HAPI FHIR JPA server starter in a non-production environment, using the hapiproject/hapi Docker image or another deployment method your team has chosen. The starter defaults to an embedded H2 database, which is fine for a first run but should be replaced with PostgreSQL or Microsoft SQL Server before anything resembling production. Confirm the server answers a capability statement request and that a test Patient can be created and read back. The step is complete when those two calls succeed from the network segment where the CDS service will run.

  2. Confirm the Java runtime matches the HAPI FHIR version

    Check the HAPI FHIR version you have chosen against the versions documentation, then confirm the JDK your build and runtime use meets its requirement. HAPI FHIR 8.2.0 requires JDK 17, and later releases may raise the requirement, so read the release notes for the exact version you pin. Run the Java version command in the build image and in the container or application server that will host the service. The check is complete when both report the same supported major version and the build passes with that toolchain.

  3. Add the CDS Hooks library and write one service method

    Add the HAPI FHIR CDS Hooks dependency to a new Java project, matching the HAPI FHIR version used by the server so that model classes agree. Write one class annotated with the CDS service annotation, define a service ID, a hook it responds to, and a method that returns a CdsServiceResponse with a single card. Keep the first method simple, with a static card, so that any later failure points to wiring rather than clinical logic. The check is complete when the project compiles and the unit test for the method returns one card with the expected summary text.

  4. Configure endpoints and the discovery response

    Register the service so the CDS Hooks discovery endpoint lists it, with the service ID, title, description, hook and any prefetch templates you intend to use. Set the base path the EHR will call and confirm it is reachable over the transport your security team has approved. Record the exact discovery response your build produces, since EHR sandboxes validate against it. The check is complete when a GET request to the discovery path returns a JSON document that lists your service with the hook and fields you configured, and nothing extra.

  5. Connect the service to the FHIR server with a test identity

    Create a dedicated test client identity on the FHIR server with read access limited to the resource types your prefetch templates need, and configure the service with its base URL and credentials through your secrets mechanism, not in source code. Use the authorization and consent options described in the HAPI FHIR security documentation to confirm the identity can read only what it should. Test one read that the service is allowed to make and one that it should be refused. The check is complete when the allowed read succeeds, the refused read returns an authorization failure, and the credentials appear nowhere in logs or configuration files committed to version control.

  6. Send a sample request and check the returned cards

    Send a sample CDS Hooks request to the service's invocation endpoint, using a hook context and a prefetch payload built from test patients on the non-production server. Compare the response with the cards you specified, checking the summary, indicator, source and any suggested actions against your expected output. Confirm the request and response are logged with the audit detail your organization requires. The step is complete when the sample request returns the expected cards on at least the cases you defined, and any mismatch is either fixed or recorded as an open item.

  7. Confirm open items in the vendor documentation

    Before moving to a sandbox or any shared environment, review the HAPI FHIR and CDS Hooks specification details your build depends on with the vendor documentation and the release notes for your pinned version. Confirm the supported hook names, prefetch behavior, authorization interceptor options and any changes in the release you chose. Write down each point you verified and the version it applies to. The step is complete when the list of verified points is signed off by the team member responsible for the service.

Prefetch or fetch on demand: choosing how the service gets its data

In this model the EHR includes the resources the service needs in the hook request, so the service reads them from the payload and does not call the FHIR server for them. This suits services that need a small, predictable set of resources, such as the active medication list or the current encounter, and where the EHR already holds that data at the moment the hook fires.

  • Latency: The service avoids a round trip to the FHIR server, so response time depends mainly on the EHR and the service's own logic. The EHR must assemble the prefetch before it calls the service, which adds work on the EHR side.
  • Data minimization: The EHR decides exactly what leaves its system, which makes it easier to show that a service receives only the fields it needs. The service should reject or log requests that lack the expected prefetch keys.
  • EHR configuration: Each hook's prefetch template is set on the EHR side, so changes to what the service needs require coordination with the EHR administrators, and a template mismatch fails quietly unless the service checks for it.
  • Testing effort: Test cases must include payloads built the way the EHR builds them, including missing or partial prefetch entries. Sandbox payloads and production payloads can differ, so confirm both.
  • Data freshness: The prefetch reflects the EHR state at hook time, which is usually what a point-of-care alert needs.

Before relying on this model, confirm with the EHR team which prefetch keys they populate for each hook and how they handle failures.

Testing services with an EHR sandbox before go-live

Test every CDS Hooks service in an EHR sandbox before any clinician sees its cards, because the sandbox is the only place where the full hook sequence runs against a real EHR client. Start by registering the service endpoint with the sandbox, using the discovery document that your HAPI FHIR service exposes at the CDS Hooks discovery path, and confirm that the sandbox lists your service under the hook it claims to support, such as patient-view. Then trigger the hook from the sandbox's test workflow for a patient that has the data your rules need. For each run, capture the request the EHR sent, including the prefetch payload and the fhirServer and fhirAuthorization fields if your service uses them, and compare it with what your @CdsService method expected. Check the returned cards for the required summary, indicator, source and suggestions or links fields, and confirm that the card text reads correctly in the EHR's display. Record each failure with its cause: a timeout, a missing prefetch key, an empty prefetch block, an authorization error, or a card that fails validation. Timeouts and missing fields often trace back to prefetch templates that do not match what the EHR actually supplies, so keep a table of expected keys per hook and update it after every failed run.

Sandbox availability, its hook support and the data it holds are decided by the EHR vendor, not by DeployOpen or the HAPI FHIR project. Before you plan a test cycle, ask the vendor which CDS Hooks hooks and specification version the sandbox supports, whether it honors auto-prefetch or only template prefetch, how it authenticates calls to your service, how long it waits before treating a call as a timeout, and whether it can run against your public test endpoint. Confirm these answers in writing, because a sandbox that accepts a hook may still ignore the prefetch fields you rely on. Use synthetic patients only. Clinical data copied from production into a sandbox creates a privacy exposure and an audit problem, so build or obtain patient records that match the conditions your rules check. Test runs should also write the same audit records as production, including the access event for each $cds-services call, the source of the request and the identity or client used. Verify these entries in your audit store on the HAPI FHIR side and in the EHR's logs, and confirm that the sandbox run is labeled so that test activity cannot be mistaken for clinical use. The CDS Hooks specification is the reference for the request and card shapes you should check against.

Security and audit controls the operator must design

HAPI FHIR states that it does not provide a single, complete security layer. It offers building blocks, so the operator designs, configures and tests each control around the CDS Hooks service. The cards below cover the controls that most directly shape what a hook caller can reach and what gets recorded.

Authenticating hook callers

Only the EHR that issues a hook should be able to call your service endpoint. Decide how the service verifies the caller, such as a token issued by the EHR's identity provider, and where that check runs, either in the service code or at the gateway in front of it. Check that unauthenticated and expired-token requests are rejected in your test environment before any live EHR connection is made.

Limiting what the service reads

A CDS service should read only the resources its logic needs. Compare each prefetch template and each follow-up FHIR call against the data the recommendation actually uses. Configure the server's AuthorizationInterceptor so the service's client identity can read the resource types and compartments in that list and nothing else. Review this list whenever the CQL or PlanDefinition changes.

HAPI security docs

Consent and search narrowing

Consent interceptors and search narrowing let the server filter results for a given caller and patient context. Confirm which consent source your organization uses, how it is looked up during a hook call, and what happens when no consent record exists. Test that a search by the service cannot return records for a patient outside the context of the hook.

CORS scope

CORS governs which browser origins can call the FHIR server directly. Keep the allowed origins limited to the EHR and SMART app hosts you have approved, and avoid wildcard origins on any endpoint that returns patient data. Verify the policy in a browser test, since a permissive setting can expose data to pages you did not intend to serve.

BALP audit logging

BALP is the FHIR audit logging profile that HAPI FHIR can emit for access events. Decide which events the service must record, including the hook invocation, each read it performs and the card returned, and where those records are stored and how long they are kept. Confirm with your privacy and security teams that the log content meets their requirements before go-live, because the default configuration may not capture everything they need.

What buyers ask before building CDS Hooks services with HAPI FHIR

What drives the cost of building a CDS Hooks service on HAPI FHIR?

The cost is driven by how many hooks the service handles, how much patient data each one needs, and how much testing and security review the organization requires. Each hook needs its own clinical logic, prefetch design and error handling, so a service with several hooks takes more design and test effort than one with a single hook. Costs split into one-time work (design, build, integration with the EHR, security review and first testing cycle) and recurring work (content updates, EHR version changes, upgrades of HAPI FHIR and Java, and monitoring). Ask any partner to price these phases separately and to name who maintains the EHR sandbox connection after launch.

How long does a CDS Hooks build usually take?

Duration depends mostly on access to the EHR sandbox, the number of hooks and the clinical sign-off cycle, not on the HAPI FHIR code itself. If the EHR vendor's sandbox, client registration and test patient data are available early, the build can run in parallel with design. If they arrive late, the schedule slips by the same amount. Ask the EHR vendor to confirm sandbox provisioning steps, lead times and the test data they will supply, and ask your internal clinical and security reviewers to commit to review dates before work starts. A written scope should state the timeline and the dependencies it assumes.

What does the client need to provide for a CDS Hooks engagement?

The client provides access and decisions that only it can give. These include a running HAPI FHIR JPA server in infrastructure it controls, sandbox credentials from the EHR vendor, the clinical rules to implement and their owners, and the data classes the service may read. The client also needs a named clinical reviewer, a security contact who can approve the service's access model, and someone who owns the EHR relationship after go-live. Missing any of these usually shows up as waiting time rather than as a technical failure, so list them in the scope document before the build starts.

Can an internal team build CDS Hooks services without outside help?

An internal team with Java, FHIR and EHR integration experience can build a CDS Hooks service alone, provided it has time to learn the CDS Hooks request and response model and the HAPI FHIR server APIs. The harder parts are usually prefetch design, security and audit controls around patient data, and a test plan that covers the EHR sandbox. Teams often bring in outside help for the security review and the first end-to-end test, then keep routine changes in-house. Assess your team's skills in these areas honestly, and ask any partner to state which parts it would hand over to your staff.

How should prefetch design affect the effort estimate?

Prefetch design is one of the largest effort drivers, because every resource a service requests before it runs adds query logic, test cases and performance work. Services that rely on auto-prefetch from the EHR need fewer custom queries but must be tested against what the EHR actually sends. Services that request their own data through prefetch templates need careful review of each query, since broad queries increase exposure of patient data and slow responses. Plan time to measure response latency on the HAPI FHIR server with realistic patient volumes, and confirm with the EHR vendor which prefetch behavior its sandbox supports.

What security review is needed before a CDS Hooks service goes live?

The service needs a review of how it authenticates to the EHR, how it authorizes access to FHIR resources, and how it records access. HAPI FHIR does not provide a single security layer. It offers building blocks such as authentication interceptors, the AuthorizationInterceptor, consent and search narrowing interceptors, CORS support and BALP audit logging, so the design must assemble and test them for this service. Security review time grows with the number of resource types the service reads and the number of systems it calls. Ask your security team to define the review criteria early, and ask the implementation partner how each control will be verified.

How much testing does a CDS Hooks service need in the EHR sandbox?

Testing usually runs in several cycles: unit tests for the clinical logic, integration tests against a HAPI FHIR server with representative data, and end-to-end tests inside the EHR sandbox where cards are rendered and actions are tested. Each cycle can find prefetch, authorization or display problems that send the work back to design. The number of cycles depends on how many hooks exist, how many EHR workflows they touch and how quickly the sandbox can be reset. Ask the EHR vendor what sandbox test patients and reset options it provides, and ask the implementer to state how many test cycles its plan includes.

Limits to confirm in your environment before you commit

A CDS Hooks service is only as useful as the EHR that calls it. The cards below list the limits that decide whether a design works in your environment, and who on your side or the vendor's should confirm each one before scope and budget are fixed.

CDS Hooks specification version

Your EHR implements a specific version of the CDS Hooks specification, and it decides which hook types, card fields, prefetch behavior and feedback endpoints you can rely on. Ask the EHR vendor which version is live in your production and sandbox environments, and whether any hooks they plan to use are missing or behave differently. Get the answer in writing, because a service built against a newer version can fail silently against an older EHR.

HAPI FHIR source

HAPI FHIR and CDS library versions

Confirm the HAPI FHIR release and the CDS Hooks module version you plan to use, then check its Java requirement against your runtime. HAPI FHIR 8.2.0 requires JDK 17, and newer releases may raise that floor, so check your base images and application servers before you pick a version. Ask your platform team whether JDK 17 is already supported in your build pipeline and whether a version upgrade path is planned.

HAPI FHIR versions

Hook response latency

EHRs set time limits for how long a hook service may take to respond, and a slow service can be dropped from the workflow. Ask the EHR team for their response time expectation and whether it applies to each hook type. Measure your service against prefetch and database load under realistic record sizes, because a service that answers quickly in a test database may be too slow against production data.

Sandbox hook and data coverage

An EHR sandbox often supports fewer hooks, fewer resource types and less realistic data than production. Ask the vendor which hooks the sandbox fires, which FHIR resources it returns for prefetch and whether it supports auto-prefetch. Document any gaps, since a service that passes sandbox testing may still fail on a hook or resource that the sandbox does not exercise.

Authentication support in the EHR

Services that receive patient data must authenticate to the EHR and to your FHIR server, usually with SMART Backend Services or a similar token flow. Confirm with the EHR team which token flow, client registration process and scopes they support, and whether they can issue keys for your service. Then confirm that your identity provider and the AuthorizationInterceptor can enforce the same scopes, because HAPI FHIR provides building blocks rather than a complete security layer.

HAPI FHIR security

Audit logging gaps

Audit requirements for CDS calls depend on your policy and on what the EHR logs itself. Ask your compliance team which events must be recorded, such as hook invocations, prefetch reads and card returns, and whether BALP audit logging covers them. Confirm with the EHR team which side owns each audit record, so the logs can answer who saw which patient data and when.

How DeployOpen scopes and delivers CDS Hooks services on HAPI FHIR

DeployOpen plans, implements, hardens and documents self-hosted open-source platforms inside your own infrastructure, including CDS Hooks services that run against a HAPI FHIR JPA server. Each engagement starts from a written scope that names the services, hooks, prefetch templates, security controls and test evidence you receive. Most engagements are fixed-scope, so deliverables and timelines are agreed in writing before work begins.

How we scope

  • Inventory the CDS Hooks services you need, the hook each one answers and the EHR workflow it appears in
  • Agree which prefetch queries and auto-prefetch behavior each service depends on, and which FHIR resources they read
  • Confirm the identity, authorization and audit requirements your security and compliance teams will review before build starts

How we build

  • Implement @CdsService methods and the discovery endpoint on your HAPI FHIR server, deployed in your own cloud, data center or air-gapped network
  • Configure prefetch templates and FHIR access controls with the AuthorizationInterceptor and BALP audit logging, reviewed against your agreed design
  • Test each service against an EHR sandbox you choose, and record the hook requests, card responses and any failures for review

How we hand over

  • Deliver the service code, configuration, deployment manifests and a runbook covering hooks, prefetch and audit settings
  • Document the security design, access model and test results so your security and clinical informatics teams can review them
  • Walk your engineers through operating the services, including how to add a new hook and roll back a faulty release

How we support

  • Offer ongoing support, upgrades and continuous testing as a retainer, scoped to the services you run
  • Plan retesting after HAPI FHIR version upgrades that touch the Java runtime, interceptors or the JPA schema
  • Keep documentation and test evidence current as your CDS content and EHR integrations change

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.