REST API Best Practices
API design patterns and best practices.
URL Design
Use nouns, not verbs
Good: GET /api/users
Bad: GET /api/getUsers
Use plural nouns
/api/users not /api/user
Nested resources
/api/users/123/posts
/api/users/123/posts/456
Filtering and sorting
/api/users?status=active
/api/users?sort=name&order=asc
Pagination
/api/users?page=2&limit=20
Versioning
URL versioning
/api/v1/users
/api/v2/users
Header versioning
Accept: application/vnd.api.v1+json
Query parameter
/api/users?version=1
Error Handling
Consistent error format
{
"error": {
"code": "USER_NOT_FOUND",
"message": "User not found",
"status": 404
}
}
Validation errors
{
"error": {
"code": "VALIDATION_ERROR",
"fields": {
"email": "Invalid email format"
}
}
}
Response Format
Single resource
{
"id": 123,
"name": "John",
"email": "[email protected]"
}
Collection with metadata
{
"data": [...],
"meta": {
"total": 100,
"page": 1,
"perPage": 20
}
}