Chapter 2: RESTful API Design
Chapter 2 of 14
Chapter 2: RESTful API Design
2.1 REST Principles
REST (Representational State Transfer) is an architectural style for designing networked applications.
Core REST Principles:
- Stateless: Each request contains all information needed to process it
- Resource-based: URLs represent resources, not actions
- HTTP Methods: Use standard HTTP methods (GET, POST, PUT, DELETE)
- Uniform Interface: Consistent way to interact with resources
- Layered System: Architecture can have multiple layers
// RESTful resource design
// Resources are nouns, not verbs
GET /api/users // Get all users
GET /api/users/123 // Get user 123
POST /api/users // Create new user
PUT /api/users/123 // Update entire user 123
PATCH /api/users/123 // Partial update
DELETE /api/users/123 // Delete user 123
// Nested resources
GET /api/users/123/posts // Get posts by user 123
POST /api/users/123/posts // Create post for user 123
GET /api/users/123/posts/456 // Get specific post
2.2 Resource Naming Conventions
// Good: Plural nouns, lowercase, hyphens for multi-word
/api/users
/api/user-profiles
/api/order-items
// Bad: Verbs, mixed case, underscores
/api/getUsers
/api/UserProfiles
/api/order_items
2.3 HTTP Status Codes
// Success codes
200 OK // Successful GET, PUT, PATCH
201 Created // Successful POST
204 No Content // Successful DELETE
// Client error codes
400 Bad Request // Invalid request
401 Unauthorized // Authentication required
403 Forbidden // Insufficient permissions
404 Not Found // Resource doesn't exist
409 Conflict // Resource conflict
// Server error codes
500 Internal Server Error
502 Bad Gateway
503 Service Unavailable