Rest – Does RESTful response always return a 404 and empty content when an array is expected but the result is empty

djangoresourcesrestruby-on-rails

I worked with Ruby on Rails and RESTful api before and now with Django Rest framework. For this question let's say we only consider the case of JSON but not XML. It seems that when we expect an array as a result, if the result is 1 or above, we can happily get back an array with the proper content, but if the result is 0, we don't get back an empty array — it actually will return a 404 HTTP status code with empty response content?

Is this always the case with RESTful resources, and is it true that if we don't define our API as REST or resource, then we can do whatever we want (and return an empty array)?

In a way, I think if it is math or functional programming, I would think that if a function returns a set or an array when the number of items is 1 or above, but give you back a null or raise an exception, instead of returning an empty set or empty array, I think it is a little strange behavior. And in the case of recursion, such behavior usually doesn't work, so I wonder if a behavior that is more "mathematically correct" may be a better behavior. But this question is about RESTful… whether its definition is that it should be 404 with empty response content but cannot be otherwise.

Best Answer

You're right, the behavior is indeed strange. A null and an empty array are, semantically, two different things.

  • An empty array indicates exactly that: the array exists but contains no elements right now, given the query parameters.

  • An HTTP 404 indicates, on the other hand, that there is no array; for some reason, it makes no sense to have an array there.

Imagine a Flickr-type application with users, photos and comments. Imagine that only paid users can upload photos, but all users can comment. If the user 123 doesn't have a paid subscription and haven't posted any comments yet:

  • The query /user/123/comments would give an empty array, but:

  • The query /user/123/photos may result in HTTP 404 to indicate that the user is not expected to have any photos.

    Another possibility is to return an empty array, which is semantically correct. You'll lose the “this user doesn't have to have any photos” aspect, but it might not matter too much: if the client needs to know whether user 123 can have photos, the query similar to /account/123/status could be used to return values such as paid or free.