REST API Design thực tế: URL, status codes, versioning, pagination, và error format
REST API không có spec cứng, nhưng có conventions được cộng đồng chấp nhận rộng rãi. API design tốt là API mà developer không cần đọc docs nhiều để đoán đúng cách dùng. Bài này đúc kết những conventions quan trọng nhất — không phải lý thuyết, mà là những quyết định cụ thể bạn cần đưa ra khi xây API.
HTTP methods — dùng đúng ngữ nghĩa
GET /api/v1/users # Lấy danh sách users
GET /api/v1/users/42 # Lấy user #42
POST /api/v1/users # Tạo user mới
PUT /api/v1/users/42 # Replace toàn bộ user #42 (idempotent)
PATCH /api/v1/users/42 # Update một phần user #42
DELETE /api/v1/users/42 # Xóa user #42
# Nested resources
GET /api/v1/users/42/orders # Orders của user #42
GET /api/v1/users/42/orders/101 # Order #101 của user #42
POST /api/v1/users/42/orders # Tạo order cho user #42
- Idempotent: GET, PUT, DELETE — gọi nhiều lần cho kết quả giống nhau
- Safe: GET — không thay đổi state
- Không idempotent: POST — gọi 2 lần tạo 2 resources
- Dùng danh từ số nhiều (
/users,/orders), không dùng động từ (/getUser,/createOrder)
Status codes cần biết
200 OKGET thành công, hoặc PATCH/PUT trả về resource đã update
201 CreatedPOST tạo resource thành công — thêm Location header trỏ đến resource mới
204 No ContentDELETE thành công, hoặc PUT/PATCH không trả body
400 Bad RequestRequest body/params sai format, thiếu field required
401 UnauthorizedChưa authenticate (không có hoặc token invalid)
403 ForbiddenĐã authenticate nhưng không có quyền với resource này
404 Not FoundResource không tồn tại
409 ConflictConflict với state hiện tại — ví dụ email đã tồn tại
422 UnprocessableFormat đúng nhưng business logic validation fail
429 Too Many RequestsRate limit exceeded
500 Internal ErrorLỗi server không mong đợi
401 vs 403: 401 = "Tôi không biết bạn là ai" (chưa login hoặc token hết hạn). 403 = "Tôi biết bạn là ai nhưng bạn không được phép làm điều này". Sự khác biệt quan trọng cho client xử lý đúng.
URL versioning
# URL versioning — phổ biến nhất, rõ ràng, dễ test
https://api.example.com/v1/users
https://api.example.com/v2/users # breaking changes
# Header versioning — cleaner URL nhưng khó test trực tiếp
GET /users
Accept: application/vnd.example+json;version=1
# Bao giờ cần v2?
# - Thay đổi cấu trúc response (rename/remove fields)
# - Thay đổi URL structure
# - Thay đổi authentication flow
# - Breaking changes trong behavior
# Không phải breaking change (không cần version mới):
# - Thêm optional field mới vào response
# - Thêm optional query param mới
# - Thêm endpoint mới
Error response format
Consistent error format giúp client xử lý lỗi chung, không phải parse riêng từng endpoint:
// Lỗi đơn (400 Bad Request)
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Request validation failed",
"details": [
{
"field": "email",
"message": "Invalid email format"
},
{
"field": "age",
"message": "Must be a positive integer"
}
]
}
}
// Lỗi business logic (422 Unprocessable)
{
"error": {
"code": "EMAIL_ALREADY_EXISTS",
"message": "An account with this email already exists"
}
}
// Lỗi server (500)
{
"error": {
"code": "INTERNAL_ERROR",
"message": "An unexpected error occurred",
"request_id": "req_01J2K..." // để trace log
}
}
Pagination — offset vs cursor
Offset pagination (đơn giản, có giới hạn)
GET /api/v1/posts?page=2&per_page=20
// Response
{
"data": [...],
"pagination": {
"total": 483,
"page": 2,
"per_page": 20,
"total_pages": 25
}
}
// Vấn đề: với large offset (trang 1000+), DB vẫn phải scan qua 19980 rows
// Vấn đề: nếu có record mới insert, page 2 có thể bị lệch (missing/duplicate rows)
Cursor pagination (scalable, cho feed/timeline)
GET /api/v1/posts?limit=20
GET /api/v1/posts?limit=20&cursor=eyJpZCI6MTIzfQ # cursor là base64 encoded
// Response
{
"data": [...],
"pagination": {
"next_cursor": "eyJpZCI6MTAzfQ", // null nếu không có trang kế
"has_more": true
}
}
// SQL implementation
SELECT * FROM posts
WHERE id < :cursor_id -- cursor encode ID hoặc timestamp của row cuối
ORDER BY id DESC
LIMIT 20;
// Ưu điểm: O(1) không phụ thuộc offset, không bị lệch khi có data mới
// Nhược điểm: không nhảy đến trang cụ thể được
Rate limiting headers
# Response headers cho rate limiting
X-RateLimit-Limit: 100 # số requests tối đa trong window
X-RateLimit-Remaining: 87 # còn lại trong window hiện tại
X-RateLimit-Reset: 1719446400 # Unix timestamp khi window reset
# Khi bị rate limit (429)
Retry-After: 30 # giây cần chờ trước khi retry
Query parameters chuẩn
# Filtering
GET /api/v1/orders?status=pending&user_id=42
# Sorting (prefix - cho DESC)
GET /api/v1/orders?sort=-created_at,+total_amount
# Field selection (giảm payload)
GET /api/v1/users?fields=id,name,email
# Search
GET /api/v1/products?q=laptop+gaming
# Date range
GET /api/v1/orders?from=2025-06-01&to=2025-06-30
# Combination
GET /api/v1/orders?status=completed&sort=-created_at&page=1&per_page=20
Authentication — một số conventions
# Bearer token trong Authorization header (không trong URL)
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
# API key cho server-to-server (cũng trong header, không URL)
X-API-Key: sk_live_abc123...
# Tại sao không đặt token trong URL?
# URL bị lưu trong server logs, browser history, Referer headers
# → token bị expose dễ dàng hơn nhiều