Search code examples
jsonweb-servicesrestdtosaas

In RESTful Web Services, should Response DTOs contain their child DTOs?


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.


Solution

  • 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"