Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API Best Practice for Deep Object Routes

When designing a RESTful API with ASP.NET Web API, I can create several routes to retrieve the same data. But should I? Is it considered helpful or confusing?

For example, if I have an object relationship of Parent > Child > Item, I could potentially have three routes return the same individual item:

  • api/parents/:parent/children/:child/items/:item
  • api/children/:child/items/:item
  • api/items/:item

Is it useful to provide all three routes, or should it be limited to the simplest route to avoid confusion? Is there a best practice in this regard?

like image 803
Andy Avatar asked Sep 23 '15 15:09

Andy


People also ask

What is the recommended term used to refer to multiple resources in API?

In this case, we refer to these resources as singleton resources. Collections are themselves resources as well. Collections can exist globally, at the top level of an API, but can also be contained inside a single resource. In the latter case, we refer to these collections as sub-collections.

What would you say are the most important best practices when it comes to build design Web APIs?

The most important takeaways for designing high-quality REST APIs is to have consistency by following web standards and conventions. JSON, SSL/TLS, and HTTP status codes are all standard building blocks of the modern web. Performance is also an important consideration.


1 Answers

Choosing which URIs/routes to use is a matter of the desired purpose, not content. Is it possible or propable that a user would look for a child without having a specific parent in mind? If yes, offer the data in a seperate root URI, if not, restrict access to the child data by requiring the user to provide a parentId.

The URI api/children would return all children regardless of their parents and therefore fulfills another purpose than api/parents/:parentId/children which would only return the children the :parentId instance actually has a reference to. The result will always contain data that can also be obtained using api/children, but it carries additional information because these children 'belong' to the specified parent.

In my opinion all of your options are valid because they all have different purposes. However I would avoid using different URIs for the same purpose.

like image 160
maxmantz Avatar answered Sep 28 '22 06:09

maxmantz