REST API Design
REST mein URL RESOURCES (nouns) batata hai aur HTTP METHOD ACTION (verb) batata hai. "/getUsers" REST nahi hai — sahi tarika hai "GET /users". Collections plural rakho: /users, /users/:id, /users/:id/orders.
Consistency sabse important hai: same casing, same error format, same pagination params poore API mein. Versioning ("/api/v1") se breaking changes ke waqt purane clients chalte rehte hain.
GET /api/v1/users // list
POST /api/v1/users // create
GET /api/v1/users/:id // read one
PUT /api/v1/users/:id // full update
PATCH /api/v1/users/:id // partial update
DELETE /api/v1/users/:id // delete- URL mein noun, action HTTP method se — GET /users, na ki /getUsers
- Collections plural, nested resources se relationship dikhao
- Versioning (/api/v1) se purane clients breaking changes se bache rehte hain
Collections plural rakho (/users), single item id se (/users/42), aur relationships nesting se (/users/42/orders). URL mein action verb mat daalo — action HTTP method batata hai. Deep nesting (3 level se zyada) se bacho, uske bajaye query params use karo.
GET /users/42/orders // achha
GET /orders?userId=42 // ye bhi theek, filter ke roop mein
POST /getUserOrders // REST nahi haiList endpoints par HAMESHA pagination do — bina limit ke "GET /users" ek din 5 lakh rows return karke server gira dega. Offset-based (page/limit) simple hai, cursor-based bade datasets par consistent aur tez hai.
// GET /users?page=2&limit=20&sort=-createdAt&role=admin
const limit = Math.min(Number(req.query.limit) || 20, 100); // hard cap
const page = Math.max(Number(req.query.page) || 1, 1);
res.json({ data, meta: { page, limit, total } });