return 的 HTTP 代码用于不支持的 PATCH

HTTP code to return for unsupported PATCH

我正在 dropwizard REST 资源上实施 PATCH 方法。 目前只有资源属性的一个子集被修补。并且目前只能完成replace操作

如果我看到对 property/path 的 PATCH 请求不受支持,我应该 return 使用哪个 HTTP 代码?如果请求不支持的 addremove 操作,我应该 return 怎么办?

Which HTTP code should I return if I see a PATCH request for a property/path that is not suppported?

在这种情况下,服务器应该 return 405 to indicate that a HTTP method is not supported by the target resource. Besides the status code, the server must return an Allow header 列出该资源支持的方法:

6.5.5. 405 Method Not Allowed

The 405 (Method Not Allowed) status code indicates that the method received in the request-line is known by the origin server but not supported by the target resource. The origin server MUST generate an Allow header field in a 405 response containing a list of the target resource's currently supported methods.


And what should I return if the unsupported add or remove operations are requested?

我假设你的意思是 add and remove operations from JSON Patch,一个 JSON 文档,描述了应用于 JSON 文档的一系列操作,适合与 PATCH HTTP 方法。

那么请看一下 error handling section of the RFC 5789,定义 PATCH HTTP 方法的文档。

你问题中描述的情况,其实是一个实体,由于语义原因,无法被服务器处理。所以 422 is a reasonable choice, according to the RFC 5789:

Unprocessable request: Can be specified with a 422 (Unprocessable Entity) response when the server understands the patch document and the syntax of the patch document appears to be valid, but the server is incapable of processing the request. This might include attempts to modify a resource in a way that would cause the resource to become invalid; for instance, a modification to a well-formed XML document that would cause it to no longer be well-formed. [...]

另请记住同一文档中的以下建议:

The entity body of error responses SHOULD contain enough information to communicate the nature of the error to the client. The content- type of the response entity can vary across implementations.

RFC 7807 定义了可用于报告 HTTP API 问题的文档格式。

我的投票是 405:

405 Method Not Allowed

A request method is not supported for the requested resource; for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource.

加上Cassio提出的关于提供足够的信息来描述错误的建议。