·7 min read
REST API Design: Best Practices
REST (Representational State Transfer) is the most common API architecture. Good REST design makes APIs intuitive, consistent, and easy to use.
URL Structure
# Use nouns, not verbs GET /users # list users GET /users/123 # get specific user POST /users # create user PUT /users/123 # update user DELETE /users/123 # delete user # Nested resources GET /users/123/orders # user's orders GET /users/123/orders/456 # specific order
HTTP Methods
GET # Read (safe, idempotent) POST # Create (not idempotent) PUT # Replace entire resource (idempotent) PATCH # Partial update (not idempotent) DELETE # Remove (idempotent)
Status Codes
200 OK # Successful GET/PUT/PATCH 201 Created # Successful POST 204 No Content # Successful DELETE 400 Bad Request # Invalid input 401 Unauthorized # Missing/invalid auth 403 Forbidden # Insufficient permissions 404 Not Found # Resource doesn't exist 409 Conflict # Duplicate or state conflict 422 Unprocessable # Validation errors 429 Too Many Requests # Rate limit exceeded 500 Internal Server Error
Request/Response Format
// POST /users
// Request body
{
"name": "Alice",
"email": "alice@example.com"
}
// Response (201 Created)
{
"id": 123,
"name": "Alice",
"email": "alice@example.com",
"createdAt": "2024-01-15T10:30:00Z"
}Pagination
# Offset-based
GET /users?page=2&limit=20
# Cursor-based (better for real-time data)
GET /users?cursor=abc123&limit=20
# Response with pagination metadata
{
"data": [...],
"pagination": {
"page": 2,
"limit": 20,
"total": 150,
"hasNext": true
}
}Filtering, Sorting, Searching
# Filtering GET /users?status=active&role=admin # Sorting GET /users?sort=name:asc GET /users?sort=-createdAt # descending # Searching GET /users?q=alice # Field selection GET /users?fields=name,email
Versioning
# URL versioning (most common) GET /v1/users GET /v2/users # Header versioning Accept: application/vnd.api.v1+json
Error Response Format
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input data",
"details": [
{ "field": "email", "message": "Invalid email format" },
{ "field": "age", "message": "Must be 18 or older" }
]
}
}Authentication
# Bearer token (most common) Authorization: Bearer eyJhbGciOiJIUzI1NiIs... # API key X-API-Key: your-api-key-here
Best Practices
- Use plural nouns for resources (
/usersnot/user) - Use HTTP methods correctly (GET for reads, POST for creates)
- Return meaningful error messages with proper status codes
- Support pagination for list endpoints
- Use consistent naming conventions (camelCase or snake_case)
- Version your API from day one