Should returning top-level arrays in API responses be a no-no? #58
Replies: 4 comments 1 reply
-
I should add - I think adopting this pattern only affects endpoints that return collections of resources, not singletons. I don't see a problem with |
Beta Was this translation helpful? Give feedback.
-
Nesting the array inside a key named for the object its returning. seems like a good pattern from a meta-data perspective. The security implications seem to have faded. But, being able to extend the endpoints with additional meta-data is a strong reason on its own. |
Beta Was this translation helpful? Give feedback.
-
Getting into the specifics:
** Edited to remove path parameter from returned object |
Beta Was this translation helpful? Give feedback.
-
@TangoYankee I wanted capture a possible anti-pattern we've been implementing and get your thoughts on it. I've seen some best practices for designing API responses recommend always return a top-level object and never an array as the response body. We have several endpoints that return "collections" such as
/zoning-districts/{uuid}/classes
that return top-level arrays. I'll try explain some reasons why this isn't a great precedent, as I understand it:/api/tax-lots
endpoint, but if we did, I'd imagine the response would look something likeGiven that context, one could make the argument that even endpoints that don't need pagination should follow this pattern for the sake of consistency
taxLots
in my example above). I think there are two approaches here. The first (and the one I would prefer) is that you use a pluralized, camelcased property name describing what it is a list of, hencetaxLots
. One thing I like about this approach is that it gives you a nice property to destructure out of the response object in the code gen'd client code, instead of the developer having to rename thedata
property, which can lead to inconsistency and clunky variable names. Instead of this code:If the API returns an object with a
landUses
property, you can doThe second approach is that you adopt a convention to always name the property the same thing, regardless of the resource the endpoint is referencing. I mostly see
data
used for this. I find this approach to be clunky, especially when you get around to making calls on the frontend because many frontend HTTP client libraries return objects that wrap the entire HTTP response in an object that has thebody
under an object calleddata
. So, if our/land-uses
endpoint returned an object like this:and you called that endpoint with Axios, for example, you end up with code like this:
Conclusion
Thoughts on adopting this pattern now? It would be pretty trivial to make the changes, not that we would have to undertake it right away necessarily. If we did, my recommendation would be for the first approach described above.
Beta Was this translation helpful? Give feedback.
All reactions