404 Not Found or Bad Request?

Dav*_*New 21 rest api-design http-status-code-404 asp.net-web-api asp.net-web-api2

假设我们有以下REST调用:

GET api/companies/5 
Run Code Online (Sandbox Code Playgroud)

(获得id为5的公司)

如果公司'5'不存在,我们通常会返回一个404 Not Found回复.

但是现在,让我们接听这个电话:

GET api/companies/5/invoices/10 
Run Code Online (Sandbox Code Playgroud)

(从公司5获得发票10)

现在,如果公司'5'不存在,我们还会退货404 Not Found吗?或者,如果无法找到最外层的资源(在这种情况下为发票10),则仅返回404.

Bad Request也许是一个更好的选择吗?

Jos*_*ack 28

404是你最好的回应.根据HTTP RFC,http://www.ietf.org/rfc/rfc2616.txt,400 Bad Request意味着:

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

鉴于,404表示:

服务器未找到与Request-URI匹配的任何内容.

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


Mār*_*dis 6

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.
Run Code Online (Sandbox Code Playgroud)