Consider a user (/users/{id}) which has a name and multiple locations (/users/{id}/locations).
When I request a user (/user/{id}), should that user be represented fully--its id, name and locations--or should locations only be returned on a separate request? For example, which JSON DTO would you expect on a request for user with id=123 (/users/123):
1) { "id":123, "name":"Peter", "locations":[{"id":1, "name":"Chicago"}, {"id":2, "name":"New York"}] }
2) { "id":123, "name":"Peter", "locations":[{"id":1}, {"id":2}] }
3) { "id":123, "name":"Peter", "locations":[1, 2] }
4) { "id":123, "name":"Peter" }
Is this more subjective, pushing and pulling between size of the DTOs and requests required in the typical use-case? I'm inclined to simply include all of the relevant data (1), but I'm not certain that's better than just requiring developers to make multiple calls to an API to get all of the data they actually want.
To be RESTful you don't necessarily have to return the full representation of the resource You do however want to enable hypermedia as means to get/set all the information the user of your API needs (Hypermedia as the engine of application state - a.k.a. HATEOAS)
To satisfy that you can either use the suggestion by @bowmanb to put a URI for all the locations or add individual URIs for each of the locations. You probably want to add additional URIs for other options of doing something with the resource.
There's a good article on HATEOAS by Jim Webber, Savas Parastatidis & Ian Robinson called "how to GET a cup of coffee"
I am a newbie in this world, but I am building a restful api and facing exactly the same issue. My initial work has been toward including everything - so my results look like your option (1). In fact, I go a little further and included a URI with each object so that, in theory, the response can be navigated by a sufficiently intelligent client.
Having said that, I have found that one particular attribute of my equivalent to your "user" object is enormous. It doesn't seem to impact performance, but it seems to me that no client would want all that information about that particular attribute - most clients would just want the id and name. So, I will be modifying my default approach for that attribute.
Bottom line - in my newbie opinion - is that the decision is driven by the expected usage of your clients - what would the client want to see?
There should be some way for a client to determine how to find a user's locations. So I would rule out number 4.
If you are concerned about the size of your response, I believe it would still be RESTful to include just the URI to a user's locations:
{ "id":123, "name":"Peter", "locations":"/users/123/locations" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With