API design

Designing REST APIs: Basics

REST is an architectural style like a design pattern for APIs. It is not necessary to follow, but if you follow you APIs will be scalable, reliable, and predictable.

REST APIs built on HTTP, so it says how to use HTTP request methods.

REST APIs are designed around resources, data that is accessed by clients.

REST uniform interface, stateless, cacheable.

A resource has identifier — URI.

Clients get data in JSON mostly.

REST APIs use a stateless request model.

  • HTTP requests should be independent and may occur in any order, so keeping transient state information between requests is not feasible.
  • The only place where information is stored is in the resources themselves, and each request should be an atomic operation.
  • This constraint enables web services to be highly scalable because there is no need to retain any affinity between clients and specific servers. Any server can handle any request from any client.

Designing REST APIs: Best Practices

  • Use nouns to denote resources in URL instead of verbs.
  • The action should be denoted by the HTTP method and not the URL.
  • image
  • Collections should be plural
  • Hierarchical objects should be nested in the URI. Example: /tweets/<tweet-id>/replies.
  • Set Content-Type. Ex: Content-Type: application/json; charset=utf-8
  • Return proper HTTP Status Code.
  • Error message. Ex: {"error": "Invalid email address"}
  • Allow filtering, sorting through URL query parameters.
    • Why? Fetch the data clients needs.
    • Ex: /orders?minCost=n
  • Pagination. Popular types of pagination — offset, cursor.
    • Ex: /orders?limit=25&offset=50
    • Offset
      1. Pros:

      2. offset pagination allows you to jump to any page
      3. Cons:

      4. the Offset will very likely have to load all the records from the first page to the page you want to get.
    • Cursor
      1. Pros:

      2. Querying high Offset will probably take a lot of time/timeout, while cursor pagination will be more performant
      3. good for real-time
      4. Cons:

      5. you can only jump into the next/previous page
  • Version the APIs to avoid breaking the clients consuming the APIs on changes in the contract.
  • Types: URI, query types, http header

  • Add cache-related headers in response headers to let the client know if it needs to cache the response with details on when to invalidate the cache.
SuperMade with Super