REST API Design Best Practices Prompt
Overview
This prompt guides you through designing REST APIs that are intuitive, scalable, and maintainable for both developers and systems.
Core REST Principles
1. Resource-Based Design
- Resources: Identify the key entities in your system
- URIs: Design intuitive, hierarchical resource paths
- HTTP Methods: Use appropriate verbs for operations
Good URI Design:
/users # Collection of users
/users/{id} # Specific user
/users/{id}/posts # User's posts
/posts?author={id} # Alternative: query parameter
2. HTTP Methods Mapping
| Method | Operation | Safe | Idempotent |
|---|---|---|---|
| GET | Read resource(s) | Yes | Yes |
| POST | Create resource | No | No |
| PUT | Update/replace resource | No | Yes |
| PATCH | Partial update | No | No |
| DELETE | Remove resource | No | Yes |
API Structure
Consistent Patterns
Base URL: https://api.example.com/v1
Resource Collections:
/users
/posts
/comments
/categories
Individual Resources:
/users/{id}
/posts/{id}
/comments/{id}
/categories/{id}
Sub-resources:
/users/{id}/posts
/posts/{id}/comments
/users/{id}/followers
Versioning Strategy
- URL Path:
/v1/users(most common) - Header:
Accept: application/vnd.api.v1+json - Query Parameter:
/users?version=1(least preferred)
Request/Response Design
Request Format
{
"data": {
"type": "user",
"attributes": {
"name": "John Doe",
"email": "[email protected]"
}
}
}
Response Format
{
"data": {
"id": "123",
"type": "user",
"attributes": {
"name": "John Doe",
"email": "[email protected]",
"created_at": "2024-01-15T10:30:00Z"
},
"links": {
"self": "/users/123"
}
}
}
Error Handling
HTTP Status Codes
200 OK - Success
201 Created - Resource created
204 No Content - Success, no response body
400 Bad Request - Invalid request
401 Unauthorized - Authentication required
403 Forbidden - Authorization failed
404 Not Found - Resource doesn't exist
409 Conflict - Resource state conflict
422 Unprocessable Entity - Validation errors
429 Too Many Requests - Rate limited
500 Internal Server Error - Server error
Error Response Format
{
"error": {
"code": "VALIDATION_ERROR",
"message": "The request contains invalid data",
"details": [
{
"field": "email",
"message": "Must be a valid email address"
}
]
}
}
Pagination
Offset-Based Pagination
GET /users?page=2&limit=50
Cursor-Based Pagination
GET /users?cursor=eyJpZCI6MTIzfQ&limit=50
Response with Pagination
{
"data": [...],
"links": {
"self": "/users?page=2&limit=50",
"first": "/users?page=1&limit=50",
"prev": "/users?page=1&limit=50",
"next": "/users?page=3&limit=50",
"last": "/users?page=10&limit=50"
},
"meta": {
"total": 500,
"page": 2,
"limit": 50
}
}
Filtering and Sorting
Filtering
GET /users?status=active&role=admin
GET /posts?published=true&author=john
GET /orders?created_after=2024-01-01&total_gte=100
Sorting
GET /users?sort=name
GET /users?sort=-created_at,name (desc created_at, asc name)
Search
GET /users?search=john
GET /posts?q=machine%20learning
Rate Limiting
Headers to Include
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200
Retry-After: 3600 (when rate limited)
Rate Limit Response
{
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "Too many requests",
"retry_after": 3600
}
}
Authentication & Authorization
API Keys
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
OAuth 2.0
Authorization: Bearer <access_token>
API Key in Header
X-API-Key: your-api-key-here
Documentation
OpenAPI Specification
openapi: 3.0.0
info:
title: User Management API
version: 1.0.0
paths:
/users:
get:
summary: Get users
parameters:
- name: limit
in: query
schema:
type: integer
default: 20
Essential Documentation Elements
- Endpoint descriptions: What each endpoint does
- Parameter definitions: Required vs optional, types, formats
- Response examples: Success and error cases
- Authentication requirements: How to authenticate
- Rate limits: What’s allowed
- Changelog: What’s changed between versions
Security Considerations
Input Validation
- Sanitize inputs: Prevent injection attacks
- Validate formats: Email, phone, dates, etc.
- Type checking: Ensure correct data types
- Length limits: Prevent buffer overflows
HTTPS Only
- Always use HTTPS: Never expose APIs over HTTP
- Certificate pinning: Additional security layer
- HSTS headers: Force HTTPS usage
CORS Configuration
// Allow specific origins
Access-Control-Allow-Origin: https://yourapp.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Performance Optimization
Caching Strategies
- ETags: Conditional requests
- Cache-Control headers: Browser caching
- CDN integration: Global distribution
Database Optimization
- Indexing: Proper database indexes
- Query optimization: Efficient database queries
- Connection pooling: Reuse database connections
Response Compression
Content-Encoding: gzip
Accept-Encoding: gzip, deflate
Testing Strategy
Unit Tests
- Endpoint logic: Business logic testing
- Validation: Input validation testing
- Error handling: Error response testing
Integration Tests
- Full request flow: End-to-end testing
- Database interactions: Data persistence testing
- External service calls: Third-party integration testing
Load Testing
- Concurrent users: Multiple user simulation
- Peak load handling: Stress testing
- Rate limit testing: Boundary condition testing
Monitoring & Analytics
Key Metrics to Track
- Response times: API performance
- Error rates: Reliability monitoring
- Usage patterns: Popular endpoints
- Rate limit hits: Capacity planning
Logging
{
"timestamp": "2024-01-15T10:30:00Z",
"method": "GET",
"path": "/users/123",
"status": 200,
"duration": 45,
"user_id": "user_456",
"ip": "192.168.1.1"
}
Remember, great APIs are designed with both machines and humans in mind. They should be intuitive to use, well-documented, and built to last.