404未找到或错误的请求?

问题描述 投票:22回答:2

假设我们有以下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也许是更好的选择吗?

rest asp.net-web-api http-status-code-404 asp.net-web-api2 api-design
2个回答
28
投票

404是您最好的选择。根据HTTP RFC http://www.ietf.org/rfc/rfc2616.txt,400错误请求表示:

由于语法格式错误,服务器无法理解该请求。

而404状态:

服务器未找到与请求URI匹配的任何内容。

整个URI是您的资源标识符,并且您没有找到该特定标识符的匹配资源。


0
投票

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.
© www.soinside.com 2019 - 2024. All rights reserved.