API Reference
Complete API reference for the Motia framework
Everything you need to know about Motia's APIs. This reference covers all the types, methods, and configurations available when building with Motia.
If you're new to Motia, start with the Steps guide to understand the basics.
Package exports
For a concise list of npm entrypoints and exports, see motia Package Exports.
Step Configuration
Every Step needs a config. The unified StepConfig type works for all step types -- the triggers array determines what activates the step.
StepConfig
Required fields:
name- Unique identifier for this Steptriggers- Array of triggers that activate this step (HTTP, queue, cron, state, stream)
Optional fields:
description- Human-readable descriptionenqueues- Topics this Step can enqueuevirtualEnqueues- Topics shown in the iii development console but not actually enqueued (gray connections)virtualSubscribes- Topics shown in the iii development console for flow visualizationflows- Flow names for iii development console groupingincludeFiles- Files to bundle with this Step (supports glob patterns, relative to Step file)
TriggerConfig
Triggers define how a step gets activated. A step can have multiple triggers.
HttpTrigger
Use this for HTTP endpoints.
QueueTrigger
Use this for background jobs and event-driven tasks.
CronTrigger
Use this for scheduled tasks.
Use crontab.guru to build cron expressions.
StateTrigger
Use this to trigger steps based on state changes.
StreamTrigger
Use this to trigger steps from stream events.
Trigger Helper Functions
Use these helpers for concise trigger definitions:
Enqueue Type
Config Examples
Queue Step Config Example
Queue config options:
type-'fifo'or'standard'(default:'standard')maxRetries- Max retry attempts (default: 3)visibilityTimeout- Seconds before message becomes visible again (default: 900)delaySeconds- Delay before message becomes visible, 0-900 (default: 0)concurrency- Max parallel message processing per topicbackoffType- Retry backoff strategy (e.g.,'exponential')backoffDelayMs- Base delay in ms for retry backoff
Cron Step Config Example
Multi-Trigger Step Config Example
A single step can respond to multiple trigger types:
Handlers
Handlers are the functions that execute your business logic. Use the Handlers type with your config for full type safety.
Handlers Type
The handler signature is unified -- the input type is inferred from the trigger that activated the step. Use ctx.match() or ctx.is to differentiate between trigger types in multi-trigger steps. Note that enqueue, logger, stateManager, and streams are now standalone imports from motia rather than context properties.
HTTP Step Handler
Receives a request, returns a response.
Queue Step Handler
Receives queue data, processes it. No return value.
Cron Step Handler
Runs on a schedule. Uses standalone imports for logging and state management.
Multi-Trigger Handler with match()
For steps with multiple triggers, use ctx.match() to handle each trigger type:
You can also use ctx.is for simpler checks:
Handler Context (FlowContext)
Every handler receives an optional context object (ctx in TypeScript/JavaScript, context in Python). The enqueue, logger, stateManager, and streams are now standalone imports from motia rather than context properties.
enqueue
Trigger other Steps by publishing messages to topics. Import directly from motia:
FIFO queues: When enqueuing to a topic that has a FIFO queue subscriber, you must include messageGroupId. Messages with the same messageGroupId are processed sequentially. Different groups are processed in parallel.
The data must match the input schema of Steps subscribing to that topic.
logger
Structured logging with automatic trace ID correlation. Import directly from motia:
All logs are automatically tagged with:
- Timestamp
- Step name
- Trace ID
- Any metadata you pass
Learn more about Observability
stateManager
Persistent key-value storage shared across Steps. Import directly from motia:
Methods:
stateManager.get(groupId, key)- Returns the value ornullstateManager.set(groupId, key, value)- Stores the value and returns{ new_value, old_value }stateManager.update(groupId, key, ops)- Applies atomic update operations and returns{ new_value, old_value }stateManager.delete(groupId, key)- Removes and returns the value (ornull)stateManager.list(groupId)- Returns array of all values in the groupstateManager.clear(groupId)- Removes all items in the group
Streams
Real-time data channels for pushing updates to connected clients. Stream instances are imported directly from their .stream.ts files:
Methods:
stream.set(groupId, id, data)- Create or update an item (returns{ new_value, old_value })stream.get(groupId, id)- Retrieve an item ornullstream.getGroup(groupId)- Get all items in a groupstream.delete(groupId, id)- Remove an itemstream.update(groupId, id, ops)- Apply atomic update operationsstream.send(channel, event)- Send an ephemeral event (e.g., typing indicators, reactions)
traceId
Unique ID for tracking requests across Steps.
The trace ID is automatically generated for each request and passed through all Steps in the workflow. Use it to correlate logs, state, and events.
trigger
Information about what triggered the current handler execution.
getData
Extract the data payload from the input. Useful in queue and stream handlers.
match
Route execution based on trigger type. See Multi-Trigger Handler with match() above.
Middleware
Intercepts API requests before and after the handler.
Parameters:
{ request, response }- TheMotiaHttpArgsobject containing request and responsectx- Context objectnext- Function to call the next middleware/handler
Returns: Response object
Handler Input
TypeScript and JavaScript handlers receive MotiaHttpArgs (containing request and response).
Python handlers use ApiRequest for standard responses and only use MotiaHttpArgs for streaming/SSE handlers.
request fields:
pathParams/path_params(Python) - Object with path parameters (e.g.,:idfrom/users/:id)queryParams/query_params(Python) - Object with query string params (values can be string or array)body- Parsed request body (validated againstbodySchemaif defined)headers- Object with request headers (values can be string or array)method- HTTP method stringrequestBody/request_body(Python) - Raw request body stream (for SSE / streaming)
response fields (for SSE / streaming):
status(code)- Set HTTP status codeheaders(headers)- Set response headersstream/writer.stream(Python) - Writable stream for sending dataclose()- Close the response stream
Response Object (ApiResponse)
HTTP handlers must return an object with these fields.
Fields:
status- HTTP status code (200, 201, 400, 404, 500, etc.)body- Response data (will be JSON-encoded automatically)headers- Optional custom headers
Server-Sent Events (SSE)
HTTP handlers can stream responses using Server-Sent Events. Instead of returning a response object, use the response object from MotiaHttpArgs to set headers and write to the stream.
Key differences from standard HTTP handlers:
- Destructure both
requestandresponsefrom the first argument - Use
response.status()andresponse.headers()to set the status and headers - Write SSE-formatted data to
response.stream(TS/JS) orresponse.writer.stream(Python) - Call
response.close()when done streaming - Do not return a response object — the response is streamed directly
Stream Configuration
Define real-time data streams for your app.
Fields:
name- Unique stream name (the stream instance is imported from the stream file)schema- Zod schema (TS/JS) or JSON Schema (Python) for data validationbaseConfig.storageType- Always'default'(custom storage coming soon)onJoin- Optional callback when a client subscribesonLeave- Optional callback when a client unsubscribes
File naming:
- TypeScript/JavaScript:
*.stream.tsor*.stream.js - Python:
*_stream.py
CLI Commands
For CLI usage, see the CLI Reference.
Common Patterns
Enqueue Types
You can enqueue topics as strings or objects with labels.
The label and conditional fields are for iii development console visualization only. They don't affect execution.
Query Parameters
Document query params for the iii development console.
This metadata is used by the iii development console.
Include Files
Bundle files with your Step (useful for templates, assets, binaries).
Files are copied into the deployment bundle and accessible at runtime.