Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Ok with empty list VS. No content

I wrote a web API that returns 204 (No Content) when a client requests all elements on a collection but the collection is empty.

For example: /api/products returns 204 when there are no products.

Now my problem is that I'm trying to consume the API using Restangular like this:

Restangular.all('products').getList().then(function (products) {
    $scope.products = products;
});

However this results in the following javascript error.

Error: Response for getList SHOULD be an array and not an object or something else

What gives? I can't find any information on handling no content in the Restangular doc

Am I using 204 wrong? Should I instead return 200 with an empty list?

like image 958
Snæbjørn Avatar asked Mar 17 '14 16:03

Snæbjørn


People also ask

Is it really better to return an empty list instead of null?

Always. It is considered a best practice to NEVER return null when returning a collection or enumerable. ALWAYS return an empty enumerable/collection.

What is the proper REST response code for a valid request but an empty data?

The answer, therefore, to your question is use 404 in your case. 204 is a specialized reponse code that you shouldn't often return to a browser in response to a GET .

How do you return a null list in Java?

The emptyList() method of Java Collections returns the list with no elements. This method is immutable. That is, we can not do any modifications after creating this method.


1 Answers

The 204 is apparently being treated as "no list" or null, rather than as an empty list. I'd say that's a reasonable behaviour. You're probably going to need to either check for a 204 and special-case it or change the API to return 200 OK with no elements. I would urge you to do the latter. I'm not sure that you're using 204 the way it's intended.

From RFC 2616,

The server has fulfilled the request but does not need to return an entity-body

In your case, the server does need to return an entity-body, it just happens that the entity is an empty collection. Typically 204 is used for POSTs or DELETEs.

like image 193
Eric Stein Avatar answered Dec 29 '22 01:12

Eric Stein