5

I am working on a REST API for managing users. Each user has a name and a surname and a list of his own contacts (name, type, value). I am considering two approaches to modelling the REST API, the coarse grained approach:

  • GET /user/{id}, to get the user details along with his contacts
  • POST /users, to add a new user along with his contacts
  • PUT /users/{id}, to update a user along with his contacts

or the fine grained approach:

  • GET /user/{id}, to get the user details
  • GET /user/{id}/contacts, to get the user's contacts
  • POST /user, to add a new user
  • PUT /user/{id}, to update a user
  • POST /user/{id}/contacts, to add a new user contact
  • PUT /user/{id}/contact/{id}, to update a user contact
  • DELETE /user/{id}/contact/{id}, to delete a user contact

When the fine grained approach should be choosen over the coarse grained approach?

Adam Siemion
  • 15,569
  • 7
  • 58
  • 92
  • why couldn't both be used? post/put just adds/updates a user and their contacts, but you can also edit the contacts individually if you want? – Sam Holder Feb 12 '16 at 15:13
  • For more see this question: [Coarse grained vs Fine grained](https://stackoverflow.com/q/3766845/7794769) – stomy Jan 27 '21 at 19:19

1 Answers1

3

This decision comes down to how your API will be consumed. If a primary functionality of this API is to track user's contacts, then I think it makes sense to go with the fine grained approach.

As a consumer of the API, the fine grained approach has the same functionality as the coarse grained approach, but also adds more specific endpoints. Think about it this way, as the developer of the backend you know that the contacts are nested inside the user object, but the consumer of the API doesn't know this nor do they need to know this. They just know that there is some relationship between a user and its contacts.

Additionally, the fine grained approach will keep your backend code very organized. You will have specific methods for each endpoint that your API provides and for that reason the code will be cleaner to read and understand. You can also have more fine-grained and clean error-handling.

Mike
  • 10,297
  • 2
  • 21
  • 21
  • What is the source of the statement that fine grained approach keeps the backend code clean? Have you assumed that a relational database (not documented based) is used, where each API call in the fine grained approach is one SQL update (insert/update/delete) to one database table? – Adam Siemion Feb 17 '16 at 08:04
  • Yes, assuming that each of these requests corresponds to a specific database operation, it is my opinion that is it easier to organize the code and keep it clean when the approach is more fine grained. You can then map each request to a specific method on the backend and the code is very easy to follow. – Mike Feb 17 '16 at 15:10