Resource Naming and URIs
Consistent and intuitive resource naming is crucial for API usability. APIs should use plural nouns for collections and singular nouns or IDs for specific resources.
- Collections:
/users,/products - Specific Resources:
/users/{userId},/products/{productId} - Nested Resources:
/users/{userId}/orders
URIs should be hierarchical and reflect the relationships between resources. Avoid verbs in URIs; actions are typically handled by HTTP methods.
HTTP Methods (Verbs)
Leverage standard HTTP methods to represent actions on resources:
GET: Retrieve a resource or collection. (Idempotent, Safe)POST: Create a new resource or perform an action. (Not Idempotent)PUT: Update a resource entirely. (Idempotent)PATCH: Partially update a resource. (Not Idempotent)DELETE: Remove a resource. (Idempotent)
Understanding idempotency is key for reliable distributed systems.
Status Codes
Use appropriate HTTP status codes to communicate the outcome of a request:
200 OK: Standard success.201 Created: Resource successfully created.204 No Content: Successful request, but no content to return.
400 Bad Request: Generic client-side error.401 Unauthorized: Authentication required.403 Forbidden: Authenticated, but lacks permission.404 Not Found: Resource not found.409 Conflict: Resource conflict (e.g., duplicate).422 Unprocessable Entity: Semantic errors in the request.
500 Internal Server Error: Generic server error.503 Service Unavailable: Server temporarily unable to handle the request.
Request and Response Bodies
JSON is the de facto standard for request and response bodies. Maintain consistency in field naming (e.g., camelCase).
Request Example (POST /users)
{
"username": "johndoe",
"email": "john.doe@example.com",
"firstName": "John",
"lastName": "Doe"
}
Response Example (GET /users/{userId})
{
"id": "a1b2c3d4",
"username": "johndoe",
"email": "john.doe@example.com",
"firstName": "John",
"lastName": "Doe",
"createdAt": "2023-10-27T10:00:00Z",
"updatedAt": "2023-10-27T10:00:00Z"
}
Versioning
API versioning is essential for managing changes without breaking existing clients. Common strategies include:
- URI Versioning:
/v1/users,/v2/users - Header Versioning:
Accept: application/vnd.myapi.v1+json - Query Parameter Versioning:
/users?version=1
Choose a strategy and document it clearly. URI versioning is often the most explicit.
Error Handling
Provide informative error responses. A common pattern includes:
{
"error": {
"code": "invalid_input",
"message": "The provided email address is not valid.",
"details": [
{
"field": "email",
"message": "Must be a valid email format."
}
]
}
}
Use appropriate HTTP status codes in conjunction with error payloads.
Filtering, Sorting, and Pagination
Enable clients to control the data they receive for collections.
- Filtering:
GET /products?category=electronics&price_lte=500 - Sorting:
GET /users?sort=-createdAt(descending),GET /users?sort=username(ascending) - Pagination:
- Offset-based:
GET /items?offset=20&limit=10 - Cursor-based:
GET /items?after_cursor=some_token&limit=10
- Offset-based:
Include pagination metadata in responses (e.g., `next`, `prev`, `total`).
Authentication & Authorization
Secure your APIs. Common methods include:
- API Keys: Passed via custom headers (e.g.,
X-API-Key: your_key) or query parameters. - OAuth 2.0: For user delegation and third-party access.
- JWT (JSON Web Tokens): Commonly used with OAuth 2.0.
Clearly define scopes and permissions.