Automating questionnaire responses with Medplum Bots

A practical guide to turning submitted FHIR questionnaire responses into structured Patients, Observations and Tasks with Medplum Subscriptions and Bots, including error handling for incomplete answers.

On this page

Automating questionnaire responses with Medplum Bots: when a form should write structured data

A form submission in Medplum is stored as a QuestionnaireResponse resource, and that resource alone does not create the Patient, Observation or Task your workflow needs. A Medplum Bot is the server-side logic that reads the response and writes structured FHIR data. A Subscription on QuestionnaireResponse triggers the Bot when a response is created or updated, so the Bot runs without a user opening the form. Bots run inside the self-hosted Medplum server, which is built on Node.js and TypeScript and uses PostgreSQL as its database and Redis as its cache. Your team therefore operates the Bot runtime, its database and its cache alongside the rest of the deployment, and those components need to be sized and monitored for form traffic.

This pattern fits when the answers map to a small, predictable set of resources, such as intake demographics becoming a Patient, a screening score becoming an Observation, or a referral answer creating a Task for a care coordinator. It fits less well when the mapping is large, changes often, or must be shared with systems outside Medplum, because the mapping then lives in code that needs tests and a release process. Before you build, confirm which questionnaire items are required, how the Bot should treat partial answers (for example, a skipped optional item versus a missing required one), and whether the Bot must write under the submitter's identity or a dedicated integration identity. These choices determine the access policy the Bot needs and the error paths you must test.

Verify the Subscription criteria, the Bot's input handling and its failure behavior in a non-production project before you connect live forms. Check the Subscription's status and the resulting AuditEvents after a test submission, and confirm that an incomplete response leaves a visible record for staff rather than failing silently. Ask your Medplum support contact or review the current Subscription and Bot documentation for per-project limits and retry behavior in your version, since these details change between releases. Compare the Bot approach with the FHIR $extract operation, which can convert a questionnaire response into resources using a StructureMap, when the mapping is stable and the team prefers declarative rules. The right choice depends on how much logic the mapping needs and who will maintain it.

How a submitted form flows through a Subscription and a Bot

The flow starts when a patient or staff member submits a form, which Medplum stores as a QuestionnaireResponse. A Subscription whose criteria match that resource triggers a Bot running inside the self-hosted server. The Bot checks each answer, then writes Patient, Observation or Task resources to the PostgreSQL database. When answers are incomplete, the Bot should take the error branch and record a Task or a clear failure instead of partial writes. Check that the Subscription criteria, the Bot's access policy and the database boundary all sit inside your own infrastructure.

Form submission to structured FHIR resources, with the error branch inside the self-hosted boundary.

$extract versus a Bot: which path fits which form

When each answer copies into one element of one resource and no answer changes what happens to another, $extract is the simpler route to evaluate. The mapping is a definition the team writes once and reviews when the questionnaire changes. Confirm in your Medplum version that $extract is available and how it expects the mapping to be supplied, because support can vary by release.

  • Mapping shape: each question maps to one target element, such as a single date copied into a birth date field, with no dependence on other answers.
  • Maintenance: the team maintains the mapping definition alongside the questionnaire, so a question change and a mapping change should go through the same review.
  • Error surface: validation problems appear in the response to the request that runs the extraction, so the caller sees them at that point. Confirm the exact error shape for your version.
  • Limits: looking up an existing record, detecting duplicates and creating resources only under certain conditions are not expressed in a straight copy.

Before committing a form to this route, run a sample response through the operation in a non-production project and check that the output matches what you expect.

Which Subscription and Bot configuration fits each form workflow

This table compares the main configuration choices for turning a submitted QuestionnaireResponse into FHIR data, including trigger scope, target resources, execution mode, identity and retries. Read each row as a decision: the right option depends on how time-sensitive the form is and how much audit evidence your compliance team needs.

