REST API Design
Subject: nodejs
REST API Design
REST (Representational State Transfer) is an architectural style for building scalable, maintainable, and stateless web APIs using standard HTTP methods.
Key Principles of REST
- Client-Server: Separates frontend and backend for independent development.
 - Statelessness: Each request must contain all needed information.
 - Cacheability: Responses define their cache behavior.
 - Uniform Interface: Consistent method of communication with resources.
 - Layered System: APIs can use intermediaries like proxies.
 - Code-on-Demand (optional): Server can send code to client.
 
HTTP Methods (Verbs)
- GET: Retrieve data (safe, idempotent).
 - POST: Create new resource (not idempotent).
 - PUT: Replace resource (idempotent).
 - PATCH: Partially update resource.
 - DELETE: Remove resource.
 
Resource Naming Best Practices
- Use plural nouns (e.g., 
/users) - Use lowercase kebab-case (e.g., 
/user-profiles) - Nest resources for relationships (e.g., 
/users/{id}/orders) 
Example: User API
1. Create User
POST /api/v1/users
Response
2. Get All Users
GET /api/v1/users
Response
3. Get User by ID
GET /api/v1/users/123
Response
If not found:
Status Codes
- 200 OK: Successful GET/PUT/PATCH/DELETE
 - 201 Created: Resource created (POST)
 - 204 No Content: Success without content
 - 400 Bad Request: Invalid request
 - 401 Unauthorized, 403 Forbidden
 - 404 Not Found, 409 Conflict
 - 500 Internal Server Error
 
Versioning
Use URI versioning: /api/v1/...
Pagination & Filtering
- Filtering: 
/products?category=electronics&price_gt=100 - Sorting: 
/users?sort=name,-age - Pagination: 
/items?limit=10&offset=20 
Security
- Use HTTPS
 - Use authentication (e.g., JWT, OAuth)
 - Validate inputs
 - Apply rate limiting
 
Key Takeaways
- RESTful APIs are stateless, resource-based, and use standard HTTP methods.
 - Follow naming and status code best practices.
 - Use versioning and error structures for maintainability.
 - Secure APIs with authentication, validation, and HTTPS.
 - Document your API clearly for ease of use.