I would be interested to know if there are rules for how the data should be returned in an Api response. Should the data be returned in an object with the key data or should the object be returned directly? I would like to decide between these two response formats.
// version 1
{
"data": [
{"id":1,"name":"Mexico City"}
]
}
// or version 2
[
{"id":1,"name":"Mexico City"}
]
// or version 3
{
"cities": [
{"id":1,"name":"Mexico City"}
]
}
CodePudding user response:
All three versions are valid. There are no data structure constraints in REST beyond standard media types. You decide about it. I like the version 3 the best, because you are representing a collection resource which can have properties, not just elements. For example if you add hyperlinks to it, then a simple array is not enough.
CodePudding user response:
It depends on what the Client requested. If a Single City was requestes I'd suggest
{"id":1,"name":"Mexico City"}
If multiple Cities where requested, for example via a search string:
[
{"id":1,"name":"Mexico City"},
{"id":2,"name":"Munich"}
]
If the cities where requested among other types of data
"cities: [
{"id":1,"name":"Mexico City"},
{"id":2,"name":"Munich"}
],
"countries": [
...
]
These aren't really rules, it's just how most JSON-Serializers will format certain objects and it makes sense to do it this way, because it always provides exactly the information the client wanted. Nothing more, nothing less.