xml - REST - 何时使用 400 ("Bad Request")

标签 xml rest http-status-codes restful-architecture http-status-code-400

我有这样的资源 sales/customers/{customerno}。如果客户端向此资源发送 PUT 请求,如果实体正文中的 xml 不是有效的 xml,我将返回 400 - 错误请求。但是,如果 xml 有效,但 xml 的内容无效怎么办。例如,假设客户端正在尝试更新客户的邮政编码并提供无效的邮政编码。在这种情况下返回 400 - Bad request 是正确的,还是我应该使用的另一个 http 代码?

最佳答案

来自 Wikipedia's List of HTTP Status Codes :

400 Bad Request: The request cannot be fulfilled due to bad syntax.

在这种情况下,您的客户端向您发送了一个包含无效邮政编码的 XML 负载,这是一种无效语法形式;因此,发送 400 Bad Request 是在这种情况下返回的适当错误代码。

此外,维基百科引用了 RFC-4918作为有关此主题的资源。从本文档中,您将找到以下信息:

Servers MAY reject questionable requests (even though they consist of well-formed XML), for instance, with a 400 (Bad Request) status code and an optional response body explaining the problem.

由于您的请求格式正确(XML 不错,它只是包含语义上不正确的信息)您可能拒绝状态代码为 400 的内容。单词 *may* 表明还有其他选择。

虽然您可能想使用状态代码 422,但在这种情况下这是不正确的,因为无效的邮政编码不符合语义错误的标准。阅读下文...

来自维基百科:

422 Unprocessable Entity (WebDAV; RFC 4918): The request was well-formed but was unable to be followed due to semantic errors.

此外,这里还有一些definitions to assist in the interpretation of status code 422 :

  • Syntax errors occur during the parsing of input code, and are caused by grammatically incorrect statements. Typical errors might be an illegal character in the input, a missing operator, two operators in a row, two statements on the same line with no intervening semicolon, unbalanced parentheses, a misplaced reserved word, etc.

  • Semantic errors occur during the execution of the code, after it has been parsed as grammatically correct. These have to do not with how statements are constructed, but with what they mean. Such things as incorrect variable types or sizes, nonexistent variables, subscripts out of range, and the like, are semantic errors.

您的无效邮政编码既不是语法错误也不是语义错误;因此,排除状态代码 422 作为一种选择是合理的。

要回答你的问题,状态码400是合适的;但是,您也可以有其他选择。

关于xml - REST - 何时使用 400 ("Bad Request"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10847224/

相关文章:

xml - 在 Go 中解码 XML

java - Android 我怎样才能制作这个 EditText 的渐变

java - 使用 XML 分配的 Java 字符串中的字符串操作

apache - 我应该返回 501/505 HTTP 状态还是 400/404

c# - VS2012 导出 "User Settings"

rest - HATEOAS - 休息并不是真正的休息

android - 使用 ETag 的 Volley 缓存

java - 如何在不使用 web.xml 的情况下配置 Jersey JSPTemplatePath

php - Laravel - 返回 json 和 http 状态码

iphone - HTTP 状态代码 = 0 (iPhone)( objective-c )