Custom FHIR operations with Medplum Bots

Medplum lets you expose your own JavaScript logic as standard FHIR operations invoked over HTTP. This page covers when that fits, how the OperationDefinition and Bot pair works, and what to validate and confirm on a self-hosted deployment.

On this page

When custom FHIR operations with Medplum Bots fit your workflow

A team needs business logic such as an eligibility check, a derived clinical summary or an intake transform, and every app that needs it should call it the same way through the FHIR API instead of through a separate, ad hoc endpoint per application. Medplum Custom FHIR Operations address that need. They combine FHIR operations with Bots, so custom JavaScript is exposed as a standard FHIR operation and invoked over HTTP. The caller sends a request to a named operation on the FHIR server, gets a FHIR-shaped response, and does not need to know that a Bot is doing the work. This keeps the integration surface inside the FHIR API your apps already authenticate against, with the same access controls and audit trail.

Choose custom operations when the caller asks for a result and waits for it: a synchronous answer about a Patient, Coverage or Encounter that a front end, portal or partner system needs now. Use a Subscription instead when the work should follow a change in data, such as sending a notification after an Observation is created, and the caller does not need to wait for a response. Use a plain Bot when the trigger is a schedule, a manual run or an integration that does not need a standard FHIR entry point. Before you commit, confirm with your Medplum contact or the Medplum docs: Custom FHIR Operations which operation shapes, input types and response formats your Medplum version supports, and map each planned operation to the caller that will invoke it.

How a custom operation request reaches your Bot

The request starts in a client application that calls the $operation endpoint on the self-hosted Medplum FHIR API, which sits on the far side of the trust boundary. The Medplum server matches the call to an OperationDefinition, reads the linked Bot, and passes the parameters to the Bot execution backend. The Bot's result returns through the server as a FHIR-shaped response, and the server reads its stored definitions and records from PostgreSQL along the way. Check the authentication step at the boundary, the parameter names the Bot receives, and the response type it returns.

Request path for a custom FHIR operation across the client, server, Bot backend and database.

Configuration choices and when each fits

This table compares the four main design choices for a custom FHIR operation on self-hosted Medplum: operation scope, Bot identity, request handling and execution backend. Read each row for the situation where the option fits and the cost it carries in access scope or coupling. The main takeaway is that the narrowest identity and the simplest synchronous path are usually the right starting point, with other choices added only when a requirement demands them.

DecisionWhen it fitsWhat it costs
Operation at type levelThe logic works across a resource type, such as validating or transforming any Patient or Encounter submitted to the server.The Bot receives requests for every instance of the type, so input checks and access rules must handle all of them.
Operation at instance levelThe logic acts on one specific resource, such as a single Encounter's close-out or a single Claim's recalculation.Clients must know the resource ID, and the operation definition and Bot logic must handle the target's current state carefully.
Bot with its own access policyThe operation performs a defined integration task that needs the same data each time regardless of who calls it, such as a partner feed.The Bot's membership and access policy must be maintained as a separate identity, and it can read more than a given caller should see.
Bot with runAsUserCallers with different roles should get results limited to their own access, such as clinicians seeing only the patients they are allowed to view.Logic that depends on broader data may fail for some callers, and each caller's permissions must be tested individually.
Synchronous request handlingThe caller needs the result in the same HTTP response, such as a calculated score or a validated payload before saving.The caller waits for execution, so slow logic affects the client, and long tasks can time out or hold resources.
Subscription-triggered BotWork follows a change to a resource and the caller does not need an answer, such as notifications or downstream updates.The result is not returned to the original caller, so failures need monitoring and replay plans, and the flow is harder to trace.
Medplum-managed executionYour team wants Medplum to run Bots with the default tooling and fewer moving parts to operate on the self-hosted deployment.You accept Medplum's runtime conventions and have less control over networking, packaging and scaling of the function.
External execution backendYour organization needs its own naming, IAM boundaries, isolation or cluster placement, such as a Kubernetes or cloud function environment.You own the extra build, deployment, permissions and monitoring work, and the operation is coupled to that backend's setup.

Setting up a custom operation on a self-hosted Medplum server

