I am developing a RESTful API. One of the URLs al开发者_Python百科lows 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.
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.
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.
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.
精彩评论