RESTful API - Designing sub-resources
The design approach raises a few questions you need to consider when choosing between the two:
Existence dependency
In A, it's very intuitive, that when you DELETE a company, you also deleting all it's sub resources - departments and employees. In B, the API user needs to think a moment about such action - do I need to invoke delete on all employees, or is it enough to delete the company? of course, this can be documented, but still, it's not straight-forward.
A have an advantage here, becuase it's very clear - when deleting a resouce, you delete all it's sub resources.
Operation endpoint
Another question it raises - how do I update an entity? from which end-point?
If I want to delete an employee, is it enough to update the company with a new set of employees? or must I DELETE the employee?
Or say I want to change employee from one company to another. In B, theoretically I can update employee with company field, and be done with it. In A there's no such way...
A have an advantage where it's very straight-forward how to do an action - CRUD on the entity URL. B makes the API user stop and wonder which action he can do on which URL.
But at the same time, B have an advantage that changing the "parenting" of an entity is easier (in cases where it's relevant).
Validation
In A, you must validate the URL arguments match, as user can provide employee id with the wrong company or department. In B there's no such problem.
Both approaches can be considered RESTful, provided you do not break the REST constraints defined in the chapter 5 of Roy Thomas Fielding's dissertation:
- Client-server
- Stateless
- Cache
- Uniform interface
- Layered system
- Code-on-demand
I cannot see major pitfalls in both approaches, but I would prefer the Approach B over the Approach A: the URLs are shorter, easier to remember and not many parameters are required.
Bonus points: Spotify and Facebook APIs follow this approach. For sure there are other APIs, but these are the ones that came up to my mind.