Simple API Example
A complete example showing how to build a simple REST API with MoroJS. This example includes CRUD operations, validation, and proper error handling.
What You'll Build
This example demonstrates a user management API with the following features:
- Basic CRUD operations (Create, Read)
- Request validation with Zod schemas
- Query parameter filtering and search
- Error handling and HTTP status codes
- In-memory data storage (easily replaceable)
API Endpoints
GET /Welcome message
GET /healthHealth check
GET /usersList all users (with filtering)
POST /usersCreate a new user
GET /users/:idGet user by ID
Complete Implementation
src/server.ts
typescript
Testing the API
Here are some example requests you can make to test the API:
Create a new user
bash
Get all users
bash
Get a specific user
bash
Get users with filtering
bash
Key Features Demonstrated
Type Safety
- • Zod schemas for validation
- • Automatic type inference
- • Parameter type checking
- • Response type safety
Error Handling
- • Proper HTTP status codes
- • Consistent error format
- • Validation error messages
- • Not found handling
Validation
- • Request body validation
- • Parameter validation
- • Email format checking
- • Business rule validation
Best Practices
- • RESTful API design
- • Consistent response format
- • Proper HTTP methods
- • Clear endpoint naming