REST API Best Practices

rachid benouini
6 min readAug 1, 2022

--

Many developers struggle with designing and building good REST APIs, which are adequately designed, appropriately implemented, effectively documented, well secured, optimized, and easy to use and adopt.
This post will go through more than 30 best practices to keep in mind when designing and building REST APIs.

1. Design

  • Designing the API according to the principles of REST allows easier build on any platform.
  • The API design must take care of the elements that are connected to it.
  • Don’t design your API in a vacuum, work with a customer and their use-cases.
  • Design and build the API with consumers in mind, don’t design it for a specific UI.

2. Contract First

  • In a Contract-First approach, you first define the contract, and then implement the service.

3. Think early integration

  • Mock API are crucial in developing and testing apps. They help stimulate imitations of real APIs.

4. Idempotent methods

  • The operations GET, HEAD, PUT, DELETE, OPTIONS and TRACE are all intended to be idempotent. There should be no adverse side effects from those operations.

5. HTTP Semantics

  • Define the API operations in terms of HTTP methods, with conformity to HTTP semantics.
  • Use GET to retrieve information, POST to create a new resource, PUT and PATCH to update existing resources, and DELETE to delete a resource.

6. Descriptive endpoints

  • Use nouns instead of verbs in endpoint URL paths
  • Use snake_case vs camelCase for field names
  • Good endpoint description enables an intuitive understanding of what a developer might experience when interacting with a particular endpoint.
  • Endpoint should not reflect how the resources are organized internally.

7. Parameters with good default values

  • It is important to provide any optional parameters with good default values.

8. Accept and respond with JSON

  • REST APIs should accept JSON for request payload and send responses as JSON.
  • Updates and creation shouldn’t be silent, must return a meaningful resource representation as JSON.

9. Readable responses

  • The lightweight syntax of JSON makes it preferred over XML for responses.
  • Use meaningful status codes for the API responses.
  • The data in the API responses must be easily accessible and readable.

10. Content negotiation

  • One can create his own content type for better description of incoming request payloads.
  • It is important to use content negotiation to support multiple representations of your resources

11. Statelessness

  • Keep the API state-free so that they can be easily and painlessly scalable.

12. Bulk Operations

  • To reduce networking overhead, bulk (batch) operations are used to perform an action on more than one resource in single request.

13. Automated Testing

  • Consider building automated tests for the API.

14. Feedback

  • Don’t forget to give your API users a chance to offer you feedback on the API.

15. Open API Initiative

  • Consider OpenAPI Specification that comes with a set of opinionated guidelines on how a REST API should be designed.

16. Manage Connectedness

  • Consider connectedness of data by utilizing a linking strategy, like JSON-LD.

17. Standard format and types

  • Consider the support of Unicode in an API endpoint.
  • Use proper formats for text, numbers, date, and time representation.

18. Discoverability

  • The API should also help the client discover the valid HTTP methods that are allowed for a particular resource.

19. Evolution over versioning

  • API version should be embedded in the path of the request URL or as a query string parameter of the URL.
  • One can use Semantic Versioning (SemVer) to version an API just as much as to packaged software.

20. Maintain Good Security Practices

  • Make sure to encrypt any traffic to your application with SSL/TLS.
  • Be aware of subtle denial-of-service attacks too, like Slowloris, Billion laughs, and ReDoS.
  • Prevent a client from smashing your API by not exceeding a specific number of requests.
  • Don’t allow your API to be accessed with the same credentials that your interactive UI sessions use (CSRF attacks).

21. Authorization and Authentication

  • Authentication should not depend on cookies or sessions.
  • In case token-over-basic-auth is not a good option for authentication, then OAuth mechanism should be used to provide secure token transfer to a third party.
  • It’s good to have a separate identity service which is dedicated to Authentication and Authorization purposes.

22. Error handling

  • It is convenient for the API endpoint to return error details in the JSON or response body.
  • It is important to include the affected field in error to help a user with debugging.
  • Handle errors gracefully and return standard error codes.

23. Caching

  • A Cache-Control header on the API responses can be used to provide the maximum number of seconds (max age) a response can be cached.
  • The API response should provide information to the clients to check if their cached copy is still valid.

24. Rate limiting

  • It is standard practice to add some sort of rate limiting to an API.
  • One can use the HTTP status code 429 Too Many Requests to accommodate this.
  • Notify the consumer of their limits before they hit it.

25. Support result filtering, sorting, searching and pagination

  • It is important to consider filtering, sorting, searching and pagination operations, when exposing a collection of resources through the API, the objective is to overcome the issue of fetching large amounts of data when only a subset of the information is required.

26. Compression

  • To improve the network performance, HTTP compression can be used for response bodies and request bodies by (Accept-Encoding: gzip and Content-Encoding: gzip).
  • When output readability is important, one can use pretty printing of JSON output (no need to do white-space compression).

27. Logging

  • Design your logging service along with your API.
  • Avoid logging excessively and anywhere, log what is important.
  • Separate between logs caused by the client input and by the API service itself.

28. Remove hardcoded Values

  • Don’t hardcode the business logic in your API, make it configurable.

29. Dependency

  • Deployment should be done with any dependency with other services.
  • If a service depends on another, then it will not be a good practice.

30. Fault tolerance

  • Robust fault tolerance system is necessary if you have several APIs.

31. Documentation

  • The faster developers understand your API documentation, the faster they start using it.
  • API doc should contain the relevant information such as the endpoint, methods, parameter options, input, and output examples.
  • The docs should be easy to find and publicly accessible.
  • Swagger is an excellent alternative to writing documentation and API contract.

32. Consistency fundamentals

  • The API requests and endpoints should be easy to construct without a well-supported client library.

33. Long running operations

  • Support partial responses for large binary resources and long running operations

34. Support notifications

  • Webhooks extends the REST API infrastructure to enable you to further integrate your applications with other services when data updates occur.

35. Handle Unsupported requests

  • The API must provide an error response if a caller requests an unsupported feature.

36. Absolute Redirects

  • For compatibility reasons with a broad range of clients, the API should use absolute URIs in any redirects.

References

--

--