API Reference
Complete API reference for 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 Configurations
Every Step needs a config. Here's what you can put in it.
ApiRouteConfig
Use this for HTTP endpoints.
Required fields:
type- Always'api'name- Unique identifier for this Steppath- URL path (supports params like/users/:id)method- HTTP method (GET,POST,PUT,DELETE,PATCH,OPTIONS,HEAD)emits- Topics this Step can emit (list all, even if empty[])
Optional fields:
description- Human-readable descriptionflows- Flow names for Workbench groupingbodySchema- Zod schema (TS/JS) or JSON Schema (Python). Can be ZodObject or ZodArray. Note: Schema is not validated automatically. Use middleware or validate manually in your handler with.parse()or.safeParse().responseSchema- Map of status codes to response schemas (used for type generation and OpenAPI)middleware- Functions to run before the handler (executed in array order)queryParams- Query parameter docs for WorkbenchvirtualEmits- Topics shown in Workbench but not actually emitted (gray connections)virtualSubscribes- Topics shown in Workbench for flow visualization (useful for chaining HTTP requests)includeFiles- Files to bundle with this Step (supports glob patterns, relative to Step file)
EventConfig
Use this for background jobs and event-driven tasks.
Required fields:
type- Always'event'name- Unique identifiersubscribes- Topic names to listen toinput- Zod schema (TS/JS) or JSON Schema (Python) for event data. Note: Validation is not automatic. In Python, manually validate with Pydantic if needed.emits- Topics this Step can emit
Optional fields:
description- Human-readable descriptionflows- Flow names for WorkbenchvirtualEmits/virtualSubscribes- For Workbench visualization onlyincludeFiles- Files to bundle with this Step (supports glob patterns)infrastructure- Resource limits and queue config (Event Steps only, Motia Cloud)
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)
CronConfig
Use this for scheduled tasks.
Required fields:
type- Always'cron'name- Unique identifiercron- Cron expression (e.g.,'0 9 * * *'for 9 AM daily)emits- Topics this Step can emit
Optional fields:
description,flows,virtualEmits,virtualSubscribes,includeFiles- Same as above
👉 Use crontab.guru to build cron expressions.
NoopConfig
Use this for visual-only nodes in Workbench (no code execution).
Required fields:
type- Always'noop'name- Unique identifiervirtualEmits- Topics shown in WorkbenchvirtualSubscribes- Topics shown in Workbench
No handler needed - NOOP Steps don't execute code.
Handler Context
Every handler gets a context object (ctx in TypeScript/JavaScript, context in Python) with these tools.
emit
Trigger other Steps by publishing events.
FIFO queues: When emitting 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 and returns the valuedelete(groupId, key)- Removes and returns the value (ornull)getGroup(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 the full item with metadata)get(groupId, id)- Retrieve an item ornullgetGroup(groupId)- Get all items in a groupdelete(groupId, id)- Remove an itemsend(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.
Handlers
Handlers are the functions that execute your business logic. The signature depends on the Step type.
API Step Handler
Receives a request, returns a response.
Parameters:
req- Request object (see below)ctx- Context object withemit,logger,state,streams,traceId
Returns: { status, body, headers? }
Event Step Handler
Receives event data, processes it. No return value.
Parameters:
input- Event data (matches theinputschema in config)ctx- Context object withemit,logger,state,streams,traceId
Returns: Nothing (void/None)
Cron Step Handler
Runs on a schedule. Only receives context.
Parameters:
ctx- Context object withemit,logger,state,streams,traceId
Returns: Nothing (void/None)
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
👉 Learn more about Middleware →
Request Object
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
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)
File naming:
- TypeScript/JavaScript:
*.stream.tsor*.stream.js - Python:
*_stream.py
CLI Commands
Motia's command-line tools for development and deployment.
motia version
Show Motia CLI version.
motia create
Create a new Motia project.
Options:
[name]- Project name (or.for current directory)-t, --template <name>- Template to use (nodejsorpython)-c, --cursor- Add Cursor IDE rules
motia rules pull
Install AI development guides (AGENTS.md, CLAUDE.md) and Cursor IDE rules.
Options:
-f, --force- Overwrite existing files
motia dev
Start development server with Workbench and hot reload.
Options:
-p, --port <number>- Port number (default: 3000)-H, --host <address>- Host address (default: localhost)-d, --debug- Enable debug logging-m, --mermaid- Generate Mermaid diagrams--motia-dir <path>- Custom path for.motiafolder
motia start
Start production server (no Workbench, no hot reload).
Options:
-p, --port <number>- Port number (default: 3000)-H, --host <address>- Host address (default: localhost)-d, --debug- Enable debug logging--motia-dir <path>- Custom path for.motiafolder
motia build
Build your project for deployment.
Compiles all Steps and generates deployment artifacts.
motia generate-types
Generate TypeScript types from your Step configs.
Creates types.d.ts with type-safe Handlers interface. Run this after changing Step configs.
motia generate step
Create a new Step interactively.
Options:
-d, --dir <path>- Path relative tosteps/directory
motia generate openapi
Generate OpenAPI specification.
Options:
-t, --title <title>- API title (default: package.json name)-v, --version <version>- API version (default: 1.0.0)-o, --output <file>- Output file (default: openapi.json)
motia install
Set up Python virtual environment and install dependencies.
motia emit
Manually emit an event (for testing).
Options:
--topic <topic>- Event topic name--message <json>- Event data as JSON string-p, --port <number>- Server port (default: 3000)
motia docker setup
Generate Dockerfile and .dockerignore.
motia docker build
Build Docker image.
motia docker run
Build and run Docker container.
Options:
-p, --port <number>- Host port to map (default: 3000)-n, --project-name <name>- Docker image name-s, --skip-build- Skip building the image
motia cloud deploy
Deploy to Motia Cloud.
Options:
-k, --api-key <key>- Motia Cloud API key (or setMOTIA_API_KEYenv var)-v, --version-name <version>- Version name/tag for this deployment-n, --project-name <name>- Project name (for new projects)-s, --environment-id <id>- Environment ID--environment-name <name>- Environment name-e, --env-file <path>- Path to environment variables file-d, --version-description <desc>- Version description-c, --ci- CI mode (non-interactive)
Common Patterns
Emit Types
You can emit topics as strings or objects with labels.
The label and conditional fields are for Workbench visualization only. They don't affect execution.
Query Parameters
Document query params for Workbench.
This shows up in the Workbench endpoint tester.
Include Files
Bundle files with your Step (useful for templates, assets, binaries).
Files are copied into the deployment bundle and accessible at runtime.
Adapter Interfaces
Adapter interfaces define contracts for pluggable infrastructure components. Implement these interfaces to create custom adapters for state, streams, events, and cron.
Adapter creation is only supported in TypeScript/JavaScript. Python steps can use adapters configured in motia.config.ts, but cannot create custom adapters.
StateAdapter
Interface for state storage adapters.
StreamAdapter
Abstract class for stream adapters.
EventAdapter
Interface for event handling adapters.
CronAdapter
Interface for cron job locking adapters.
Supporting Types
Learn more about creating adapters →
What's Next?
Steps
Learn how to build with Steps
State Management
Deep dive into the State API
Streams
Real-time streaming guide
Middleware
Request/response middleware patterns
Examples
See these APIs in action