For a REST API that I am working on, I want to return JSON in a consistent layout:
{
"Data" : {
"Id" : 123,
"Email" : "[email protected]"
"Firstname" : "Charlie",
"Surname" : "Brown",
},
"Error" : null
}
The payload will always contain "Data" and "Error", where one or the other can be null.
My question relates to "Data" and endpoints which only ever really return one object. For example, let's say I have an API users/current
, which returns the currently authenticatedd user. I would have returned that user as shown above; a single JSON object named "Data".
For endpoints that could return zero, one or more objects, then I would (of course) make "Data" be an array:
{
"Data" : [
{
(first object)
},
{
(second object)
}
],
"Error" : null
}
I've heard a point of view that, for consistency, "Data" should always be an array. Even when an endpoint would logically only ever return a single object (or null).
What do others think? I think that there's no need to make "Data" and array if there'll never be more than one object returned.