开发者

API Development: When to return a BAD REQUEST HTTP Status Code (REST)

We're authoring REST services, and there's a debate on what to do when someone requests a resource with a parent ID that does not exist.

Example: You are asking for a list of people associated with a company, so you GET with ID 1, but that company ID does not exist.

I would argue that the definition of REST says that we would simple return a empty list (resulting in a HTTP 204 (No Content)), since a HTTP Bad Request is for only malformed syntax, per the specification:

http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

I think it's also clearer that there was no error to be interpreted, the resource you are requesting does not exist.

Thoughts on best practice?

There is a SO discussion here: HTTP 400 (bad request) for logical error, not malformed request syntax although it's a 开发者_C百科bit more abstract, I'm torn if I should post this, or simply use that question.


If you do

GET /company/1

and there does not exist a company with id 1 then I think the appropriate HTTP status code is 404 - not found.

However, if you were to do,

GET /companies?id=1

Then I would return a 200 and an empty list of companies.


204 is not an error code, it is a success code, but that's a quibble. I don't often see it for empty lists, but rather success responses that simply have no meaningful content to respond with, such as a successful DELETE. For example, if you are returning JSON, a 200 with content of [] is what I would expect of an empty list of results. However, I don't think it is incorrect to use it in your case.

404 Not Found is a more common error for the case you describe. You are correct that it is not a syntax error, so 400 is not appropriate, but in fact, the resource is not there. 404 Not Found is an accurate response.

But in choosing between 200, 204 and 404, the correct answer is: it depends. The question is whether it is an error or not. 404 is more expressive (the client can tell that there is no such company) but you can trade expressiveness for security, meaning that it might be a good thing that a client can't tell whether the company with that id exists or not.


What about caching? only 200 will get cached, both 204 and 404 won't get cached. If this is important 200 with empty list seems ok. Not sure what about empty single elements?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