REST – Should ‘No Results’ Be an Error in RESTful Response?

http-responserest

I'll describe an example:
I start making an API for a baking shop. The API will allow people to search their catalogus for baking products, such as home-made minty chocolate chip cookies using api.examplebakery.com/search?q=......

Someone uses this to look for a product named pineapple-banana flavoured cookies and will obviously not find any results.

Should this be returned as an error? The search did not fail, the API searched and successfully concluded no cookies could be found. The API should not return 404, because the API was indeed found.

Best Answer

When there are results, the output is a (JSON, based on your comment) list. For queries with no results, the output should be exactly the same. The list simply has 0 items in it.

So if your response is normally this:

{
    "results": [
        {
            "name": "Pancakes",
            ....
        },
        {
            "name": "French Fries",
            ....
        }
    ]
}

Then for a query with 0 results, it should be this:

{
    "results": []
}

If you also include meta data about how many "pages" of results there are, links to those "pages", etc. then I would suggest saying there is 1 "page".

The HTTP status should be the same as when there are results - 200 OK.

204 No Content may also seem to be an option, but it is not because you are in fact returning "content" - the empty list. If you feel an empty list does not count as "content", what if you then amend the response to offer spelling suggestions? The core of the response will still be an empty list, but now there is even more "content".

For more useful information about HTTP status codes, jpmc26 has an answer worth reading.

Related Topic