Pure.Krome
Pure.Krome

Reputation: 87007

Should this Json result return a 404 or 200?

I'm trying to make an API sorta loosly based on StackExchange's api results.

So here's my json output.

{
    "items" : [ ... objects in here .... ]
    "page" : 
    "page_size" :  
    "total_pages" : 
    "total_items_count" :  
    "maximum_quota" : 
    "remaining_quota" : 
}

pretty damn simple.

Now, I'm not sure what do to if the person tries to request a .. um .. product or question or whatever, and the item doesn't exist.

eg..

{
    "items": []
    ... snipped ....
}

I was thinking I would return a 200 AND the Json above, with the Items property being empty.

The other idea I had was returning that json with the items property empty BUT setting the response http status to 404.

Thoughts / standards ?

I really want to return the json no matter what. Why? the quota's. Even an empty result is still a legit hit to the api service.

Upvotes: 5

Views: 1761

Answers (2)

realbart
realbart

Reputation: 3994

The correct response is 200. You're asking for a collection of items. The collection exists.

If you ask me for a euro and my wallet is empty, you'd get a 404. If you ask me for wallet with all my money, you'd get a 200, even if my wallet is empty. 404 would imply I don't have a wallet.

If you ask me for the name of my oldest child you'd get a 404. If you ask me for the names all of my children, you'd get a 200, regardless of how many children I have. 404 would imply children don't exist. Returning

So 200 for an empty collection is perfectly fine.

Note: In some cases 400 might be reasonable too. 204 is just plain wrong. This is if you don't need to return any information, e.g. after a POST or a DELETE. You must not return a body with 204.

Upvotes: 0

Phill
Phill

Reputation: 18804

In my opinion I would return a 400 & 204 status:

http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

400 Bad Request

The request cannot be fulfilled due to bad syntax.[2]

If you pass an invalid argument, a 400 status is returned saying the request is bad.

In this scenario, I wouldn't return any JSON message back. It's invalid, sort it out. The StatusMessage can say 'Invalid Argument', but no content.


204 No Content

The server successfully processed the request, but is not returning any content.[2]

If you pass valid arguments, but the content wasn't found, you can say it wasn't found.

You may* want to pass some additional info back, may not.

For Twitter, say you wanted to search for '@JohnDoe' user, and it wasn't found. You could say 204, with: "Sorry we couldn't find @JohnDoe, but we did find these 3 similar people that may be what you want" in which case you wouldn't push down their details, just the Twitter names.

However if you were searching for a tweet, and it wasn't found, there's no reason to send any additional info to the client. Just say it wasn't found, end of story.

Upvotes: 2

Related Questions