REST 的哪个 4xx http 状态码

Which 4xx http status code for REST

我们有一个 RESTful 架构,我有一个关于 API.

的异常和 http 状态的问题

我们使用 400 个案例:

在逻辑错误但不是客户端错误的情况下使用422(无法处理的实体)。例如,尝试将类别设置为已有类别的产品。这在客户端是不可预测的。

最后,我们使用 409(冲突)来处理客户端错误的情况。 例如,如果他试图通过 JSON 发送无效的 Date 格式。或者注册日期远早于当前日期。

但一个案例可以归为几类: 我们有一个 Tax 字段,它是整数。

如果客户端发送 小数 Tax 那么应该抛出异常。

从一方​​面来看,这显然是 400,客户应该看到 'Tax cannot be fractional'。

但是,从另一方面来看——这是客户的程序员错误,因为他试图发送 Double/Float Integer/Long (即他发送 另一种 类型,就像传递 Long 而不是 String) 并且应该抛出 409。

我应该选择什么:400409 for TypeMismatch in Numbers case? 如果 400,我为什么要为 Number 类型做一个 exusement,而为 TypeMismatchDate/String 情况抛出 409

我更喜欢有明确逻辑的答案而不是"I think"。这不是讨论。

意见:由于类型更基本,我会抛出 409

我同意基于意见的问题评论,但我也会把它扔在那里:

我不明白您为什么要 409 处理任何这些情况。 这是维基百科关于 409 的说法:

Indicates that the request could not be processed because of conflict in the request, such as an edit conflict in the case of multiple updates.

我会使用 400 作为数字类型以及 Date/String 大小写。

但这是个人喜好问题,只要您在 API 期间保持一致,两种状态代码都是可能的。

老实说,对于您的用例,我更喜欢状态代码 400422,因为所提供的实体因其内容而无法处理。这可能是结构性的(错误的类型、缺少必填字段……)或数据验证(使用正则表达式的错误格式、不允许的值、重复值……)。

状态代码 409 更应该用于乐观锁定,如 link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html:

中所述

10.4.10 409 Conflict

The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.

Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can't complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.

希望对你有帮助, 蒂埃里