Rest – Always return single objects in an array for REST API JSON payloads

apijsonrest

For a REST API that I am working on, I want to return JSON in a consistent layout:

{
  "Data" : {
     "Id" : 123,
     "Email" : "charlie@somewhere.com"
     "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.

Best Answer

I think this type of consistency is misguided.

Wrapping the data in an array is unlikely to benefit an API consumer, because he would still have to know how to interpret the actual data. As an example, it is just not likely that the "data" results of /users/current and /cities/chicago/restaurants are going to be handled by the same code.

For errors, on the other hand, it is likely that all errors are processed by the same error handling code, and then there is a benefit to use the same structure.

Ask yourself this: if this was a class in your favorite OOP language, would you make all methods return the same type for consistency?