This sequence takes a custom FHIR operation from a confirmed server version to a tested endpoint that a client can call over HTTP, with a logged execution at each stage. Each step ends with a check so the team knows the operation works before it reaches production.

  1. Confirm server version and upgrade path

    Before writing any code, confirm which Medplum server version your self-hosted deployment runs and which version you plan to target. Medplum's upgrading guide says self-hosted servers must move through each minor version in sequence, and skipping versions can cause startup failures, so the upgrade path must be settled first. Ask your platform team to record the current version and any pending upgrade in the change log. The step is done when the team agrees on one version to build against and the target environment matches it.

  2. Create the Bot in a non-production project

    Create a new Bot in a development project on your self-hosted server, not in the production project. Give it a clear name that reflects the business operation, and note the Bot's ID, since the OperationDefinition will reference it later. Keep the Bot's access policy narrow while you build, because the Bot will only be able to read or write what its membership allows. The check is that the Bot appears in the development project with its own ID and that you can open its settings in the web app.

  3. Write the JavaScript handler

    Write the handler in JavaScript or TypeScript as a Medplum Bot function that receives the request and returns a FHIR resource or Parameters result. Validate every input in the handler before it touches the FHIR API, returning a clear error for missing or malformed parameters. Keep business logic in pure functions where possible so unit tests can cover them without a live server. The step is complete when the handler runs locally against sample input and produces the expected output object.

  4. Define the OperationDefinition and its parameters

    Create an OperationDefinition resource that names the operation, sets its code, lists its input and output parameters with their types and cardinality, and states the resource types it applies to. Parameter names and types should follow FHIR conventions so that clients familiar with standard operations can call it without special documentation. Store the resource in the development project. The check is that the server accepts the resource and that its parameter list matches what the handler reads and returns.

  5. Bind the operation to the Bot

    Link the OperationDefinition to the Bot so that a call to the operation's endpoint executes the Bot's handler. Confirm the binding in the resource's references, then trigger a test call from a client with a valid token. Check that the response matches the expected FHIR result, including the status code and body shape. If the call fails, review the Bot's logs and the handler's input validation before changing the binding.

  6. Deploy through the chosen path

    Move the Bot code and the OperationDefinition from the development project to the target project using the deployment method your team has chosen, such as the Medplum CLI run from a pipeline. Keep the deployment in version control so every change can be traced to a commit. Confirm that the production project has the same Bot code and OperationDefinition as the reviewed build, with no manual edits in the web editor. The check is a matching deployment record and a passing smoke call in the target environment.

  7. Call the operation over HTTP

    Invoke the operation with an HTTP POST to the operation endpoint on the server, passing parameters in a FHIR Parameters resource and authenticating with an approved client or user token. Compare the response with the expected FHIR result from your test cases and confirm the status code and resource type. Then open the AuditEvent resources for the execution to confirm that the call was recorded with the caller and the Bot that ran. The step is done when the response is correct and the AuditEvent exists for that call.

  8. Verify conformance and record the audit trail

    Run the operation with valid, incomplete and malformed inputs to confirm it returns the correct FHIR error responses rather than failing silently. Check that every test run produces an AuditEvent, and record the results alongside the OperationDefinition version. Ask your compliance or security lead to review the audit records and the access policy before the operation is released to clients. The step is complete when the negative tests pass, the audit trail is confirmed, and the team has signed off on the release.

Validating inputs and keeping responses FHIR conformant

Validation belongs inside the Bot that implements the operation, before any write happens. The Bot receives the operation's parameters as a Parameters resource, so the first job is to check that each expected parameter name is present, that it carries the value type you declared in the OperationDefinition, and that unexpected inputs are rejected rather than silently ignored. When a check fails, return an OperationOutcome with an issue that names the problem and the parameter at fault, so the caller's client can show a useful error. Next, check the resource types you read or create. Confirm that a referenced resource is the type your logic expects, that required fields such as the subject or status are populated, and that codes come from the value sets your organization has agreed to use. Do these checks before any createResource or updateResource call, because a partial write from a half-validated request is harder to unwind than a clean rejection.

The response is the other half of conformance. Whatever the operation declares as its output, whether a Parameters resource with named outputs or a single resource type, the Bot should return exactly that shape on every success path, and the same shape on every error path that is not an OperationOutcome. Write tests that call the Bot logic directly with valid inputs, malformed inputs, missing fields and wrong resource types, and assert on both the status path and the structure of the returned resource. Keep a small set of sample requests and their expected responses in version control so that a change to the Bot or the OperationDefinition shows up as a failing test. Validate the outputs against the base FHIR specification for the version your deployment uses, and confirm any profile or implementation guide your organization follows, since the base specification alone does not capture local requirements. The exact conformance tooling and profile set are for your team to confirm with your standards owner and the Medplum custom FHIR operations docs before you commit to a design.

Security risks for operations that touch clinical data

