REST API Design
A well-designed REST API makes your application intuitive, scalable, and easy to maintain. This guide covers essential patterns and conventions.
REST Principles
REST (Representational State Transfer) relies on these core ideas:
- Resources — Everything is a resource identified by a URL
- HTTP Methods — Use standard verbs to perform actions
- Stateless — Each request contains all necessary information
- Uniform Interface — Consistent URL and response patterns
HTTP Methods
| Method | Purpose | Example |
|---|---|---|
GET | Read resource(s) | GET /api/users |
POST | Create a resource | POST /api/users |
PUT | Replace a resource | PUT /api/users/1 |
PATCH | Partial update | PATCH /api/users/1 |
DELETE | Remove a resource | DELETE /api/users/1 |
URL Design
Good URL patterns are predictable and hierarchical:
# Collection
GET /api/articles # List all articles
POST /api/articles # Create an article
# Single resource
GET /api/articles/42 # Get article #42
PUT /api/articles/42 # Update article #42
DELETE /api/articles/42 # Delete article #42
# Nested resources
GET /api/articles/42/comments # Comments on article #42Response Structure
Use a consistent JSON envelope for all responses:
{
"status": "success",
"data": {
"id": 42,
"title": "REST API Design",
"author": "diqitech",
"createdAt": "2024-01-15T10:30:00Z"
}
}For errors:
{
"status": "error",
"message": "Resource not found",
"code": "NOT_FOUND"
}Status Codes
Use appropriate HTTP status codes:
200— Success201— Created400— Bad request (validation error)401— Unauthorized404— Not found500— Internal server error
Pagination
For large collections, implement cursor-based or offset pagination:
GET /api/articles?page=2&limit=20{
"status": "success",
"data": [...],
"meta": {
"page": 2,
"limit": 20,
"total": 156,
"totalPages": 8
}
}Best Practices
- Use plural nouns for resource names (
/users, not/user) - Version your API (
/api/v1/users) - Filter via query params (
?status=active&sort=-createdAt) - Rate limit your endpoints to prevent abuse
- Document everything with OpenAPI/Swagger