Automating FHIR QuestionnaireResponses with Medplum Bots

A Medplum Bot is a serverless function that runs inside your Medplum project. Connected to a Questionnaire, it reads each QuestionnaireResponse as it is saved and turns the answers into clinical resources, such as AllergyIntolerance and MedicationRequest, so the frontend only submits the form. Medplum’s documentation covers how to write one. This post walks through a working example and then covers what Medplum’s guides leave to you: when the pattern pays off, and what to settle before a Bot handles patient data in production.
Questionnaires and QuestionnaireResponses are how a FHIR EHR collects data from its users, and most forms we build use them. A QuestionnaireResponse holds the answers. Later, those answers become specialized resources such as Patients, Observations and Conditions.
Without a clear structure, that conversion gets messy fast. Medplum Bots give it one: a place on the server where the conversion runs.
Key takeaways
What a Bot is
A TypeScript or JavaScript function that Medplum runs as a sandboxed AWS Lambda, with access to every resource in the project through Medplum’s SDK.
Where the work happens
The frontend saves only the QuestionnaireResponse. A Bot reads it and creates the specialized resources, such as AllergyIntolerance and MedicationRequest.
How it triggers
Connect the Bot on the Questionnaire’s Bots tab. Medplum creates a Subscription that runs the Bot when a related QuestionnaireResponse is saved.
How you debug it
A Subscription-triggered run is saved as an AuditEvent, with the Bot’s console output. A failed one carries the stack trace; a successful one has outcome 0.
What are Medplum Bots?
Bots are Medplum’s serverless functions. They run on AWS Lambda by default: you write the Bot’s code and choose how it is called, and Medplum handles the deploy. A Bot can read and write any resource in the Medplum project that its Access Policy allows and call any function in Medplum’s SDK. In practice, Bots are Medplum’s custom backend.
Bots cannot import your frontend code. To share code between Bots, Medplum supports Lambda Layers: separate files deployed alongside the Bots.
Bots must be activated on your Medplum project before you can use them, and Medplum’s plans differ in whether they include Bots and scheduled Bots.
Why use Bots instead of frontend code?
Medplum’s SDK also runs in the browser, so frontend code could create both the QuestionnaireResponse and the specialized resources. That has two costs. The user needs permission to write clinical resources they would not otherwise need. And the browser does the heavy processing, which slows the app down.

In this setup, the frontend sends every processed resource to the Medplum server. With a Bot, the processing moves to the server, and the frontend no longer handles sensitive or heavy work.

A Bot linked to a Questionnaire runs whenever a related QuestionnaireResponse is created, updated or deleted. Medplum also has other ways to trigger a Bot.
Security and performance
When a healthcare form collects health information, you have to decide where that information is processed. The technical discipline described in Strategic Software Engineering by Filipe Ximenes applies directly here. Our implementation showed that processing on the backend is a security requirement, not only a good practice.
In our implementation, using Bots with QuestionnaireResponse was the right choice for both performance and security. The Bot processes every answer with the context it needs. A QuestionnaireResponse alone doesn’t carry the full clinical context. An Observation does: it is structured health information about the patient, saved in the backend. So we create those resources in a Bot, on the server, and not in the browser.
Creating a Bot on Medplum
Create a Bot from Medplum’s admin interface: open the Bots page and click New. The “Create new Bot” page asks for a name, a description and an Access Policy. Only the name is required:

Medplum then opens the new Bot’s page on the Editor tab. The tab shows the Bot’s code, a field for the input to run it with, and an area for its output.

When the code is ready, click Save, then Deploy to deploy it to AWS Lambda. After a deploy, Execute runs the Bot from this page, which helps while you develop and debug.
In production, deploy from a pipeline instead, with Medplum’s deploy endpoint.
Connecting a Bot to a Questionnaire
To run a Bot when a QuestionnaireResponse is saved, link the Bot to the Questionnaire. Medplum does this on the Questionnaire’s Bots tab:

Behind the scenes, Medplum creates a Subscription resource that runs the Bot when the event happens. In the image above, the event is the creation of a QuestionnaireResponse for the “patient-intake” Questionnaire. The Subscription is saved in your Medplum project.
Why use Questionnaire and QuestionnaireResponse?
Why save a Questionnaire and a QuestionnaireResponse instead of creating the specialized resources when the form is submitted? Besides the built-in link to Bots, this approach:
- Follows FHIR’s structure, which Medplum is built around;
- Reuses Medplum’s QuestionnaireForm and QuestionnaireBuilder components, which render and edit
Questionnaireresources and produceQuestionnaireResponseresources; - Separates form logic from the specialized resources, so you decide when they are created by deciding when the Bot runs;
- Keeps a record of what the user answered, when, and in which
Questionnaire. A Practitioner can audit it, and you can rerun the Bot after a failure; - Keeps heavy processing out of the frontend, as described above.
Practical example: patient intake with a Medplum Bot
This example uses Medplum’s own Patient Intake demo. The intake process is usually a patient’s first contact with your EHR and collects the most information, so its Questionnaire is often one of the biggest in the system.
After you set up the demo, open the New Patient form: click Medplum’s logo to open the sidebar, then click New Patient:

QuestionnaireForm renders every question in the form from the Questionnaire resource. Take the Allergies section:

The section comes from this part of the Questionnaire resource:
{
"linkId": "allergies",
"text": "Allergies",
"type": "group",
"repeats": true,
"item": [
{
"linkId": "allergy-substance",
"text": "Substance",
"type": "choice",
"answerValueSet": "http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1186.8"
},
{
"linkId": "allergy-reaction",
"text": "Reaction",
"type": "string"
},
{
"linkId": "allergy-onset",
"text": "Onset",
"type": "dateTime"
}
]
}Each item has a linkId. The QuestionnaireResponse repeats that linkId beside each answer, which is how the Bot will match answers to questions.
Triggering the Bot
The intake form saves its answers in a QuestionnaireResponse that mirrors the structure of the Questionnaire. Take these answers:

They produce this QuestionnaireResponse:
[..., {
"id": "id-94",
"linkId": "allergies",
"text": "Allergies",
"item": [
{
"id": "id-95",
"linkId": "allergy-substance",
"text": "Substance",
"answer": [
{
"valueCoding": {
"system": "http://snomed.info/sct",
"code": "102264005",
"display": "Cheese (substance)"
}
}
]
},
{
"id": "id-96",
"linkId": "allergy-reaction",
"text": "Reaction",
"answer": [
{
"valueString": "Mild"
}
]
},
{
"id": "id-97",
"linkId": "allergy-onset",
"text": "Onset",
"answer": [
{
"valueDateTime": "2024-12-20T03:00:00.000Z"
}
]
}
]
},
{
"id": "id-147",
"linkId": "allergies",
"text": "Allergies",
"item": [
{
"id": "id-148",
"linkId": "allergy-substance",
"text": "Substance",
"answer": [
{
"valueCoding": {
"system": "http://snomed.info/sct",
"code": "102263004",
"display": "Eggs"
}
}
]
},
{
"id": "id-149",
"linkId": "allergy-reaction",
"text": "Reaction",
"answer": [
{
"valueString": "Severe"
}
]
},
{
"id": "id-150",
"linkId": "allergy-onset",
"text": "Onset",
"answer": [
{
"valueDateTime": "2024-12-20T03:00:00.000Z"
}
]
}
]
},
{
"id": "id-98",
"linkId": "medications",
"text": "Current medications",
"item": [
{
"id": "id-99",
"linkId": "medication-code",
"text": "Medication Name",
"answer": [
{
"valueCoding": {
"system": "http://www.nlm.nih.gov/research/umls/rxnorm",
"code": "1007388",
"display": "Lactase / rennet"
}
}
]
}
]
}, ...]These answers map to two resources, AllergyIntolerance and MedicationRequest. The frontend does not create them. Saving the QuestionnaireResponse triggers the Bot, which reads the answers and creates the resources.
const response: QuestionnaireResponse = event.input;The Bot receives the whole QuestionnaireResponse in the event’s input, as the line above shows. From there it can parse the answers however it needs.
In the excerpt below, patient is the Patient the Bot created or updated earlier in the same run, and getGroupRepeatedAnswers and PROFILE_URLS come from the demo’s utils layer. The other helpers come from @medplum/core.
const questionnaire: Questionnaire = await medplum.readReference({
reference: response.questionnaire,
});
const allergies = getGroupRepeatedAnswers(
questionnaire, response, "allergies",
);
for (const allergy of allergies) {
const code = allergy['allergy-substance']?.valueCoding;
if (!code) {
continue;
}
const reaction = allergy['allergy-reaction']?.valueString;
const onsetDateTime = allergy['allergy-onset']?.valueDateTime;
await medplum.upsertResource(
{
resourceType: 'AllergyIntolerance',
meta: {
profile: [PROFILE_URLS.AllergyIntolerance],
},
clinicalStatus: {
text: 'Active',
coding: [
{
system: 'http://hl7.org/fhir/ValueSet/allergyintolerance-clinical',
code: 'active',
display: 'Active',
},
],
},
verificationStatus: {
text: 'Unconfirmed',
coding: [
{
system: 'http://hl7.org/fhir/ValueSet/allergyintolerance-verification',
code: 'unconfirmed',
display: 'Unconfirmed',
},
],
},
patient: createReference(patient),
code: { coding: [code] },
reaction: reaction ? [{ manifestation: [{ text: reaction }] }] : undefined,
onsetDateTime,
},
{
patient: getReferenceString(patient),
code: `${code.system}|${code.code}`,
}
);
}This code creates AllergyIntolerance resources from the Allergies section of the QuestionnaireResponse. It:
- Collects the allergy answers with
getGroupRepeatedAnswers; - Loops through each allergy and reads its values by linkId;
- Fills an
AllergyIntolerancefrom those values.

