Bot $execute
The $execute operation runs an OpenOrchid Bot on-demand, allowing you to trigger server-side automation logic via API calls. Bots can process
incoming data, integrate with external systems, and return custom responses-making this operation the primary way to leverage OpenOrchid's
automation capabilities.
Whether you're processing HL7v2 messages from legacy systems, responding to webhooks, or building custom API endpoints, $execute provides
the flexibility to handle virtually any healthcare integration scenario.
Use Cases
- Webhook Handling: Receive and process incoming webhooks from external services (labs, pharmacies, payers)
- HL7v2 Integration: Parse and transform HL7v2 messages from legacy healthcare systems
- Custom API Endpoints: Build application-specific endpoints that return custom JSON responses
- On-Demand Processing: Trigger data transformations, validations, or calculations programmatically
- External System Integration: Connect to third-party APIs and synchronize data with your FHIR resources
If you're not familiar with OpenOrchid Bots, you may want to review Bot Basics documentation first.
Invoke a bot by ID
Invoke a bot by ID when you know the Bot's ID in advance.
Finding your Bot Id
You can find the id of your Bot by clicking on the Details tab of the Bot resource. In this example, it is 43ac3060-ff20-49e8-9682-bf91ab3a5191

Using POST
POST [base]/Bot/[id]/$execute
Examples
The MedplumClient TypeScript class provides a executeBot convenience method
const result = await medplum.executeBot(id, { input: { foo: 'bar' } }, ContentType.JSON);
console.log(result);medplum login
medplum post 'Bot/[id]/$execute' '{ "foo": "bar" }'
curl 'https://api.medplum.com/fhir/R4/Bot/[id]/$execute' \
-X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $MY_ACCESS_TOKEN" \
-d '{"foo":"bar"}'
Using GET
Query parameters will be passed to the bot as type Record<string, string> (see Content Types below)
GET [base]/Bot/[id]/$execute?params
const getResult = await medplum.get(medplum.fhirUrl('Bot', id, '$execute').toString() + '?foo=bar');
console.log(getResult);medplum login
medplum get 'Bot/[id]/$execute?foo=bar'
curl 'https://api.medplum.com/fhir/R4/Bot/[id]/$execute?foo=bar' \
-H "Authorization: Bearer $MY_ACCESS_TOKEN"
Invoke a bot by identifier
Sometimes you may not know the OpenOrchid Bot ID in advance. In that case, you can invoke a Bot by Identifier.
This is also useful when the same conceptual bot exists in multiple OpenOrchid projects. Each bot will have a different ID, but they can all have the same identifier.
Using POST
POST [base]/Bot/$execute?identifier=[system]|[code]
Examples
The MedplumClient executeBot convenience method supports both id: string and identifier: Identifier:
const result = await medplum.executeBot(
{
system: 'https://example.com/bots',
value: '1234',
},
{
foo: 'bar',
}
);
console.log(result);medplum login
medplum post 'Bot/[id]/$execute?identifier=https://example.com/bots|1234' '{ "foo": "bar" }'
curl 'https://api.medplum.com/fhir/R4/Bot/$execute?identifier=https://example.com/bots|1234' \
-X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $MY_ACCESS_TOKEN" \
-d '{"foo":"bar"}'
Using GET
Query parameters will be passed to the bot as type Record<string, string> (see Content Types below)
GET [base]/Bot/$execute?identifier=[system]|[code]¶ms
const getResult = await medplum.get(
medplum.fhirUrl('Bot', '$execute').toString() + '?identifier=https://example.com/bots|1234&foo=bar'
);
console.log(getResult);medplum login
medplum get 'Bot/$execute?identifier=https://example.com/bots|1234'
curl 'https://api.medplum.com/fhir/R4/Bot/$execute?identifier=https://example.com/bots|1234' \
-H "Authorization: Bearer $MY_ACCESS_TOKEN"
Content Types
OpenOrchid Bots support a variety of input content types. Specify the input content type using the standard Content-Type HTTP header, or as an optional parameter to MedplumClient.executeBot().
| Content-Type | typeof event.input | Description |
|---|---|---|
text/plain | string | <INPUT_DATA> is parsed as plaintext string |
application/json | Record<string, any> | <INPUT_DATA> is parsed as JSON-encoded object |
application/x-www-form-urlencoded | Record<string, string> | <INPUT_DATA> is parsed as URL-encoded string, resulting in a key/value map |
application/fhir+json | Resource | <INPUT_DATA> is parsed as a FHIR Resource encoded as JSON |
x-application/hl7-v2+er7 | HL7Message | <INPUT_DATA> is a string that should be parsed as a pipe-delimited HL7v2 message. HL7v2 is a common text-based message protocol used in legacy healthcare systems |
The input data that will be parsed according to CONTENT_TYPE and passed into your Bot as event.input.
Asynchronous Execution
For authenticated Bot $execute requests, specify Prefer: respond-async to receive HTTP 202 Accepted with a job status URL while the Bot runs in the background. Use this for non-streaming execution; it does not extend the Bot runtime's limits. Custom FHIR operations and public /webhook/ routes do not implement this response mechanism.
The server records an AsyncJob, but this execution path does not persist the request body as a resumable queue or automatically retry Bot failures. An interruption can leave a job unfinished. Retain the inputs and operation identity separately when recovery needs them, and reconcile an uncertain outcome before resubmitting. See Recover an item safely.
Making an Async Request
Add the Prefer: respond-async header to the $execute request:
import { ContentType, isOk, isOperationOutcome, MedplumClient, OperationOutcomeError } from '@medplum/core';
import type { AsyncJob, Parameters } from '@medplum/fhirtypes';
const response = await medplum.executeBot('your-bot-id', { foo: 'bar' }, ContentType.JSON, {
headers: {
Prefer: 'respond-async',
},
});medplum post 'Bot/[id]/$execute' '{ "foo": "bar" }' --prefer-async
curl 'https://api.medplum.com/fhir/R4/Bot/[id]/$execute' \
-X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $MY_ACCESS_TOKEN" \
-H "Prefer: respond-async" \
-d '{"foo":"bar"}'
Checking Job Status
When using async execution, the server returns a 202 Accepted response with a Content-Location header containing the URL to check the job status:
HTTP/1.1 202 Accepted
Content-Location: https://api.medplum.com/fhir/R4/job/[job-id]/status
You can poll this URL to check the status of your bot execution. In general, for long running jobs it's best to poll no more frequently than 1 second.
The SDK can poll automatically. Its resolved value is the terminal AsyncJob, not the Bot's unwrapped result. Inspect both the job status and output:
const job: AsyncJob = await medplum.executeBot('your-bot-id', { foo: 'bar' }, ContentType.JSON, {
headers: {
Prefer: 'respond-async',
},
pollStatusOnAccepted: true, // Returns the terminal AsyncJob, not the Bot result
pollStatusPeriod: 2000, // Poll every 2 seconds
});
const output = getCompletedBotOutput(job); // Defined below
// Apply your Bot's result contract to output before declaring business success.
Use this helper with either polling approach. It rejects terminal job failures and error OperationOutcome output, including errors inside a completed job. Interpret custom Bot response data according to your application's result contract as well.
export function getCompletedBotOutput(job: AsyncJob): Parameters {
// A completed wrapper can still contain a Bot error OperationOutcome.
for (const parameter of job.output?.parameter ?? []) {
if (isOperationOutcome(parameter.resource) && !isOk(parameter.resource)) {
throw new OperationOutcomeError(parameter.resource);
}
}
if (job.status !== 'completed') {
throw new Error(`Bot job is ${job.status}; inspect its output before retrying`);
}
if (!job.output) {
throw new Error('Bot job has no output; reconcile its result before retrying');
}
// Preserve the Parameters, including false/zero values. The caller must also
// interpret any custom success/failure representation returned by its Bot.
return job.output;
}Alternatively, capture the status URL and poll with a limit. Use the same authenticated identity, or another identity authorized to read the job. A polling timeout stops waiting; it does not cancel execution or authorize resubmitting the action.
// Example: Get the status URL from the Content-Location header
const accessToken = 'your-access-token';
const response = await fetch('https://api.medplum.com/fhir/R4/Bot/bot-id/$execute', {
method: 'POST',
headers: {
Prefer: 'respond-async',
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ foo: 'bar' }),
});
if (response.status !== 202) {
throw new Error(`Expected asynchronous acceptance; received HTTP ${response.status}`);
}
const statusUrl = response.headers.get('Content-Location');
if (!statusUrl) {
throw new Error('No Content-Location header found');
}
// Retain statusUrl so a caller can resume polling after a disconnect or timeout.
const pollingClient = new MedplumClient({ baseUrl: 'https://api.medplum.com/', accessToken });
const output = await waitForBotJob(pollingClient, statusUrl);export async function waitForBotJob(
client: MedplumClient,
statusUrl: string,
maxAttempts = 30,
pollInterval = 2000
): Promise<Parameters> {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const job = await client.get<AsyncJob>(statusUrl, { cache: 'no-cache', pollStatusOnAccepted: false });
if (job.status === 'completed' || job.status === 'error' || job.status === 'cancelled') {
return getCompletedBotOutput(job);
}
if (attempt + 1 < maxAttempts) {
await new Promise((resolve) => {
setTimeout(resolve, pollInterval);
});
}
}
throw new Error(`Polling limit reached; retain ${statusUrl} and reconcile before resubmitting`);
}# Check job status
medplum get 'job/[job-id]/status'
# Check job status
curl 'https://api.medplum.com/fhir/R4/job/[job-id]/status' \
-H "Authorization: Bearer $MY_ACCESS_TOKEN"
AsyncJob Resource Structure
The status endpoint returns an AsyncJob resource. HTTP 202 means it is nonterminal; HTTP 200 means it has reached a terminal status, which can include failure or cancellation.
status: Current job statusaccepted- Job was accepted. Bot$executecan retain this status while processing; it is not proof that work is still waiting to start.active- An in-progress status used by some asynchronous operations; do not require this transition when polling Bot execution.completed- The asynchronous wrapper finished. Inspect the output before treating the Bot's business operation as successful.error- The asynchronous operation reported a failure. Inspect its output.cancelled- Cancellation was recorded. Do not rely on this to interrupt an already running Bot or undo its effects.
output: AParametersresource containing the result or failure details. Look up parameters by name rather than position.responseBodycontains ordinary Bot return data. Objects are JSON-encoded invalueString; booleans usevalueBoolean.outcomecontains anOperationOutcome, which can indicate success or failure. A Bot error can appear here even when the job status iscompleted.- Errors from the asynchronous wrapper can also produce
errorandstackparameters. Avoid exposing internal diagnostics to end users.
requester: The user or client application that started the execution
Example Response
When the bot execution completes successfully:
{
resourceType: 'AsyncJob',
id: 'job-id',
status: 'completed',
request: 'https://api.medplum.com/fhir/R4/Bot/:bot-id/$execute',
requestTime: '2023-01-01T00:00:00.000Z',
transactionTime: '2023-01-01T00:00:05.000Z',
output: {
resourceType: 'Parameters',
parameter: [
{
name: 'responseBody',
valueString: 'Bot execution result',
},
],
},
};An example of an asynchronous operation failure follows. A Bot execution failure can instead have status: completed with an error outcome, so do not use status alone to detect it.
{
resourceType: 'AsyncJob',
id: 'job-id',
status: 'error',
request: 'https://api.medplum.com/fhir/R4/Bot/:bot-id/$execute',
requestTime: '2023-01-01T00:00:00.000Z',
transactionTime: '2023-01-01T00:00:05.000Z',
output: {
resourceType: 'Parameters',
parameter: [
{
name: 'outcome',
resource: {
resourceType: 'OperationOutcome',
issue: [
{
severity: 'error',
code: 'processing',
details: {
text: 'Bot execution failed',
},
},
],
},
},
],
},
};Related
- Bot $deploy - Deploy bot code before execution
- Bot Basics - Introduction to OpenOrchid Bots
- Bots In Production - Best practices for production bot deployments
- HL7 Interfacing - Processing HL7v2 messages with bots
- Consuming Webhooks - Handle incoming webhooks with bots