When to use sub-resources in RESTful design?

When to use sub-resources in RESTful design?

Your rule when a resource could not exist without another, it should be represented as its sub-resource is a good guidance for this decision. if a subresource is uniquely identifiable without its owning entity, it is no subresource and should have its own namespace (i.e. /users/ {user} rather than /companies/ {*}/users/ {user}).

How are representations returned in a REST API?

Multiple endpoints that return the same representations can also lead to problems with caching and can violate one of the core principles of RESTful API design. This problem can be solved via HTTP redirects, so all representations are returned from a central root resource and can be cached, but there is still code needed to implement this.

Why are multiple endpoints bad for REST API?

Multiple endpoints increase the effort for the API owner to document the whole thing and make onboarding for new customers much more troublesome. Multiple endpoints that return the same representations can also lead to problems with caching and can violate one of the core principles of RESTful API design.

Do you have to use nested resources in REST API?

While nesting is sometimes necessary and can’t be avoided, it is often a choice that comes with specific costs or dangers we should keep in mind. Let’s look at them one-by-one. We learned before that nesting resources could make our URLs more readable, but this isn’t a sure bet.

What are sub-resources meant and not meant to model?

What relationships are sub-resources meant and not meant to model? Sub resources are well suited for compositions but more generally spoken to model that a resource cannot exist without the parent resource and always belongs to one parent resource.

When to use users as a Sub-Resource?

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.

When to treat a resource as a Sub-Resource?

If a resource cannot exist without another, it should be represented as its sub-resource; however, treat the operation as a search engine query. Meaning, instead of carrying out the operation immediately, simply return HTTP 307 (“Temporary redirect”) pointing at the canonical URI.