tags:

views:

37

answers:

3

I am developing a RESTful API. One of the URLs allows the caller to request the record for a specific person by id.

What is the conventional value to return of the record for that id does not exist? Should the server send back an empty object or maybe a 404, or something else?

Thanks.

+1  A: 

404, or perhaps 410 (Gone) if it was there before (but 404 isn't wrong in this case either).

As always with REST, it's also preferable to send a representation with it (even with a 4xx code) to tell the client that the resource does not exist and tell it what possible actions it can take from there.

Bruno
+2  A: 

Generally I return a 404 error from my RESTful API in these cases, based off of the convention used by CodeIgniter Rest Server.

This works out fine for the most part, and is the most "correct" and "pure" solution. However the 404 error can make it a bit harder to handle those "missing" cases on the client because you may need a separate error handler instead of just doing nothing because you got back an empty object.

I would recommend weighing the pro's and con's of both approaches and implementing the approach that makes the most sense for you.

Justin Ethier
@Justin: How does the client distinguish between a URL path that does not exist and a record that does not exist?
Ralph
There is no distinction since neither exists. However, I quite like @Bruno's suggestion of sending a representation with the 404 code - this could be used to make such a distinction.
Justin Ethier
A: 

In addition to considering 404, I would consider the possibility of returning some representation of "empty": Consider a Google search for the word klinjeraliknoplidocus. At the time of this writing, it returns 200 OK with "no matches" and suggestions no how to move forward. It does not return 404, since the URI http://www.google.com/search?q=klinjeraliknoplidocus actually identifies something, namely "All documents known to Google that are related to the term klinjeraliknoplidocus". Pretty soon, this page will show up there.

So:

  • if you define your lookup feature as returning zero or more items with this ID then 200 and an empty response makes sense.
  • if you define your lookup feature as returning exactly one item, then 404 (or 410) makes sense.
mogsie
How about 400 (Bad Request)? That way I can distinguish between a mis-typed URL (400) and an id that does not exist.
Ralph
I think Bad Request ought to be reserved for syntactical errors. A URI identifying garbage isn't syntactically incorrect. A header which is malformed (e.g. `If-None-Match: abc` missing quotes around the ETag) is malformed; an XML document with syntax errors in a PUT or POST is syntactically incorrect, both could cause 400s. Doing a GET for /customers?q=12345 or /customer/id/12345 is in itself not syntactically incorrect. 200 or 404 should be used if the customer ID doesn't exist depending on the nature of the definition of the resource.
mogsie