REST Constraints
REST is defined by 6 constraints that guide API design.
Constraint 1: Client-Server
Client (Frontend) Server (Backend)
┌─────────────┐ ┌─────────────┐
│ UI Logic │ ←──────→ │ Business │
│ Rendering │ HTTP │ Logic │
└─────────────┘ └─────────────┘
Benefits:
- Independent evolution
- Separation of concerns
- Different teams can work separately
Constraint 2: Stateless
Each request contains ALL information needed:
Request 1:
GET /api/users/123
Authorization: Bearer token123
Request 2:
GET /api/users/456
Authorization: Bearer token456
Server stores NO client state between requests.
Benefits:
- Easy to scale (any server can handle any request)
- Simple failover
- No session affinity needed
Constraint 3: Cacheable
Responses must indicate if they can be cached:
Cache-Control: max-age=3600 (cache for 1 hour)
Cache-Control: no-cache (validate with server)
Cache-Control: no-store (never cache)
ETag: "v1.2.3" (version identifier)
Benefits:
- Reduced server load
- Faster responses
- Lower network usage
Constraint 4: Uniform Interface
Four sub-constraints:
1. Resource Identification
- Resources identified by URIs
- /users/123, /orders/456
2. Resource Manipulation
- Through representations (JSON, XML)
- PUT /users/123 with new representation
3. Self-Descriptive Messages
- Each message includes enough info
- Content-Type: application/json
4. HATEOAS (Hypermedia)
- Responses include links to related resources
- {"links": {"self": "/users/123", "orders": "/users/123/orders"}}
Constraint 5: Layered System
Client → Load Balancer → API Gateway → Service → Database
Client can't tell if it's talking to end server or intermediary.
Benefits:
- Load balancing
- Caching layers
- Security layers
Constraint 6: Code on Demand (Optional)
Server can send executable code:
- JavaScript (for web clients)
- Shell scripts (for CLI)
Rarely used in practice.
HTTP Methods
Each HTTP method has specific semantics and rules.
Method Semantics
| Method | Purpose | Idempotent | Safe | Request Body |
|---|---|---|---|---|
| GET | Read resource | Yes | Yes | No |
| POST | Create resource | No | No | Yes |
| PUT | Replace resource | Yes | No | Yes |
| PATCH | Partial update | No | No | Yes |
| DELETE | Delete resource | Yes | No | Optional |
| HEAD | Same as GET but no body | Yes | Yes | No |
| OPTIONS | Describe allowed methods | Yes | Yes | No |
Idempotency Explained
Idempotent: Same result whether called once or multiple times
GET /users/123
→ Always returns same user (doesn't change)
PUT /users/123
→ Replaces resource with provided data
→ Calling 3 times = same result as calling once
DELETE /users/123
→ Deletes resource
→ Calling 3 times = same result as calling once
POST /users
→ Creates new resource each time
→ Calling 3 times = creates 3 resources
PATCH /users/123
→ Partial update
→ Calling with different data = different results
Safe Methods
Safe: Doesn't modify server state
GET: Read only, no side effects
HEAD: Same as GET, no body
OPTIONS: Returns allowed methods
POST, PUT, PATCH, DELETE: Not safe (modify server)
PUT vs PATCH
PUT (Full Replace):
PUT /users/123
{
"name": "John",
"email": "john@example.com",
"age": 30
}
→ Replaces entire resource
PATCH (Partial Update):
PATCH /users/123
{
"email": "newemail@example.com"
}
→ Updates only provided fields
POST Usage
POST is used for:
1. Creating resources
POST /users → 201 Created
2. Actions that don't fit CRUD
POST /users/123/activate → 200 OK
3. Custom operations
POST /reports/generate → 202 Accepted
Status Codes
Status codes communicate the result of an HTTP request.
Status Code Categories
1xx: Informational
2xx: Success
3xx: Redirection
4xx: Client Error
5xx: Server Error
Common Status Codes
2xx Success:
200 OK - Successful request
201 Created - Resource created (POST)
204 No Content - Success, no body (DELETE)
3xx Redirection:
301 Moved Permanently - Resource moved
304 Not Modified - Use cached version
4xx Client Error:
400 Bad Request - Invalid input
401 Unauthorized - Not authenticated
403 Forbidden - Not authorized
404 Not Found - Resource doesn't exist
405 Method Not Allowed - Wrong HTTP method
409 Conflict - Resource conflict
422 Unprocessable Entity - Validation error
429 Too Many Requests - Rate limited
5xx Server Error:
500 Internal Server Error - Unexpected error
502 Bad Gateway - Upstream error
503 Service Unavailable - Service down
504 Gateway Timeout - Upstream timeout
Status Code Usage Guide
| Scenario | Status Code |
|---|---|
| Successful GET | 200 OK |
| Successful POST (created) | 201 Created |
| Successful DELETE | 204 No Content |
| Validation error | 422 Unprocessable Entity |
| Not authenticated | 401 Unauthorized |
| Not authorized | 403 Forbidden |
| Resource not found | 404 Not Found |
| Rate limited | 429 Too Many Requests |
| Server error | 500 Internal Server Error |
Error Response Format
{
"error": {
"code": 422,
"message": "Validation failed",
"details": [
{
"field": "email",
"message": "Invalid email format"
},
{
"field": "name",
"message": "Name is required"
}
]
}
}
Resource Modeling
Good resource modeling is essential for RESTful APIs.
Resource Identification
Nouns, not verbs:
Good:
GET /users (list)
GET /users/123 (get)
POST /users (create)
PUT /users/123 (update)
DELETE /users/123 (delete)
Bad:
GET /getUsers
POST /createUser
GET /user/delete/123
Resource Hierarchy
Flat:
/users
/orders
/products
Nested (related resources):
/users/123/orders
/users/123/orders/456/items
/products/789/reviews
Rules:
- Max 2 levels deep
- Use query params for filtering
Resource Relationships
One-to-Many:
/users/123/orders
Many-to-Many:
/products/789/categories
/categories/1/products
Self-referencing:
/users/123/followers
/users/123/following
Filtering, Sorting, Pagination
Filtering:
GET /users?status=active&role=admin
GET /orders?created_after=2024-01-01
Sorting:
GET /users?sort=name_asc
GET /users?sort=-created_at (descending)
Pagination:
GET /users?page=2&limit=20
GET /users?offset=20&limit=20
GET /users?cursor=abc123&limit=20
HATEOAS Example
{
"id": 123,
"name": "John Doe",
"email": "john@example.com",
"links": {
"self": "/users/123",
"orders": "/users/123/orders",
"avatar": "/users/123/avatar"
}
}
API Design Checklist
- Resources are nouns (users, orders)
- HTTP methods match operations
- Status codes are appropriate
- Consistent naming conventions
- Pagination for lists
- Filtering and sorting supported
- Error responses are helpful
- Versioning strategy defined
Practice Problems
Design a scalable REST system. Cover high-level architecture, data model, and API design.
Solution
// Complete system design:
// - Functional + Non-functional requirements
// - Capacity estimation
// - Data model (SQL/NoSQL choice)
// - API endpoints
// - Component architecture
// - Scaling strategy
// - Monitoring & reliabilityHow would you scale REST to handle 10x the current load? Identify bottlenecks and solutions.
Solution
// Scaling approach:
// 1. Load balancing
// 2. Database sharding/replication
// 3. Cache layer (Redis)
// 4. CDN for static assets
// 5. Async processing (queues)
// 6. Microservices decompositionAnalyze potential failure modes for REST and design mitigation strategies.
Solution
// Failure mitigation:
// 1. Redundancy (multi-AZ)
// 2. Circuit breakers
// 3. Retry with backoff
// 4. Dead letter queues
// 5. Health checks
// 6. Graceful degradationQuiz
1. What does it mean for a method to be idempotent?
2. When should you use PATCH instead of PUT?
3. What status code should you return when a resource is not found?
4. Why should REST APIs use nouns instead of verbs?
Flashcards
Question
What are the 6 REST constraints?
Click to reveal answer
Answer
1) Client-Server, 2) Stateless, 3) Cacheable, 4) Uniform Interface, 5) Layered System, 6) Code on Demand (optional).
Question
What is the difference between PUT and PATCH?
Click to reveal answer
Answer
PUT replaces the entire resource with the provided data. PATCH updates only the specific fields provided, leaving others unchanged.
Question
What does idempotent mean in HTTP?
Click to reveal answer
Answer
An operation is idempotent if calling it multiple times has the same effect as calling it once. GET, PUT, DELETE are idempotent; POST is not.
Question
What are the HTTP status code categories?
Click to reveal answer
Answer
1xx: Informational, 2xx: Success, 3xx: Redirection, 4xx: Client Error, 5xx: Server Error.
Question
How should you handle pagination in REST?
Click to reveal answer
Answer
Use query parameters: ?page=2&limit=20 (offset-based) or ?cursor=abc123&limit=20 (cursor-based). Cursor-based is better for real-time data.
Revision Notes
Key Takeaways
- 1.REST is defined by 6 constraints, with Stateless being critical for scalability
- 2.HTTP methods have specific semantics: idempotent, safe, request body
- 3.Use appropriate status codes to communicate results
- 4.Resource modeling should use nouns with HTTP methods for operations
- 5.Pagination, filtering, and sorting are essential for list endpoints
Interview Tips
- •Always discuss REST constraints when designing APIs
- •Use proper HTTP methods and status codes
- •Design resources as nouns, operations as HTTP methods
- •Consider pagination and filtering for list endpoints
Cheat Sheet
REST - Cheat Sheet
6 Constraints:
- Client-Server
- Stateless
- Cacheable
- Uniform Interface
- Layered System
- Code on Demand (optional)
HTTP Methods:
| Method | Purpose | Idempotent |
|---|---|---|
| GET | Read | Yes |
| POST | Create | No |
| PUT | Replace | Yes |
| PATCH | Update | No |
| DELETE | Delete | Yes |
Status Codes:
200 OK, 201 Created, 204 No Content
400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found
422 Validation Error, 429 Rate Limited
500 Server Error, 502 Bad Gateway, 503 Unavailable
Resource Modeling:
- Use nouns (/users, /orders)
- Max 2 levels deep
- Support filtering, sorting, pagination