A comprehensive, production-ready REST API demonstrating industry best practices for building scalable, maintainable server applications.
This is a learning repository designed to teach you how to build production-ready REST APIs. Every concept is implemented with extensive documentation, code comments, and explanations.
- β Input Validation - How to validate and sanitize all client input
- β Concurrency Control - How to prevent race conditions and overselling
- β Idempotency - How to handle duplicate requests safely
- β Caching - How to improve performance with intelligent caching
- β Structured Logging - How to debug production issues with tracing
- β Security - How to protect against common vulnerabilities
- β Error Handling - How to return consistent, helpful error messages
- β API Design - How to design clean, intuitive REST APIs
- β TypeScript - How to write type-safe Node.js applications
- β Testing - How to validate your code works correctly
- Node.js >= 20.0.0
- npm >= 10.0.0
- Git (for cloning)
# Clone the repository
git clone https://github.com/your-username/se-node-server-rest-apis.git
cd se-node-server-rest-apis
# Install dependencies
npm install
# Set up environment (optional - defaults work for development)
cp .env.example .env
# Run database migrations
npm run db:migrate
# Seed the database with sample data
npm run db:seed
# Start the development server
npm run devThe API will be available at http://localhost:3000
# Check health
curl http://localhost:3000/health
# List items
curl http://localhost:3000/api/v1/items
# Reserve an item
curl -X POST http://localhost:3000/api/v1/reserve \
-H "Content-Type: application/json" \
-H "Idempotency-Key: test-key-123" \
-d '{"userId":"user_test","itemId":"item_1","qty":1}'We've created comprehensive learning documentation in the docs/ directory:
- docs/01-introduction.md - Overview and architecture
- docs/02-validation.md - Input validation with Zod
- docs/03-concurrency.md - Atomic database operations
- docs/04-idempotency.md - Handling duplicate requests
- docs/05-caching.md - Performance with caching
- docs/06-logging.md - Observability and tracing
- docs/07-validation-guide.md - Complete testing guide
π‘ Start with docs/README.md for the full learning guide.
- POSTMAN_GUIDE.md - Complete Postman testing instructions
- LEARNING_CHECKLIST.md - Track your learning progress
Ready-to-use Postman collection for testing all features:
- postman-collection.json - Import this into Postman
- postman-environment.json - Environment variables
| Component | Technology | Why? |
|---|---|---|
| Runtime | Node.js 20+ | Latest LTS, ES2022 support |
| Framework | Express 4.x | Battle-tested, huge ecosystem |
| Language | TypeScript 5.x | Type safety, better DX |
| Database | SQLite (better-sqlite3) | Embedded, fast, zero-config |
| Validation | Zod | Runtime + compile-time validation |
| Logging | Pino | Ultra-fast structured logging |
| Security | Helmet, CORS | Security headers, cross-origin |
se-node-server-rest-apis/
βββ docs/ # Learning documentation
β βββ README.md # Documentation index
β βββ 01-introduction.md # Overview
β βββ 02-validation.md # Input validation
β βββ 03-concurrency.md # Race conditions
β βββ 04-idempotency.md # Duplicate requests
β βββ 05-caching.md # Performance
β βββ 06-logging.md # Observability
β βββ 07-validation-guide.md # Complete testing guide
β
βββ src/ # Source code
β βββ cache/ # Caching layer
β β βββ index.ts # TTL cache with invalidation
β β βββ README.md # Module learning guide
β βββ config/ # Configuration
β β βββ index.ts # Environment variables
β β βββ README.md # Module learning guide
β βββ database/ # Database layer
β β βββ index.ts # SQLite connection
β β βββ migrate.ts # Migration runner
β β βββ seed.ts # Data seeding
β β βββ README.md # Module learning guide
β βββ http/ # Response utilities
β β βββ index.ts # ok(), fail() helpers
β β βββ README.md # Module learning guide
β βββ idempotency/ # Idempotency handling
β β βββ index.ts # Duplicate request prevention
β β βββ README.md # Module learning guide
β βββ middleware/ # Express middleware
β β βββ rateLimit.ts # Token bucket rate limiting
β β βββ security.ts # Security headers, CORS
β β βββ README.md # Module learning guide
β βββ observability/ # Logging & metrics
β β βββ index.ts # Pino structured logging
β β βββ README.md # Module learning guide
β βββ routes/ # API endpoints
β β βββ index.ts # Main routes
β β βββ health.ts # Health checks
β β βββ README.md # Module learning guide
β βββ services/ # Business logic
β β βββ reservations.ts # Domain logic
β β βββ README.md # Module learning guide
β βββ types/ # TypeScript types
β β βββ index.ts # All type definitions
β β βββ README.md # Module learning guide
β βββ validation/ # Zod schemas
β β βββ schemas.ts # Request/response schemas
β β βββ README.md # Module learning guide
β βββ server.ts # Application entry point
β
βββ postman-collection.json # Postman collection (import this!)
βββ postman-environment.json # Postman environment (import this!)
βββ POSTMAN_GUIDE.md # Complete Postman instructions
βββ LEARNING_CHECKLIST.md # Track your progress
βββ POSTMAN_COLLECTION.md # API testing with curl
β
βββ .env.example # Environment template
βββ package.json # Dependencies
βββ tsconfig.json # TypeScript config
βββ README.md # This file
Problem: Clients send invalid or malicious data.
Solution: Validate all input at the API boundary using Zod schemas.
// src/validation/schemas.ts
export const reserveRequestSchema = z.object({
userId: z.string().min(1),
itemId: z.string().regex(/^item_\d+$/),
qty: z.number().int().min(1).max(5)
});Learn more: docs/02-validation.md
Problem: Two users reserve the last item simultaneously, both succeed (overselling).
Solution: Atomic database operations with conditional updates.
UPDATE items
SET availableQty = availableQty - ?
WHERE id = ? AND availableQty >= ?Learn more: docs/03-concurrency.md
Problem: Network retries create duplicate reservations.
Solution: Store responses by unique key, replay on duplicates.
// First request: Process and store
// Second request: Return cached responseLearn more: docs/04-idempotency.md
Problem: Repeated database queries waste resources.
Solution: Cache responses with TTL, invalidate on changes.
const cached = getCache('items');
if (cached) return cached;
const items = fetchItems();
setCache('items', items, 30_000);Learn more: docs/05-caching.md
Problem: Debugging production issues is hard without context.
Solution: Structured logs with request tracing.
{
"level": "info",
"requestId": "abc-123",
"msg": "Item reserved",
"userId": "user_1",
"itemId": "item_1"
}Learn more: docs/06-logging.md
http://localhost:3000/api/v1
| Method | Endpoint | Description |
|---|---|---|
| GET | /items |
List all items |
| GET | /items/:id |
Get single item |
| POST | /reserve |
Reserve an item |
| POST | /confirm |
Confirm reservation |
| POST | /cancel |
Cancel reservation |
| GET | /reservations/user/:userId |
List user's reservations |
| GET | /health |
Health check |
All responses follow a consistent format:
Success:
{
"ok": true,
"data": { ... }
}Error:
{
"ok": false,
"error": {
"code": "ERROR_CODE",
"message": "Description",
"details": { ... },
"requestId": "uuid"
}
}Complete testing setup ready to use:
- Import
postman-collection.jsoninto Postman - Import
postman-environment.jsoninto Postman - Select "Reservation API - Local" environment
- Start testing!
π Full instructions: POSTMAN_GUIDE.md
# Health check
curl http://localhost:3000/health
# List items
curl http://localhost:3000/api/v1/items
# Reserve an item
curl -X POST http://localhost:3000/api/v1/reserve \
-H "Content-Type: application/json" \
-H "Idempotency-Key: test-key-123" \
-d '{"userId":"user_test","itemId":"item_1","qty":1}'
# Confirm reservation
curl -X POST http://localhost:3000/api/v1/confirm \
-H "Content-Type: application/json" \
-d '{"userId":"user_test","reservationId":"res_abc123"}'π More examples: POSTMAN_COLLECTION.md
Track your learning progress and validate each feature:
π Checklist: LEARNING_CHECKLIST.md
npm run dev # Start development server with hot reload
npm run build # Compile TypeScript
npm run start # Start production server
npm run lint # Lint code
npm run format # Format code
npm run db:migrate # Run database migrations
npm run db:seed # Seed database
npm run clean # Clean build output# .env file (copy from .env.example)
NODE_ENV=development
PORT=3000
LOG_LEVEL=debug
DB_PATH=./app.db- Input Validation with Zod schemas
- Atomic Operations to prevent race conditions
- Idempotency for safe request retries
- Response Caching with automatic invalidation
- Rate Limiting (token bucket algorithm)
- Structured Logging with request tracing
- Security Headers (Helmet.js)
- CORS Configuration
- Health Check Endpoints
- Graceful Shutdown
- TypeScript (100% typed)
- Database Migrations
- Consistent Error Responses
We've built a reservation system for an inventory store because it demonstrates:
- Time-sensitive operations - Reservations expire after 10 minutes
- State transitions - reserved β confirmed β cancelled/expired
- Concurrency - Multiple users competing for limited inventory
- Idempotency needs - Network retries can cause double-charging
Request β Security Middleware β Rate Limiting β Validation β Route Handler
β
Business Logic
β
Database (SQLite)
β
(Cache/Idempotency)
β
Response
docs/README.md- Complete learning guide- Each source file has extensive comments
- Type definitions in
src/types/index.tsfor reference
This is a learning repository. Feel free to:
- Explore the code
- Make changes and break things
- Fix issues and learn from them
- Add new features
MIT License - See LICENSE file for details
Ready to dive in? Continue to the learning documentation:
β Start Learning with docs/01-introduction.md
Or jump straight to a topic:
π‘ Tip: Every file in this repository is heavily documented. Start exploring and happy learning!