每当我在基于Django/活塞的REST API应用程序中遇到验证失败时,我都会返回401 Unauthorized。 已经看了HTTP状态代码注册表 我不相信这是一个合适的代码验证失败,你们都建议什么?

400错误请求 401年未经授权 403年被禁止的 405方法不允许 406不可接受 412前置条件失败 417期望失败 422不可处理实体 424依赖失败

更新:上述“验证失败”是指应用程序级别的数据验证失败,即错误指定日期时间、伪造电子邮件地址等。


当前回答

在记录HTTP 1.1的RFC 2616中有关于这些错误语义的更多信息。

就我个人而言,我可能会使用400个坏请求,但这只是我个人的观点,没有任何事实支持。

其他回答

数据库中的副本应该是409冲突。

我建议使用422 UNPROCESSABLE ENTITY来处理验证错误。

我在这里对4xx代码给出了更详细的解释:http://parker0phil.com/2014/10/16/REST_http_4xx_status_codes_syntax_and_sematics/

来自RFC 4918(也在http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml):上有文档

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.

在记录HTTP 1.1的RFC 2616中有关于这些错误语义的更多信息。

就我个人而言,我可能会使用400个坏请求,但这只是我个人的观点,没有任何事实支持。

你说的“验证失败”到底是什么意思?你在验证什么?你指的是语法错误(比如格式错误的XML)吗?

如果是这样的话,我认为400个坏请求可能是正确的,但如果不知道你正在“验证”的是什么,就不可能说出来。

如果你正在验证数据,而数据不是,根据定义的规则,最好发送422(不可处理实体),这样发送方就会明白他违反了约定的规则。

坏请求是语法错误。有些工具,如postman,会提前显示语法错误。