📐
REST APIs with Express

REST API Design

Resources, Nouns aur Consistency
💡 REST API EK ACHCHE SE ORGANISED LIBRARY jaisa hai — shelves cheezon (nouns) se labelled hain, aur tum unke saath standard actions (padhna, lena, wapas karna) karte ho. Har shelf par apni alag bhaasha nahi likhi hoti.

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
📐
REST API EK ACHCHE SE ORGANISED LIBRARY jaisa hai — shelves cheezon (nouns) se labelled hain, aur tum unke saath standard actions (padhna, lena, wapas karna) karte ho. Har shelf par apni alag bhaasha nahi likhi hoti.
1 / 2
⚡ Quick Recap
  • 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
Is page mein (2 subtopics)

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 hai

List 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 } });