Your First API
Let's build a complete API from scratch. This tutorial will guide you through creating a production-ready API with validation, error handling, and best practices.
Step 1: Create the Basic Server
Start by creating a simple server with a health check endpoint:
src/server.ts
typescript
Test it out!
Run npm run dev
and visithttp://localhost:3000/health
Step 2: Add Data Validation
Let's add a user management endpoint with proper validation:
src/server.ts
typescript
Step 3: Add Middleware
Add logging and error handling middleware:
src/server.ts - With Middleware
typescript
Step 4: Test Your API
Test your API endpoints with these example requests:
Create a User
POST /users
typescript
Get All Users
GET /users
typescript
What You've Learned
Core Concepts
- Creating a MoroJS application
- Defining routes with handlers
- Request and response handling
- Server startup and configuration
Advanced Features
- Schema-based validation with Zod
- Type-safe parameter handling
- Global middleware setup
- Error handling patterns