In RESTful web services, should the response DTOs contain their child DTOs?

Consider a user (/ users / {id}) who has a name and multiple locations (/ users / {id} / location).

When I ask the user (/ user / {id}), should this user be fully represented - his identifier, name and locations - or should the locations be returned only by a separate request? For example, what JSON DTO do you expect from a request for a 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 it more subjective, pushing and pulling between the size of the DTO and the queries required in a typical use case? I tend to just include all the relevant data (1), but I'm not sure if this is better than just requiring developers to make a few calls to the API to get all the data they need.

+6
source share
3 answers

To be RESTful, you do not have to return the full view of the resource. However, you want to enable hypermedia as a means to get / set all the information your API user needs (Hypermedia as an application state mechanism - aka HATEOAS )

To make sure you can use the @bowmanb clause to put URIs for all locations or add separate URIs for each location. You probably want to add additional URIs for other options to do something with the resource.

There's a nice article on HATEOAS by Jim Webber, Savas Parastatides and Ian Robinson entitled "How to get a cup of coffee"

+3
source

I am new to this world, but I create a calm api and face the same problem. My initial job was to include everything, so my results look like your option (1). In fact, I went a little further and included a URI with each object, so that, theoretically, the response could be controlled by a fairly intelligent client.

Having said that, I found that one specific attribute of my equivalent to your "user" object is huge. This does not seem to affect performance, but it seems to me that no client will want to receive all the information about this particular attribute - most clients just need an identifier and a name. So, I will modify my default approach for this attribute.

The bottom line - in my opinion, is that the decision depends on the expected use of your customers - what would the customer like to see?

+2
source

There must be some way for the client to determine how to find the user's location. Therefore, I would exclude the number 4.

If you are concerned about the size of your response, I believe that RESTful will only include URIs in user locations:

{ "id":123, "name":"Peter", "locations":"/users/123/locations" } 
+1
source

Source: https://habr.com/ru/post/914667/


All Articles