Configuration choiceWhen it fitsTrade-off in a regulated deployment
Subscription criteria scoped to completed QuestionnaireResponseForms that should only create records once the patient or staff member has submitted all required answersDrafts and partial saves do not trigger the Bot, but you must confirm how your form client sets QuestionnaireResponse status before relying on this filter
Subscription on every QuestionnaireResponse updateWorkflows that intentionally react to in-progress answers, such as flagging a red-flag symptom during intakeEach save fires a run, which multiplies AuditEvents and can create duplicate Patients or Tasks unless the Bot checks for existing records
Bot target: Patient creationRegistration or referral forms where no matching Patient exists yetIdentity matching becomes the main risk; a Bot that creates without a duplicate check can produce records that need manual merging later
Bot target: Observation creationStructured clinical measures such as scores, vitals or screening results captured in form itemsEach Observation needs a correct code and subject reference; mistakes in LOINC mapping are clinical data-quality issues that reviewers must catch
Bot target: Task creationRouting incomplete or flagged answers to a staff queue for follow-upTasks are a low-risk way to hand work to people, but assignment rules and access to the Task must be confirmed before go-live
Synchronous handling (Bot called from the form flow)Short workflows where the patient needs an immediate confirmation or validation messageThe user waits on the Bot, so timeouts and error messages become part of the user experience and must be tested
Asynchronous handling (Subscription triggers the Bot)Heavier processing, multiple writes or workflows that must survive a brief outageErrors surface later and can be missed, so failure alerts and a named owner for the queue are needed
Run-as identity: dedicated Bot identity with least privilegeMost production Bots that write Patients, Observations or Tasks on behalf of the systemThe Bot can act beyond what the submitting user may do, so access policies must be tightly scoped and reviewed
Run-as identity: runAsUser inheriting the caller's accessBots that should only write what the submitter is allowed to see or changeAccurate attribution is easier to evidence, but anonymous or self-registration forms may lack a user with enough rights to complete the write
Retry and manual reprocessingForms where a failed write must be recovered without asking the patient to resubmitReplays can duplicate records unless the Bot is idempotent; confirm your replay procedure and who is allowed to trigger it

How to set up questionnaire-to-resource automation on a self-hosted Medplum

This sequence takes a submitted questionnaire from a version-checked self-hosted Medplum install to a tested Bot and Subscription that turn QuestionnaireResponse answers into FHIR resources. Each step ends with a check so the team knows when to move on.

  1. Confirm the Medplum version and upgrade path

    The platform team checks the Medplum version running on the self-hosted server against the latest release listed on the GitHub releases page, and confirms which minor versions sit between the current version and the target. Self-hosted Medplum must be upgraded through each minor version in sequence, and skipping versions causes startup failures, so the upgrade path is written down before any Bot work begins. Check: the team can name the running version, the target version and every intermediate minor version, and the staging environment runs the target version.

  2. Define the questionnaire and its mapping

    The clinical informatics lead and a developer agree on the Questionnaire, its linkIds and answer types, and a written mapping from each answer to a target resource such as Patient, Observation or Task. The mapping states which answers are required, which codes or units apply, and what the Bot does when a required answer is missing. Check: every linkId in the Questionnaire appears once in the mapping table, and each target field has a named owner and a sample value.

  3. Create the Bot in a development project

    A developer creates the Bot in a development project on the self-hosted instance, not in production, and sets its runtime and input type to match the QuestionnaireResponse payload. Only the Bot's own identity and the minimum memberships it needs are granted at this stage. Check: the Bot appears in the development project, a test invocation with a hand-built QuestionnaireResponse returns a response from the Bot, and the Bot's identity is listed separately from any staff account.

  4. Write and test the mapping logic

    The developer implements the mapping in the Bot, reading each answer by linkId, validating types and required fields, and creating or updating resources through the FHIR API with references back to the QuestionnaireResponse. Unit tests cover complete submissions, missing required answers, malformed values and duplicate submissions. Check: the unit tests pass locally and in the development project, and each test case produces either the expected resources or a clear error that names the failing linkId.

  5. Add the Subscription on QuestionnaireResponse

    An administrator creates a Subscription in the development project that watches for new or updated QuestionnaireResponse resources matching the target Questionnaire, and points it at the Bot. The criteria are kept narrow so unrelated forms do not trigger the Bot, and the team confirms that the Subscription's per-project limit is not close to exhaustion. Check: submitting a QuestionnaireResponse through the normal form path triggers exactly one Bot execution, and a submission for a different Questionnaire triggers none.

  6. Promote the Bot to production

    The team moves the Bot code and the Subscription from the development project into the production project through its release process, and reviews the Bot's access so it can write only the resource types the mapping needs. Production secrets and endpoints are set separately from development values. Check: the production Bot shows the same version as the tested build, the access policy lists only the intended resource types, and a deployment record exists for the release.

  7. Verify with test submissions, including incomplete ones

    The QA lead submits a set of test QuestionnaireResponses to production or a production-equivalent environment: complete answers, answers missing required items, invalid values and a resubmission of an earlier form. For each one, the team checks the resources created, the references on them, and the AuditEvent record of the Bot execution. Check: complete submissions produce the expected resources, incomplete ones produce a documented error or Task without partial data, and every run has a traceable AuditEvent.