A custom FHIR operation runs your code with a identity, against clinical records, and is reachable over HTTP. The risks below share one root: an operation that can do more than its caller should be allowed to do, or leaves no trace of what it did. Each card names the control to apply and what to verify in your own project, because access behavior depends on how your Bots, memberships and policies are configured.

Over-broad Bot access policies

A Bot that backs an operation runs with the access its project membership grants. If that membership is a broad administrator role, a single bug in the handler can read or change any resource in the project. Create a dedicated Bot membership for each operation, scoped to the resource types and compartments it needs, and review it whenever the handler changes. Ask your team to confirm, in writing, which resource types each membership can read and write before the operation reaches production.

Custom operations docs

Data exposure beyond caller rights

An operation can return data the calling user could not retrieve through a normal search, because the Bot reads with its own identity. Consider whether the operation should run as the caller, so that the caller's access policies still apply to every read. Test this with a user who lacks access to a sample patient and confirm the response is empty or refused. Document which operations run as the caller and which deliberately use a service identity.

Secrets embedded in handler code

Hard-coded API keys, database passwords or third-party tokens in an operation's source end up in version control, logs and copies of the Bot. Store credentials as project secrets and read them from the Bot environment at runtime. Separate development and production projects so test credentials never reach clinical data. Ask who can edit secrets and how rotation is handled, since these answers are usually what an assessor asks first.

Unauthenticated or weakly authenticated callers

An operation is an HTTP endpoint, so every caller must prove who it is. Confirm that the operation is invoked only with a valid token, and choose the client type deliberately: an interactive user session, a client credentials client for server-to-server calls, or a multi-factor flow for staff. Client credentials are powerful and easy to over-share, so limit each client to the operations it calls. Verify that anonymous requests are rejected in your environment, not assumed.

Medplum auth docs

Missing audit trails

Without a record of each execution, you cannot tell who invoked an operation, what it read or wrote, or whether a failed call changed data. Medplum records AuditEvents for Bot executions, and these should be reviewed alongside your own access logs. Decide how long these records are kept under your retention policy, and test that a sample invocation produces a traceable entry. Treat a gap in the audit trail as a defect to fix before go-live.

Questions teams ask before building custom FHIR operations

How much effort does a first custom FHIR operation take?

A first operation is mostly a design and verification exercise, and the effort depends on how precisely the business rule can be described. The main drivers are the number of inputs and outputs, how many FHIR resources the logic reads and writes, whether the operation must be idempotent, and how many edge cases the rule has. Expect a first operation to include the OperationDefinition, the Bot, input validation, unit tests, a deployment path into each environment and a sign-off from the people who own the rule. Later operations reuse that scaffolding, so the second and third usually cost less. Ask any partner for a quote that lists each of these items separately, since a bare total hides where the time goes.

Can an in-house team build and run custom operations without a partner?

Yes, if the team has JavaScript or TypeScript skills, experience with FHIR resource structures and someone who can own the deployment and access model. The harder part is usually not the code but the ongoing ownership: keeping the OperationDefinition aligned with the business rule, reviewing changes, managing secrets and access policies for the Bot, and testing against each new Medplum release. Work out who is accountable for each of those before deciding. A partner can cover the first build, a knowledge transfer and periodic review, which is often a better fit than an open-ended retainer for a team that wants to keep control.

What does a custom operation need from clinical and security stakeholders?

Clinical stakeholders define what the operation must return and when it is valid, such as which codes, statuses or patient conditions trigger a result. Security and privacy stakeholders decide what data the Bot may read and write, under which identity it runs and how its output is logged. Ask clinical leads for worked examples with expected inputs and outputs, and ask security teams to review the Bot's access policy before the first production call. Both groups should sign off on the input validation rules, because an operation that accepts loosely checked clinical data can produce results that look authoritative but are wrong.

How do custom operations change during Medplum upgrades?

Custom operations sit on top of Medplum's FHIR API and Bot runtime, so each upgrade is a checkpoint for them. Medplum says a self-hosted server must be upgraded through each minor version in sequence, and skipping versions causes startup failures, so your operations need to be retested at every step rather than only at the end. Keep the OperationDefinition and Bot under version control, run your test suite against each target version in a non-production project and confirm that the Bot runtime and any Node.js or dependency changes do not alter responses. Check the upgrade guide before scheduling the change, and plan rollback steps for the operation code alongside the server.

When should a team choose a Subscription or a plain Bot instead?

