Alex Rivera | Logout

RESTful design: when to use sub-resources?

Asked 2012-11-21T07:57:46.310
70

When designing resource hierarchies, when should one use sub-resources?

I used to believe that when a resource could not exist without another, it should be represented as its sub-resource. I recently ran across this counter-example:

  • An employee is uniquely identifiable across all companies.
  • An employee's access control and life-cycle depend on the company.

I modeled this as: /companies/{companyName}/employee/{employeeId}

Notice, I don't need to look up the company in order to locate the employee, so should I? If I do, I'm paying a price to look up information I don't need. If I don't, this URL mistakenly returns HTTP 200:

/companies/{nonExistingName}/employee/{existingId}

  1. How should I represent the fact that a resource to belongs to another?
  2. How should I represent the fact that a resource cannot be identified without another?
  3. What relationships are sub-resources meant and not meant to model?
Edit
Report

1 Answer

19

This is problematic because it's no longer obvious that a user belongs to a particular company.

Sometimes this may highlight a problem with your domain model. Why does a user belong to a company? If I change companies, am I whole new person? What if I work for two companies? Am I two different people?

If the answer is yes, then why not take some company-unique identifier to access a user?

e.g. username:

company/foo/user/bar

(where bar is my username that is unique within that specific company namespace)

If the answer is no, then why am I not a user (person) by myself, and the company/users collection merely points to me: <link rel="user" uri="/user/1" /> (note: employee seems to be more appropriate)

Now outside of your specific example, I think that resource-subresource relationships are more appropriate when it comes to use rather than ownership (and that's why you're struggling with the redundancy of identifying a company for a user that implicitly identifies a company).

What I mean by this is that users is actually a sub-resource of a company resource, because the use is to define the relationship between a company and its employees - another way of saying that is: you have to define a company before you can start hiring employees. Likewise, a user (person) has to be defined (born) before you can recruit them.

answered 2012-11-21T18:29:33.710

Your Answer