API Best Practices – Returning JSONObject or JSONArray

apijavajson

I'm making an API that will return data in JSON.

I also wanted on client side to make an utility class to call this API.

Something like :

JSONObject sendGetRequest(Url url);
JSONObject sendPostRequest(Url url, HashMap postData);

However sometimes the API send back array of object [{id:1},{id:2}]

I now got four choices ():

  • Make the method test for JSONArray or JSONObject and send back an Object that I will have to cast in the caller
  • Make a method that returns JSONObject and one for JSONArray (like sendGetRequestAndReturnAsJSONArray)
  • Make the server always send Arrays even for one element
  • Make the server always send Objects wrapping my Array

I going for the two last methods since I think it would be a good thing to force the API to send consistent type of data.

But what would be the best practice (if one exist).

Always send arrays? or always send objects?

Best Answer

That should depend on what it is actually doing. If it is retrieving one or more objects, it makes logical sense to always return an array containing the results, even if it is an array with only one element. This makes it easy to then do a foreach on the returned array, for example.

If the format of the request causes it to return completely different kinds of data though, it would be clearer to have a different method for each context.

How this would work as a method is a good analogy. If you have some collection foo, and a function searchFoo that searches the collection for elements, you are not going to write it such that it returns an element if only one element matches, and otherwise it returns a list of elements. Either it always only finds one elements (like if the search is based on a unique key) in which case it also returns an object of the appropriate type, or it will find a variable number of elements in which case it will always return a list, regardless of how many elements were found.

Related Topic