Choose a custom FHIR operation when a caller needs an explicit, on-demand result that returns over HTTP, such as a calculated eligibility answer or a generated summary. Choose a plain Bot when the logic runs on a schedule or as a server-side task that no caller waits on. Choose a Subscription when the logic should react to a resource change, such as a new Observation, without any client asking for it. The deciding questions are who triggers the work, whether the caller needs the result in the same request and how failures should surface. Many systems use more than one of these patterns, so design the boundaries before building.

Which parts of a custom operation do the most damage when they fail?

The most common failures are loose input validation, operations that quietly return non-conformant FHIR resources and Bots that write data under an identity with broader access than the caller should have. Each one can pass a basic smoke test while still causing downstream errors. Ask your team to test invalid inputs, missing optional fields and unexpected resource types, and to check every returned resource against the FHIR definitions your deployment targets. Review the run-as identity and access policy as part of the same change so that a successful test does not hide an access problem.

Does the Medplum compliance program cover a custom operation?

Medplum's compliance documentation states that compliance is a shared responsibility between Medplum and its customers, so the code you add to a self-hosted deployment is part of your side of that split. Your evidence for a custom operation includes its specification, tests, access policy, change history and audit logs. DeployOpen prepares systems, controls and evidence for compliance assessments, but independent auditors and certification bodies issue any audit report or certification. Confirm with your assessor which records they expect for custom application logic before the operation goes live.

What should a quote for custom FHIR operations include?

A useful quote lists the operations in scope, the inputs and outputs of each, the FHIR resources they touch, the test and validation approach, the deployment path into each environment and the handover or support model afterward. It should also say who owns the code repository, who approves changes and what happens at each Medplum upgrade. Engagements are normally fixed-scope, with scope, deliverables and timelines agreed in writing before work starts. Ongoing support and upgrade testing can be quoted separately as a retainer, which lets you compare the one-time build with the recurring cost.

Keeping custom operations working through Medplum upgrades

Self-hosted Medplum must be upgraded through each minor version in sequence, so a custom operation has to survive every step, not just the final version you land on. Skipping steps causes startup failures according to the upgrade guide, which means your operation tests should run after each intermediate version is deployed to a staging project, not once at the end. Before the first upgrade, record which Medplum version each custom operation was last verified against, and keep that record with the Bot code so the history stays attached to the code it describes.

Pin the Bot source in version control with the exact OperationDefinition resource that exposes each operation, including its code, resource and parameter definitions, and the Bot identifier it points to. Treat changes to the operation's parameter list or response shape as interface changes that need a version note for the teams calling it over HTTP. After each upgrade, rerun a fixed set of invocations against the staging server and compare the responses with the recorded baseline. Check that required inputs are still rejected with an OperationOutcome that names the problem, since changes to how the server reports validation errors are the kind of drift that breaks client error handling without failing any build.

Plan the rollback window before the upgrade starts. Confirm with your database team whether a rollback to the prior version is supported once post-deploy data migrations have run, because a rollback path that depends on the old schema may not exist after the migration completes. Keep the previous Bot deployment and its OperationDefinition available so you can reverse the Bot change independently of the server change. Check the Medplum upgrading guide for the current steps and ask your vendor contact to confirm what they support for rollback in your version path.

How DeployOpen scopes and delivers custom Medplum operations

DeployOpen scopes, builds, tests and hands over custom FHIR operations on a Medplum deployment that runs in infrastructure you control. Each engagement starts with a written scope that names the business logic, the FHIR resources involved and the operations your systems will call.

How we scope

  • We list each business rule you want exposed and map it to a FHIR operation, its input parameters and its output.
  • We confirm which FHIR resources the operation reads and writes, and which Bot identity and access policies it will run under.
  • Engagements are fixed-scope, so deliverables, timelines and acceptance tests are agreed in writing before build work starts.

How we build

  • We write each OperationDefinition and its paired Bot, with input validation that rejects malformed requests before any data changes.
  • We test each operation against the FHIR conformance rules for its resource type and the expected responses for valid and invalid inputs.
  • We check that operations run under least-privilege access and that no credentials are hard-coded in Bot source code.

How we hand over

  • You receive the OperationDefinition and Bot source, the test suite, and documentation of each operation's inputs, outputs and error responses.
  • We document how to deploy operations to your environment and how to invoke them through the FHIR API from your client applications.
  • Handover includes a walkthrough with your engineers so your team can extend, review and troubleshoot the operations after delivery.

How we support

  • Ongoing support, upgrades and continuous testing are available as retainers, including checks after each Medplum version change.
  • We can review operations when your data model changes or when you add new callers, so conformance and access rules stay current.
  • Ask your quote to separate one-time build work from any recurring support, testing and upgrade effort in the retainer.

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.