假设我们有以下REST调用:
GET api/companies/5
(获取ID为5的公司)
如果公司'5'不存在,我们通常会返回404 Not Found
响应。
但是现在,让我们接听此电话:
GET api/companies/5/invoices/10
(从公司5获取发票10)
现在,如果公司'5'不存在,我们是否仍返回404 Not Found
?或仅在找不到最外面的资源时才返回404(在这种情况下,发票10)。
Bad Request
也许是更好的选择吗?
404是您最好的选择。根据HTTP RFC http://www.ietf.org/rfc/rfc2616.txt,400错误请求表示:
由于语法格式错误,服务器无法理解该请求。
而404状态:
服务器未找到与请求URI匹配的任何内容。
整个URI是您的资源标识符,并且您没有找到该特定标识符的匹配资源。
404可能会造成混乱-资源丢失还是实际的URL不正确?
我个人会使用422
代码:
The 422 (Unprocessable Entity) status code means the server
understands the content type of the request entity (hence a
415(Unsupported Media Type) status code is inappropriate), and the
syntax of the request entity is correct (thus a 400 (Bad Request)
status code is inappropriate) but was unable to process the contained
instructions. For example, this error condition may occur if an XML
request body contains well-formed (i.e., syntactically correct), but
semantically erroneous, XML instructions.