Rohan
Rohan

Reputation: 13811

What is the better practice to respond with JSON from a web service?

I am new to web development and I trying to build RESTful web services where the web service communicated is JSON.

Now what I would like to know is that which the better way to respond with JSON?

Way 1

{
    "status": "success",
    "messages": {},
    "data": {
         "Some Data": "About Something",
         "Some Other Data": "About Something Else"
    }
}

Way 2

[
    "Some Data": "About Something",
    "Some Other Data": "About Something Else"
]

Upvotes: 0

Views: 25

Answers (1)

Matthew Franglen
Matthew Franglen

Reputation: 4532

If you annotate the response like the first version then you send more data, but you open the door to things such as pagination. You will want to paginate the data if the client only needs a small amount of it at a time and it would be overly onerous to generate the entire data set.

If you provide the raw response like the second version then you send less data, but you are less able to support things like pagination. You could force them in there, but the client would have to know things about the server which results in increased coupling between them.

So really both approaches are valid for different circumstances. As it happens REST libraries such as the django rest framework provide support for both kinds of response. This clearly shows that either one can work, and it is really up to you which suits your circumstance better.

I would add that you can indicate the success status of the request using a HTTP Response Code rather than an explicit message.

Upvotes: 1

Related Questions