REST API Design Best Practices
Master REST API design principles and patterns. Learn industry best practices for building scalable, maintainable, and developer-friendly APIs that stand the test of time.
What is REST?
REST (Representational State Transfer) is an architectural style for designing networked applications. It uses HTTP protocols and leverages standard HTTP methods to perform operations on resources.
Core REST Principles:
- • Client-Server architecture
- • Stateless communication
- • Cacheable responses
- • Uniform interface
- • Layered system
Resource Naming Conventions
✓ Best Practices
- → Use nouns, not verbs: /users not /getUsers
- → Use plural names: /users/123 not /user/123
- → Use lowercase: /user-profiles not /UserProfiles
- → Use hyphens for readability: /user-accounts not /user_accounts
- → Keep URLs short and intuitive: /users/123/orders not /api/v1/get-user-orders-by-id
Example Resource Structure
GET /users # List all users
POST /users # Create new user
GET /users/123 # Get specific user
PUT /users/123 # Update user (full)
PATCH /users/123 # Update user (partial)
DELETE /users/123 # Delete user
GET /users/123/orders # Get user's orders
POST /users/123/orders # Create order for user HTTP Methods
Read Resources
Retrieve data without side effects. Safe and idempotent.
- • Should not modify server state
- • Can be cached
- • Parameters in query string
Create Resources
Create new resources. Not idempotent.
- • Data in request body
- • Returns 201 Created with Location header
- • Multiple calls create multiple resources
Replace Resources
Full update of existing resource. Idempotent.
- • Complete resource in body
- • Creates if doesn't exist (upsert)
- • Same result on multiple calls
Partial Update
Partial modification of resource.
- • Only changed fields in body
- • More efficient than PUT
- • Use JSON Patch format
Remove Resources
Delete specified resource. Idempotent.
- • Returns 204 No Content
- • Multiple deletes have same effect
- • Consider soft deletes
HTTP Status Codes
Success (2xx)
200 OK- Request succeeded201 Created- Resource created204 No Content- Success, no body206 Partial Content- Partial response
Redirection (3xx)
301 Moved Permanently- Permanent redirect302 Found- Temporary redirect304 Not Modified- Cached version valid
Client Errors (4xx)
400 Bad Request- Invalid syntax401 Unauthorized- Auth required403 Forbidden- No permission404 Not Found- Resource missing429 Too Many Requests- Rate limited
Server Errors (5xx)
500 Internal Server Error- Server crash502 Bad Gateway- Invalid upstream503 Service Unavailable- Overloaded504 Gateway Timeout- Upstream timeout
API Versioning
1. URL Path Versioning (Recommended)
https://api.example.com/v1/users
https://api.example.com/v2/users ✓ Clear, explicit, easy to route, widely adopted
2. Header Versioning
GET /users
Accept: application/vnd.example.v2+json More RESTful but less visible
3. Query Parameter Versioning
https://api.example.com/users?version=2 Simple but mixes versioning with query params
Authentication & Security
Common Authentication Methods
- → API Keys: Simple but limited security (use for server-to-server)
- → OAuth 2.0: Industry standard for user authorization
- → JWT (JSON Web Tokens): Stateless, scalable, self-contained
- → Basic Auth: Simple but must use HTTPS (avoid for production)
Security Best Practices
- ✓ Always use HTTPS in production
- ✓ Implement rate limiting to prevent abuse
- ✓ Validate and sanitize all inputs
- ✓ Use CORS properly for browser security
- ✓ Never expose sensitive data in URLs
- ✓ Implement proper error handling
Pagination & Filtering
Pagination Approaches
Offset-based (Simple):
GET /users?limit=20&offset=40 Page-based (User-friendly):
GET /users?page=3&per_page=20 Cursor-based (Scalable):
GET /users?cursor=eyJpZCI6MTIzfQ&limit=20 Filtering & Sorting
# Filtering
GET /users?status=active&role=admin
# Sorting
GET /users?sort=created_at&order=desc
# Field selection
GET /users?fields=id,name,email
# Full-text search
GET /users?q=john Error Handling
Standard Error Response Format
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input data",
"details": [
{
"field": "email",
"message": "Email format is invalid"
},
{
"field": "age",
"message": "Must be at least 18"
}
],
"timestamp": "2025-01-15T10:30:00Z",
"request_id": "abc123"
}
} Error Response Guidelines
- • Use appropriate HTTP status codes
- • Provide clear, actionable error messages
- • Include error codes for programmatic handling
- • Never expose stack traces or internal details
- • Include request ID for debugging
API Documentation
Essential Documentation Elements
- → Authentication requirements and examples
- → All endpoints with HTTP methods
- → Request/response examples for every endpoint
- → Parameter descriptions and constraints
- → Status codes and error responses
- → Rate limiting information
Popular Documentation Tools
- • OpenAPI/Swagger: Industry standard specification
- • Postman: Interactive API documentation
- • Redoc: Beautiful OpenAPI documentation
- • API Blueprint: Markdown-based format
Performance Optimization
Caching Strategies
- • Use ETags for validation
- • Implement Cache-Control headers
- • Support conditional requests
- • Cache at multiple levels
Response Optimization
- • Enable gzip compression
- • Implement field filtering
- • Use pagination by default
- • Minimize payload size