REST API Masterclass
Architecting Modern Backends01.Home02.What is REST?03.HTTP Deep Dive04.URI Best Practices05.JSON & Data Formats06.Environment Setup07.Your First Resource08.Advanced Controllers09.Database Strategy10.JWT Authentication11.Role-Based Auth (RBAC)12.API Versioning13.Filtering & Searching14.Pagination & Sorting15.Global Error Handling16.Rate Limiting17.CORS & Security18.Swagger & OpenAPI19.Testing with Supertest20.Webhooks & Caching21.Production Checklist
Database Strategy
How your database is structured determines how your API performs. In REST, we often model our database to match our Resources.
1. Serialization (Clean Output)
Your database schema isn't your API response. Never return your entire DB object.
// ❌ Bad: Returns passwordHash, privateEmail, __v
res.json(user);
// ✅ Good: Transform the object before sending
const output = {
id: user._id,
username: user.username,
member_since: user.createdAt
};
res.json({ data: output });2. Normalization vs Embedding
- SQL Approach: Normalize data and use JOINs. Great for data integrity.
- NoSQL Approach: Embed related data (e.g., embedding tags in a post). Great for read speed.
3. Indexing for API Queries
If your API allows filtering (e.g., /products?category=electronics), you must have a database index on the category field. Without it, your API will slow down exponentially as users grow.
4. The Data Access Layer (DAL)
Avoid calling database methods (like Model.find) directly in controllers. Create a data layer so you can mock the database during unit testing.
Security Warning: Always use an Allow-list for fields. Accidentally returning
password_hash or reset_tokenis one of the most common API security breaches.