sheg
sheg

Reputation: 132

Is it normal for http responses to return inconsistent json

I am working with an endpoint thats returning fields which sometimes return a json object, and sometimes an empty array. For example,

response 1:

{
   "status": true,
   "people": {
      "id":"123",
      "name":"john"
   }        
}

response 2:

{
   "status": true,
   "people": []
}

Notice that "people" is set to an empty [] when there's nothing, and a singular object when something exists.

I have seen this come up a few times in random places, and it seems a bit cavalier to me as the inconsistency make the values seem ambiguous. I was wondering if anyone knew if this is considered to be bad practice, and why. Would you consider it a bug on their end? Can anyone help shed some light on this please?

Thanks!

Upvotes: 0

Views: 580

Answers (2)

George
George

Reputation: 2594

Some client technologies will want to deserialize this JSON into an object of some class. Trying to accommodate the two JSON snippets you posted will be difficult for some clients (at least in a statically typed language). A RESTful webservice implementation should not assume that a client will use a particular stack or even the same language as the service. For this reason, if I was designing this endpoint, I would try to avoid returning this inconsistent result.

Of course, as the other answer pointed out, it is a matter of convention and will work. I just think it will make things unnecessarily complicated for some clients trying to work with your service.

Upvotes: 1

Robert Moskal
Robert Moskal

Reputation: 22553

Depends, there are a number of stacks that will return a single {} object if there is one result for people and an array of people [person, person] if there are more than one. I personally would prefer an array containing one entity.

If you are saying that people are never more than one (the name implies many) then I'd definitely say the api was inconsistent in returning an array when there are no results and an object literal otherwise.

As to what should happen if there are none? It's a matter of convention and an empty array is no stranger than any thing else, though it could be a null, or something else.

Again, it's a matter of convention. If you have some say in the construction of the api you are calling, you can express a preference. Otherwise you just have to adapt to what comes back.

Upvotes: 1

Related Questions