rest - 发布不存在的 ID 时,REST API 是否应该返回 404?

标签 rest http http-status-code-404

据我所知,除了为未知端点返回404 Not Found之外,REST API 还应该在以下情况下返回 404:

  • 请求资源的 ID 不存在于路径中:路由 /users/{id} 存在,但 /users/123456不存在
  • 请求资源的 ID 不存在于查询参数中:路由 /search 存在,但 /search?user=123456 如果用户不存在则返回 404(几年前我问过 similar question)

现在端点接受具有多个字段的 JSON 对象的用例如何,其中一个是不存在的用户 ID:

POST /makeReservation HTTP/1.1
...

{
    "userId": 123456,
    ...
}

这是否也应该返回 404,或者在这种情况下这是否被视为不同类型的错误(验证错误?)?

最佳答案

As far as I understand it

我想说您目前的理解比应该理解的要复杂一些。

404 Not Found意思是:

The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

如果“目标资源”不清楚,我们可以查看 Request Line 的规范.

request-line = method SP request-target SP HTTP-version CRLF

The request-target identifies the target resource upon which to apply the request, as defined in Section 5.3.

换句话说,404 表示“请求目标的拼写有问题”。

因此,当实际问题出在请求正文中时,暗示请求目标存在问题是误导性的。

对于这种情况,您可能需要的错误代码是 422 Unprocessable Entity

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.

IANA 的 HTTP Status Code Registry当您确定应该有适用于您的用例的标准化代码,但您很难猜测是哪个规范描述它时,这是一个不错的地方。

it's part of WebDAV and I'm not sure how correct it is to use it for other applications?

TL;DR:将它用于其他应用程序是正确的。

HTTP 规范定义了 process通过它可以将新代码添加到状态代码注册表中,并且 WebDAV 代码已遵循该过程。所以我们可以确信 422 的含义不会被其他语义所取代(为了兼容性,状态代码已停用——参见状态代码 306。)

WebDAV 规范中 422 的定义不是 WebDAV 特定的。

此外,在 RFC 7231 中描述了不了解 WebDAV 规范的客户端的行为。

a client MUST understand the class of any status code, as indicated by the first digit, and treat an unrecognized status code as being equivalent to the x00 status code of that class, with the exception that a recipient MUST NOT cache a response with an unrecognized status code.

您还可以查看 appendix B WebDAV 规范。

(作为旁注,我认为您的担忧是合理的——WebDAV 方法在该上下文之外更难重用。)


2022-07-12 更新:状态代码 422 的 IANA 注册引用现在是 RFC 9110 (HTTP 语义)。当我们在 WebDAV 上下文之外使用该状态代码时,我们不再需要担心。

关于rest - 发布不存在的 ID 时,REST API 是否应该返回 404?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56872243/

相关文章:

html - WavPack用于html音频播放

PHP & MySQL 空记录

angularjs - 如何捕获无效的 URL?

javascript - 使用 javascript 打开下载的 zip 文件时出现问题

c# - 使用 RestSharp 反序列化来自一个资源的不同数据输出

java - 如何在 Java 中使用 Firebase REST API?

java - 如何一致地处理 jersey 和 tomcat 错误?

rest - 使用维基百科的 RecentChanges API 进行实时数据流

http - 在 rfc7230 中遇到 "ought"时应该如何解释?

php - CodeIgniter 应用程序在移至生产环境时显示 404