REST API – Understanding Different Response Types

rest

Let's say I've got a REST endpoint which is returning a list of people from some location, which can be referenced by address.

GET /people?address=London

A response could be:

[{
   "name":"Jane",
   "age":72
},{
   "name":"John",
   "age": "23"
},
....

But let's say there are people from London UK, but there are also matches from other places (like London, Arkansas, US).

Is it OK, that for this case I return a completely different response?

[{
   "address":"London, UK",
   "count":31
},{
   "address":"London, AK, US",
   "age": "12"
}
....

Is this a good practice? Or maybe in the second case I should set a different status code?

Best Answer

Having these completely different kinds of responses for what is essentially the same resource will make it extremely hard for the recipients of the response to do something useful with it.

A better approach would be to essentially merge the two responses:

[{
  "address":"London, UK",
  "count":31,
  "people":[{
    "name":"Jane",
    "age":72
  },{
   "name":"John",
   "age": "23"
  },
  ....
  ]
},{
 "address":"London, AK, US",
 "count": "12",
 "people": [
   ...
 ]
}
....      

If you now have just one city matching, you could return an array with a single element and still keep the same structure.