Rest – What’s the best way to return an array as a response in a RESTful API

jsonrest

Assume we have resources like this,

book:
    type: object
    properties:
        author: {type: string}
        isbn: {type: string}
        title: {type: string}

books:
    type: array
    items: book

So, when someone makes a GET on the books resource, we would be returning the following

[{"author": "Dan Brown", "isbn": "123456", "title": "Digital Fortress"},
 {"author": "JK Rowling", "isbn": "234567", "title": "Harry Potter and the Chamber of Secrets"}]

I heard from someone at work that the recommended REST practice is to always return responses as JSON objects, which would mean that our schema for books would look like this,

books:
    type: object
    properties:
        list:
            type: array
            items: book

So, now, response would look like this,

{
    "list": [{"author": "Dan Brown", "isbn": "123456", "title": "Digital Fortress"},
             {"author": "JK Rowling", "isbn": "234567", "title": "Harry Potter and the Chamber of Secrets"}]
}

Which of these is the best REST practice?

Best Answer

In practice the second option is the best practice. Reason for this is that you cannot extend the resource at all when you just return an array.

For example: If you need to add a count of all records you are already done with the array only approach.

If that happens in one list api then you want to keep it consistent so make all an object then your api becomes more consistent and easier to use for developers.

For example: Let's say a developer writes generic code to use your api to show list and detail pages. He does not want to build an exception because sometimes it's an array and sometimes it's an object with a list property.

This answer in total has nothing todo with principles about rest, hateoas and other protocols but just being real about the data you need to send to the client. If you decide to follow for example hateos then off course stick to their standards (which is also objects btw).