Overview
This tutorial guides you through building a full-featured Todo API with create, read, update, and delete operations. You’ll learn how to use Motia’s streams for real-time updates and state management for data persistence. What you’ll learn:- Creating CRUD HTTP endpoints
- Input validation with Zod schemas
- Working with streams for real-time data
- Managing state across operations
- Path parameters and request bodies
- Update operations with atomic updates
Prerequisites
Before starting, make sure you have:
- Node.js version 19 or higher
- Completed the Hello World tutorial
- Basic understanding of REST APIs
Project Setup
Building the API
Step 1: Define the Todo Stream
Streams provide real-time, reactive data storage. Createsteps/todo/todo.stream.ts:
steps/todo/todo.stream.ts
- Schema: Defines the structure of stream data
- onJoin/onLeave: Hooks for subscription lifecycle events
- Type export: Makes the Todo type available to other files
Step 2: Create Todo Endpoint
Createsteps/todo/create-todo.step.ts:
steps/todo/create-todo.step.ts
- http() helper: Shorthand for defining HTTP triggers
- Body validation: Automatically validates request bodies
- Streams vs State: Streams for real-time data, state for persistence
- Virtual enqueues: Declares events without actual queue topics
Step 3: Update Todo Endpoint
Createsteps/todo/update-todo.step.ts:
steps/todo/update-todo.step.ts
- Path parameters: Extract values from URL paths
- Update operations: Atomic updates with UpdateOp array
- Conditional updates: Only apply provided fields
- Error handling: Return appropriate status codes
Step 4: Delete Todo Endpoint
Createsteps/todo/delete-todo.step.ts:
steps/todo/delete-todo.step.ts
Step 5: List Todos Endpoint
Createsteps/todo/list-todos.step.ts:
steps/todo/list-todos.step.ts
Running the Application
Testing
Create a simple test scripttest-api.sh:
test-api.sh
Next Steps
Message Queue
Add background processing to your API
Scheduled Tasks
Learn to run periodic cleanup jobs
Streams Guide
Deep dive into real-time streams
State Management
Learn more about state operations