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.
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 (API, 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.
ApiTrigger
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
Infrastructure config (Motia Cloud only):
handler.ram- Memory in MB (128-10240, required)handler.cpu- CPU vCPUs (optional, auto-calculated from RAM if not provided, must be proportional)handler.timeout- Timeout in seconds (1-900, required)queue.type-'fifo'or'standard'(required)queue.maxRetries- Max retry attempts (0+, required)queue.visibilityTimeout- Timeout in seconds (required, must be > handler.timeout to prevent premature redelivery)queue.delaySeconds- Optional delay before message becomes visible (0-900)
Cron Step Config Example
Multi-Trigger Step Config Example
A single step can respond to multiple trigger types:
NoopConfig
Use this for visual-only nodes in the iii development console (no code execution).
No handler needed - Noop Steps don't execute code. They exist for iii development console visualization only.
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.
API 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. Only receives context.
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 gets a context object (ctx in TypeScript/JavaScript, context in Python) with these tools.
enqueue
Trigger other Steps by publishing messages to topics.
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.
All logs are automatically tagged with:
- Timestamp
- Step name
- Trace ID
- Any metadata you pass
Learn more about Observability
state
Persistent key-value storage shared across Steps.
Methods:
get(groupId, key)- Returns the value ornullset(groupId, key, value)- Stores the value and returns{ new_value, old_value }update(groupId, key, ops)- Applies atomic update operations and returns{ new_value, old_value }delete(groupId, key)- Removes and returns the value (ornull)list(groupId)- Returns array of all values in the groupclear(groupId)- Removes all items in the group
streams
Real-time data channels for pushing updates to connected clients.
Methods:
set(groupId, id, data)- Create or update an item (returns{ new_value, old_value })get(groupId, id)- Retrieve an item ornullgetGroup(groupId)- Get all items in a groupdelete(groupId, id)- Remove an itemupdate(groupId, id, ops)- Apply atomic update operationssend(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:
req- Request objectctx- Context objectnext- Function to call the next middleware/handler
Returns: Response object
Request Object (ApiRequest)
API handlers receive a request object with these fields.
Fields:
pathParams- Object with path parameters (e.g.,:idfrom/users/:id)queryParams- 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)
Response Object (ApiResponse)
API 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
Stream Configuration
Define real-time data streams for your app.
Fields:
name- Unique stream name (used inctx.streams.<name>)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.