Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top