Recently, I have seen several articles talking about RESTful API design. Of course this is also a common topic of discussion for the engineers at Teem. I want to use (and write) APIs that are easy to understand and explain and the fastest way to complicate your API is nested routes. Just don’t do it! Do not create nested routes in your API. Let’s keep our APIs simple and create one endpoint per resource and if filters are needs, use GET parameters. This is simpler to document and simpler to maintain and ultimately, easier to use.
In a RESTful API urls identify resources and identifiers should change
as infrequently as possible [Fielding pg. 110]. The natural
consequence is that urls should contain the minimal information needed
to access a resource. For example, in an API with Users and Companies,
/users/:userId is better than
If your user changes companies, then the identifier must change. This is also
more complicated than it needs to be. The user’s
id should be enough to
access it from the database.
Some people will argue that you solve the above problem by implementing both endpoints. However, if you pair this with the Unix philosophy “Do One Thing and Do It Well”, then you simply shouldn’t use nested routes. It is simpler to understand an API that has only one way to access any given resource. Additionally, any request that you can do with nested routes you can do with a non-nested route and query parameters. This also reduces the complexity of managing and testing endpoints because there is only one code path that users/developers can use. Basically, the non-nested endpoint is works it works well, so why create another endpoint to clutter up the API?
At the end of the day, APIs without nested routes are easier to build, easier to maintain, and easier to consume. This leads to happy devs and ultimately happy users.
Thank you to Tom Ducat-White for the CC BY-NC-ND image I used as the cover on this post.