Wes Wes - 1 year ago 67
reST (reStructuredText) Question

What are best practices for REST nested resources

As far as I can tell each individual resource should have only one canonical path. So in the following example what would good URL patterns be?

Take for an example a rest representation of Companies. In this hypothetical example each company owns 0 or more departments and each department owns 0 or more employees.

A department can't exist without an associated company.

An employee can't exist without an associated department.

Now I'd find the natural representation of the resource patterns to be.

  • /companies
    A collection of companies - Accepts put for a new company. Get for the entire collection.

  • /companies/{companyId}
    An individual company. Accepts GET, PUT and DELETE

  • /companies/{companyId}/departments
    Accepts POST for a new item. (Creates a department within the company.)

  • /companies/{companyId}/departments/{departmentId}/

  • /companies/{companyId}/departments/{departmentId}/employees

  • /companies/{companyId}/departments/{departmentId}/employees/{empId}

Given the constraints in each of the sections I feel that this makes sense if a bit deeply nested.

However my difficulty comes if I want to list (
) all employees accross all companies.

The resource pattern for that would most closely map to
(The collection of all employees)

Does that mean that I should have
also because if so then there are two URI's to get the same resource?

Or maybe the entire schema should be flattened but that would mean that employees are a nested top level object.

At a basic level
returns the exact same view of employees as the most deeply nested pattern.

What's the best practice for URL patterns where resources are owned by other resources but should be query-able separately?

See my answer below to see what I've done.

Answer Source

What you have done is correct. In general there can be many URIs to the same resource - there are no rules that say you shouldn't do that.

And generally, you may need to access items directly or as a subset of something else - so your structure makes sense to me.

Just because employees are accessible under department:


Doesn't mean they can't be accessible under company too:


Which would return employees for that company. It depends on what is needed by your consuming client - that is what you should be designing for.

But I would hope that all URLs handlers use the same backing code to satisfy the requests so that you aren't duplicating code.