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:
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}
A year later, I ended with the following compromise (for database rows that contain a unique identifier):
/companies/{id}
and /employees/{id}
).HTTP 307 ("Temporary redirect")
pointing at the canonical URI. This will cause clients to repeat the operation against the canonical URI./companies
but not /employees
.This approach has the following benefits:
/companies/{companyId}/employees/{employeeId}/computers/{computerId}
.