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?
Always. It is considered a best practice to NEVER return null when returning a collection or enumerable. ALWAYS return an empty enumerable/collection.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With