v2/examples/05-swarm-apps/rest-api/README.md
A complete REST API built with Node.js and Express, demonstrating best practices for API development.
rest-api/
├── src/
│ ├── controllers/ # Request handlers
│ ├── models/ # Data models (in-memory for demo)
│ ├── routes/ # API route definitions
│ ├── middleware/ # Custom middleware
│ └── server.js # Express server setup
├── tests/ # Test suites
├── package.json # Dependencies and scripts
├── .env.example # Environment variables template
└── README.md # This file
# Install dependencies
npm install
# Copy environment variables
cp .env.example .env
# Development mode with auto-reload
npm run dev
# Production mode
npm start
The API will be available at http://localhost:3000
GET /health - Server health statusGET /api/v1 - API information and available endpointsGET /api/v1/users - List all users (with pagination)GET /api/v1/users/:id - Get user by IDPOST /api/v1/users - Create new userPUT /api/v1/users/:id - Update userDELETE /api/v1/users/:id - Delete userGET /api/v1/products - List all products (with pagination and filtering)GET /api/v1/products/:id - Get product by IDPOST /api/v1/products - Create new productPUT /api/v1/products/:id - Update productDELETE /api/v1/products/:id - Delete productcurl -X POST http://localhost:3000/api/v1/users \
-H "Content-Type: application/json" \
-d '{
"name": "John Doe",
"email": "[email protected]",
"age": 30
}'
# Filter by category
curl http://localhost:3000/api/v1/products?category=Electronics
# Filter by price range
curl http://localhost:3000/api/v1/products?minPrice=50&maxPrice=200
# With pagination
curl http://localhost:3000/api/v1/products?page=2&limit=5
curl -X PUT http://localhost:3000/api/v1/products/1 \
-H "Content-Type: application/json" \
-d '{
"name": "Updated Product",
"price": 149.99,
"category": "Electronics",
"stock": 25
}'
# Run all tests
npm test
# Run tests with coverage
npm test -- --coverage
# Run tests in watch mode
npm run test:watch
All API responses follow a consistent format:
{
"success": true,
"data": { ... },
"message": "Operation successful"
}
{
"success": false,
"error": {
"message": "Error description",
"status": 400,
"timestamp": "2024-01-13T12:00:00.000Z"
}
}
{
"success": true,
"data": [ ... ],
"pagination": {
"page": 1,
"limit": 10,
"total": 50
}
}
The API validates all input data:
Validation errors return a 400 status with details:
{
"errors": [
{
"type": "field",
"msg": "Valid email is required",
"path": "email",
"location": "body"
}
]
}
| Variable | Description | Default |
|---|---|---|
| PORT | Server port | 3000 |
| NODE_ENV | Environment (development/production) | development |
| API_PREFIX | API route prefix | /api/v1 |
| API_RATE_LIMIT | Rate limit per hour | 100 |
# Linting
npm run lint
# Format code
npm run format
This example uses in-memory storage for simplicity. For production:
MIT