Should the user id be in the URI when getting data?

Viewed 140

I am creating an api and the client can make a GET request to get all the user documents. I'm unsure if I should have the user id in the URI or not. I will not be needing the id in the url, because I have issued a jwt token that already contains the user id. So which one is "better" according to the restful design principles?

GET /documents

or

GET /users/{id}/documents

Should shared documents also have an URI like GET /documents/shared or would one of the above still be ok to use?

1 Answers

Everything needed to identify a resource should be included in the resource identifier.

The motivation here is simple - general purpose components are going to assume that the target URI is the identifier of the resource, because that's what the spec says. The fact that everybody uses messages with the same semantics means that general purpose components can do useful things.

Two cases where this sort of thing matters:

If the URI identifies the resource, then I can paste that identifier into an answer in stack overflow, and when you click on the link you get exactly the resource that I intend, not some completely different thing because your JWT token doesn't copy mine.

If the URI identifies the resource, then we can use general purpose caches that know how re-use HTTP responses, and know to automatically invalidate previously cached responses with the same identifier when that is appropriate.

Related