How to handle incomplete or invalid answers without losing the submission

The first decision is whether a Bot should reject an incomplete questionnaire or accept it and flag the gaps. Rejecting keeps bad data out of Patient and Observation resources, but the patient's answers then depend on a retry or a manual re-entry. Accepting and flagging keeps the submission moving: the Bot creates what it can, marks the missing or doubtful fields, and routes the rest to a person. Most intake flows need a mix, with hard rejects for fields that identify the patient (such as name or date of birth) and accept-and-flag for optional clinical answers. Write that rule down per question before building the Bot, because it determines what the Bot's error path must do.

Whichever path you choose, keep the submitted QuestionnaireResponse as the source record and never overwrite it with transformed data. Create a Task for human review when the Bot cannot complete a mapping, with the QuestionnaireResponse referenced in its focus, so a staff member can see the raw answers and act on them. Make writes idempotent: derive a stable identifier from the QuestionnaireResponse id or a business key, check for an existing Patient before creating one, and confirm this logic under a forced retry, since a Subscription-triggered Bot can run more than once for the same change. Confirm in your version how Subscription retries and Bot re-executions behave and what the Bot's error and retry settings are. AuditEvents and Bot logging record executions and failures, which lets you trace a failed submission back to its input, but confirm exactly what each one captures in your deployment before relying on it for an audit trail.

Security and operational considerations for form-driven Bots

A Bot that turns form answers into clinical records runs with identity, secrets and data access that a security review will ask about. The cards below cover the decisions that connect those controls, from the identity a Bot runs as to who holds responsibility for them in a self-hosted deployment.

Run-as identity and least privilege

Give each questionnaire Bot its own identity and a membership that allows only the resource types it writes, such as Patient, Observation or Task. Avoid running it under an administrator account, because a broad identity turns a form-parsing error into a broad data change. Ask your team to list every resource type and operation each Bot performs, then confirm that the Bot's access policy permits nothing else. Review the list whenever the questionnaire changes.

Medplum auth docs

Secrets for external calls

If the Bot calls an external service, such as a terminology lookup, a scheduling API or a messaging provider, store that credential as a project secret and never in Bot source code. Keep development and production projects separate so that test forms cannot reach live credentials. Confirm who can edit secrets, how keys are rotated, and whether changes are recorded. Treat any credential printed in an error message as exposed and rotate it.

PHI in logs and error output

Questionnaire answers are often protected health information, and a Bot that logs its input will copy that information into log storage. Log record IDs, the questionnaire version and the outcome instead of answer text. Check that error handlers do not echo the full QuestionnaireResponse, and confirm the retention period and access list for your log platform. Test this with a deliberately incomplete form before go-live.

Access policies on created resources

A Patient, Observation or Task created from a form becomes visible to whoever the access model allows, which may be wider than the person who submitted it. Decide which compartment or project each new resource belongs to, and whether patients and staff should see it through the portal or the clinical app. Verify this with a test patient account and a staff account before opening the form to real submissions.

Audit trails for Bot activity

A clinician or auditor may need to show which form produced which record and which Bot changed it. Confirm that Medplum records Bot executions and Subscription triggers, and that the audit records link the source QuestionnaireResponse to each created resource. Set a retention period that matches your record policy, and test the trail by tracing one submission end to end. Ask your team which audit questions they must answer and build the trail to answer them.

Shared responsibility in self-hosting

Medplum's compliance documentation states that compliance is a shared responsibility between Medplum and its customers. On a self-hosted deployment, your organization owns the infrastructure, the Bot runtime, the secrets store, the log platform and the backups, so those controls become part of your evidence. Ask Medplum which controls it provides and which you must document, and ask your auditor which of them they expect to test.

Medplum compliance docs

Questions teams ask before automating questionnaire responses

How much effort does automating questionnaire responses with Medplum Bots take?