The Bot does the same for MedicationRequest with the Medications section. The demo’s full Bot code and its utils layer are on GitHub. Every helper comes from Medplum’s SDK or that utils layer.
When the run ends, the specialized resources exist in Medplum:

Debugging and auditing Bot executions
Bots can fail like any other code. Medplum records every Bot execution as an AuditEvent, listed on the Bot’s page in the admin interface.

The example above shows two executions:
- The bottom one failed because of a bug in the Bot. Its stack trace shows where the error happened;
- The top one succeeded. It has no stack trace, and its
Outcomeis 0.
Running Medplum Bots in production
The demo shows the pattern. These are the decisions that come up once a Bot handles real intake forms.
When should a Bot process the form?
Use a Bot when the answers become clinical resources, when creating them needs permissions the person filling in the form should not have, or when the same conversion has to run for responses that arrive another way, such as an API call or an import. If nothing is created from the answers beyond the QuestionnaireResponse itself, a Bot adds a moving part without a reason.
Make the Bot safe to run twice
Medplum does not guarantee the order in which Subscriptions deliver events, and you will rerun a Bot after a failure. The demo uses upsertResource with search criteria (the patient and the allergy code), so a second run updates the AllergyIntolerance instead of creating a duplicate. A Bot that calls createResource creates a new record on every run. Key each resource on something stable, such as the patient and code or the QuestionnaireResponse’s ID.
Test Bots without a server
Medplum’s MockClient keeps resources in memory, so a Bot’s handler can run in a unit test with Jest or Vitest. Create a new client for each test, add the resources the Bot reads, call the handler and search for what it should have created:
import { MockClient } from '@medplum/mock';
import { expect, test } from 'vitest';
import { handler } from './intake-form';
import { intakeResponse } from './fixtures';
test('creates one AllergyIntolerance per allergy answer', async () => {
const medplum = new MockClient();
const input = await medplum.createResource(intakeResponse);
await handler(medplum, {
bot: { reference: 'Bot/intake-form' },
input,
contentType: 'application/fhir+json',
secrets: {},
});
const allergies = await medplum.searchResources('AllergyIntolerance');
expect(allergies).toHaveLength(2);
});Run the same test twice against the same client to check that the Bot is safe to rerun. Keep the fixtures synthetic: never copy a real patient’s answers into a test.
Give the Bot only the access it needs
Use the Access Policy field on the Create new Bot form. Give the Bot a policy that reads Questionnaire and QuestionnaireResponse and writes only the resources it creates. Keep the client credentials your pipeline deploys with out of source control: by default they can only read Bots, so grant write access to Bot to that client alone.
Deploy from CI, not from the editor
The Editor tab’s Deploy button is fine while you develop. In production, deploy with Medplum’s CLI (npx medplum bot deploy) from your pipeline, so the code that runs is the code that was reviewed. Bots also handle integrations: we used one to sync patient data between Medplum and Epic.
Keep patient data out of the logs
The AuditEvent for each run stores what the Bot printed. Log resource references, such as QuestionnaireResponse/123, and never the answers. The same rule applies to every Lambda function that handles PHI.
Frequently asked questions
What is a Medplum Bot?
A Bot is a single TypeScript or JavaScript file with an async handler function. Medplum runs it as a sandboxed AWS Lambda: on hosted Medplum in Medplum’s environment, on a self-hosted server in your own AWS account. It can read and write the resources its Access Policy allows in the Medplum project, through Medplum’s SDK, so it plays the role of a custom backend without a server of your own.
How do I run a Medplum Bot when a QuestionnaireResponse is created?
Open the Questionnaire in Medplum’s admin interface, go to its Bots tab and connect the Bot. Medplum creates a Subscription that runs the Bot when a QuestionnaireResponse for that Questionnaire is saved, and the tab lets you choose the trigger event. A Bot can also run from its $execute endpoint or on a schedule.
What is the difference between a Medplum Bot and a Subscription?
A Subscription is the FHIR resource that watches for changes that match its criteria and sends a notification. A Bot is the code that runs. Connecting a Bot to a Questionnaire creates a Subscription that calls the Bot. A Subscription can also post to an endpoint of your own when the logic lives in your backend instead.
How do I automate clinical workflows with Medplum Bots and Subscriptions?
Start where the data enters: a Bot connected to the intake Questionnaire turns answers into clinical resources. Then add Subscriptions on the resources that drive the next steps, such as a Task or a ServiceRequest, each calling a Bot that does one job. We built one that emails a practitioner when a Task is assigned.
Should I turn QuestionnaireResponses into FHIR resources in the frontend or in a Bot?
In a Bot. The frontend then only needs permission to save the QuestionnaireResponse, not to write clinical resources, the heavy processing leaves the browser, and the response stays on record as what the user answered at that time.
How does a Bot read the answers in a QuestionnaireResponse?
The Bot receives the whole QuestionnaireResponse as event.input. It matches each answer to its question by linkId, the identifier the Questionnaire gives every item. For repeated groups such as a list of allergies, the patient intake demo uses a helper, getGroupRepeatedAnswers, that returns one set of answers per group.
How do I debug a Medplum Bot that failed?
Open the Bot’s Event tab in the admin interface. Each Subscription-triggered run is an AuditEvent: a failed one includes the stack trace, and a successful one shows 0 in the Outcome column. The AuditEvent also stores what the Bot printed, so log resource references such as QuestionnaireResponse/123, never the answers, which are patient data. While developing, you can run the Bot from its Editor tab with a sample input.
How do I deploy Medplum Bots in production?
The Editor tab’s Save and Deploy buttons are fine during development. For production, deploy from your pipeline with Medplum’s CLI (npx medplum bot deploy) or the Bot deploy operation, so the code that runs is the code in your repository.
Can I run Medplum Bots on a self-hosted server?
Yes. On hosted Medplum, Bots run in Medplum’s environment. On a self-hosted server they run in your own AWS account, and you publish the Bot Lambda layers yourself, since they do not publish on their own.
Are Bots available on every Medplum project?
No. Bots are disabled by default and only project administrators can use them; Medplum enables them on request. Medplum’s pricing page shows which plans include Bots and scheduled Bots.
Who can help build Medplum Bots?
Vinta builds healthcare products on Medplum, including the Bots that turn form answers into FHIR resources, integrations with EHRs such as Epic and the clinical workflows around them.
References
- Bot basics, Medplum documentation
- Bot Lambda layers, Medplum documentation
- Bot deploy operation, Medplum documentation
- Bot for QuestionnaireResponse, Medplum documentation
- Unit testing Bots, Medplum documentation
- Bots in production, Medplum documentation
- Pricing, Medplum
- Patient intake demo, Medplum on GitHub
Related articles

Article · 9 min read
Is AWS Lambda HIPAA compliant? Where PHI leaks in serverless
Lambda is HIPAA eligible under the AWS BAA. Where PHI still leaks, and how to stop it.
9 min read

Article · 4 min read
FHIR Subscriptions on Medplum: building real-time healthcare integrations
Real-time integrations on Medplum with webhooks, email alerts and Bot automation.
4 min read




