RESTful API routes design: nested vs. non-nested
<p>My question is about the advantages of nesting resources when building URLs for API purposes. Consider the following two alternatives for accessing an employee resource:</p>

<pre><code>/api/employees?department=1   # flat

Vs.

/api/departments/1/employees  # nested
</code></pre>

<p>Now consider the task of developing a general purpose library to access REST resources from an API. If all routes were flat, such a REST wrapper library would only need to know the name of the resource being accessed:</p>

<pre><code>store.query('employees', {department_id:1})   =&gt;   /api/employees?department=1
</code></pre>

<p>However, if we were to support nested routes, this wrapper would need to know extra information about what models are nested and under which other resource, in order to know how to build the URLs for referencing such a model. Given that not all models would be nested under the same parent resource, and even some models would not be nested at all, the REST wrapper library would need to have some sort of configuration describing all this extra knowledge that wouldn't be needed otherwise.</p>

<p>So my questions are:</p>

<ul>
<li><p>Are there any real advantages to nested resource routes in an API? (Which is not meant to be consumed by end users, and therefore gains less from having prettier URLs).</p></li>
<li><p>Is the nested approach really better than flat, beyond aesthetics, so as to justify the extra effort and complexity introduced to support the lack of uniformity in resource URL building?</p></li>
</ul>

<p>See also: <a href="https://stackoverflow.com/a/36410780/621809">https://stackoverflow.com/a/36410780/621809</a></p>

<p><strong>UPDATE: IMPORTANT CLARIFICATION</strong></p>

<p>I realize from some of the comments and answers, that I wasn't clear enough regarding one aspect: I'm not against addressing single resources with URLs like <code>/employees/5</code> or <code>/departments/1</code>. I don't consider that to be nested.</p>

<p>When I say nested resources, I refer to URLs like <code>/departments/1/employees</code> where a resource is addressed always within the context of another resource. The main issue is the fact that <strong>for URL building, a generic library would need to know extra stuff</strong> like "employees are nested under departments" but "branches are not nested under anything". If all resources could be addressed RESTfully, but in a flat fashion, it is simpler and more predictable to know how to address them.</p>

<p>When you think about it, in databases you don't need to know extra information in order to know how to address a collection of objects (e.g. a table in a RDMS). You always refer to the collection of employees as <code>employees</code>, not as <code>departments/5/employees</code>.</p>