Effort depends mostly on how many questionnaires you handle, how many answers map to FHIR resources, and how clean the form logic is. Each questionnaire needs a QuestionnaireResponse trigger, a Bot or $extract mapping, validation for incomplete answers, and tests against sample submissions. Mapping work is usually the largest share, because every question must land in the right resource and field. Ask any partner to split the estimate into design, build, testing and handover so you can see where the hours go.

Can an internal team build questionnaire automation on its own?

A team with working FHIR and TypeScript skills can build it, provided it has someone who understands the Medplum data model and the clinical meaning of each answer. The harder parts are usually not the code: they are agreeing on the mapping, deciding how partial submissions are handled, and proving the result to compliance reviewers. Many teams keep ownership of the Bot code and bring in outside help for the first mapping design or for test coverage. Decide this before you start, because it sets the staffing plan.

What do clinical and compliance stakeholders need to provide?

Clinical owners need to confirm what each question means, which answers are required, and which values must never be inferred. Compliance and privacy teams need to review which resources will be created, who can read them, and how the submission is retained. Operations staff should confirm what happens when an answer is missing, such as whether a Task is created for follow-up. Get these decisions written down as a mapping specification, since engineers cannot reliably infer them from the form.

How long does questionnaire automation take to deliver?

Duration depends on the number of forms, how many resource types each form writes to, and how many conditional questions exist. A single simple form with a few direct mappings is far shorter than a set of multi-page intake forms that create Patients, Observations and Tasks together. Testing and stakeholder sign-off often take longer than the build itself. No duration figure is supplied for this work, so ask for a timeline tied to a written scope with a named list of forms and mappings.

Should questionnaire mapping use $extract or a Bot?

Use $extract when the mapping is declarative and the output is a standard FHIR resource shape that your team can maintain as data. Use a Bot when you need conditional logic, lookups against existing records, duplicate checks or custom error handling. Many implementations use both, with $extract for simple resources and a Bot to orchestrate the rest. Confirm in the Medplum documentation which extraction features your version supports before committing to a design, because the choice affects testing and upgrade effort.

What does Medplum's supplied pricing include for self-hosting?

Medplum's pricing page lists a free Community self-hosting option and custom-priced Enterprise Self-Hosted, alongside hosted plans with fixed monthly prices. The pricing information supplied does not state what infrastructure, storage, email, support or engineering time is included in self-hosting, so those costs sit outside any listed figure. Your own cloud accounts, database and Redis hosting, backups, monitoring and upgrade work will recur. Ask Medplum for a written statement of what Enterprise Self-Hosted covers, and ask your partner to include all recurring infrastructure in the quote.

What goes wrong when questionnaire answers are incomplete?

The most common failure is a Bot that creates a Patient or Observation with empty or defaulted values, which then looks valid to downstream users. A well-built flow validates required answers before writing, returns a clear error or creates a Task for review, and records the failed submission for replay. Confirm during design how incomplete submissions are surfaced, who reviews them, and how long they are retained. Test these paths as carefully as the happy path.

How DeployOpen scopes and delivers questionnaire automation on Medplum

DeployOpen plans, implements, tests, documents and supports self-hosted open-source platforms inside the client's own infrastructure. For questionnaire automation on Medplum, we start from the forms your teams submit, the FHIR resources they must produce, and the controls your compliance and security teams need to review before anything goes live.

How we scope

  • Inventory every questionnaire, its QuestionnaireResponse flow and the resources each answer should produce
  • Decide between Subscriptions plus Bots and $extract for each form, with the reasoning written down
  • Agree in writing how incomplete, invalid and duplicate answers are handled, routed and reported

How we build

  • Build Bots that create Patients, Observations or Tasks, with input validation and idempotent writes
  • Store credentials as project secrets and set Bot access policies to least privilege for each integration
  • Test with unit tests and sample submissions, including malformed and partial responses, before release

How we hand over

  • Deliver the Bot source, mapping tables, test suite and deployment steps for your own CI/CD pipeline
  • Document execution, AuditEvent trails, failure alerts and the runbook for replaying failed submissions
  • Walk your engineers and compliance reviewers through the controls so they can verify them independently

How we support

  • Engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts
  • Ongoing support, upgrades and continuous testing are available as a retainer after handover
  • Confirm with DeployOpen which Medplum version your questionnaires will run on and plan each upgrade step

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.