Fine-grained and coarse-grained resource APIs

While building a RESTful web API, you should try avoiding the chattiness of APIs. On the other hand, APIs should not be very coarse-grained as well. Highly coarse-grained APIs become too complex to use because the response representation may contain a lot of information, all of which may not be used by a majority of your API clients.

Let's take an example to understand the difference between fine-grained and coarse-grained approaches for building APIs. Suppose that you are building a very fine-grained API to read the employee details as follows:

  • API to read employee name: GET /employees/10/name
  • API to read employee address1: GET /employees/10/address1
  • API to read employee address2: GET /employees/10/address2
  • API to read employee email: GET /employees/10/email

It is obvious that a majority of your clients may need all the preceding details to work on an employee resource. As a result, clients may end up making four different remote API calls to get all the required details of an employee resource. This is very expensive in terms of the network (resource) usage and CPU cycles. A possible solution to this scenario of converting all these fine-grained APIs into a coarse-grained API that returns all the required details as part of a single API call is GET /employees/10.

On the other hand, highly coarse-grained APIs may not fit all use cases. Suppose that you built a very coarse-grained API that returns an employee resource along with the associated department, /employees/{id}. If not many consumers use the department details present in the employee resource, it simply makes the API complex to use and does not add any value for the consumers.

A better solution to this scenario is to build two separate fine-grained APIs, one for reading employee details and the other for reading the department details as shown here:

  • API to read individual employee details: GET /employees/10
  • API to read department of an employee: GET /employees/10/departments

To summarize this discussion, always look at the usage pattern of the APIs and the consumer requirements before deciding on the granularity of the APIs. Although very fine-grained APIs may not be an efficient solution for many use cases, it is perfectly valid to have fine-grained inner interfaces (not exposed for public) if this improves the modularity of the application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.212.102