- Amir Boroumand | Software engineer based in Pittsburgh, PA/
- blog/
- π Six Rules for Designing a REST API/
π Six Rules for Designing a REST API
1. Use the correct verbs #
REST APIs rely on standard HTTP verbs to ensure that the purpose of each request is clear and semantically accurate. These verbs include:
GET
for retrieving resourcesPOST
for creating new resourcesPUT
for updating/replacing resourcesPATCH
for partially updating resourcesDELETE
for removing resources
Following this convention makes the API intuitive and predictable which improves the developer experience.
2. Status codes should convey the outcome #
HTTP status codes should convey the result of an API request. They help clients understand whether a request has been successful, if an error occurred, and what type of error it was.
Key status codes to use include:
200 OK
for successful requests201 Created
for successfully creating a resource400 Bad Request
for invalid request formats401 Unauthorized
for unauthenticated access attempts403 Forbidden
for unauthorized access attempts404 Not Found
for non-existent resources500 Internal Server Error
for server-side issues
Using appropriate status codes makes your API more reliable and easier to debug.
3. Resource names should be nouns #
Resource naming should be intuitive and consistent, using nouns to represent resources. Plural nouns are generally preferred to indicate collections (/users
for a list of users) and singular nouns for individual resources (/users/{id}
for a specific user). This convention simplifies the understanding of API endpoints and their relationships to the resources they manipulate.
4. Zero breaking changes #
If the need for a breaking change arises, then the best course of action is to deprecate that endpoint and create a new one. This can also be handled via API versioning. Versioning is typically done via the URI (/v2) but can also be accomplished via headers.
5. Pagination and filtering #
To avoid overwhelming clients with too much data and to improve the efficiency of your API, implement pagination and filtering. Pagination limits the number of items returned in a single response, while filtering allows clients to request only the data they need. Both features enhance performance and usability.
You donβt want to return a 10 MB response body that contains thousands of records to a browser.
6. API documentation #
Good documentation helps the adoption of public API’s. Comprehensive and clear documentation is the cornerstone of a successful API. It should detail available endpoints, supported HTTP methods, expected request and response formats, status codes, and error messages. Additionally, providing examples and best practices can significantly improve the developer experience. Good documentation is not just a reference guide; it’s an invitation to use your API effectively. This is especially important for a public API since adoption will hinge on how easily other developers can grok your API.