假设我有一个将用户绑定(bind)到公司的 RESTful API:PUT http://example.com/users/john.smith
{
"company": "http://example.com/companies/Nintendo"
}
但引用的公司不存在(可能是由于竞争条件,也可能是由于用户错误)。该操作无法成功完成,因为数据库需要外键指向现有行。什么是适当的响应代码,为什么?
最佳答案
绝对是4xx
错误,因为客户提供的信息是问题的根源。
由于我们正在处理 的问题语义 自然, HTTP 1.1's WebDAV 422
是最适合的响应代码:
422 Unprocessable Entity (WebDAV)
The
422 (Unprocessable Entity)
status code means the server understands the content type of the request entity - hence a415 (Unsupported Media Type)
status code is inappropriate -, and the syntax of the request entity is correct - thus a400 (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.
当然,不要让您的客户独自一人在黑暗中,并确保您在响应正文中解释 为什么错误正在发生。
现在讨论一下为什么不是其他代码,首先是三个更令人困惑的,然后是其余的:
`403 Forbidden` *服务器理解请求,但拒绝执行。授权将无济于事,并且不应重复请求*:这通常在客户端经过身份验证但缺乏对请求资源的权限(写入、读取或其他要求)时发出。也不是 403。
`404 Not Found` *服务器没有找到任何与Request-URI*匹配的东西:注意错误是关于**Request-URI**,也就是用户。当 **user**(URI 中的那个)不存在时,应发送此响应,而不是公司。
`401 Unauthorized` *请求需要用户认证*:这里无需争论。
`402 Payment required` *此代码保留供将来使用*:此处均无。
`405 Method Not Allowed`:与 HTTP 方法无关(`GET`、`PUT` 等)。
`406 Not Acceptable`:这与接受 header 有关。
`407 Proxy Authentication Required`:代理相关。
`408 Request Timeout`:显然不是。
`409 Conflict`: *由于与资源的当前状态冲突,请求无法完成。*当前(之前保存的)资源(用户的公司)在服务器中是正常的。任何新公司都是可以接受的,新公司和当前公司之间不能有冲突,因为新公司总是会覆盖当前公司。
`410 Gone`:*请求的资源在服务器上不再可用,并且不知道转发地址。*与此无关。
`411 Length Required`:关于 `Content-Length` header 。
`412 Precondition Failed`:关于请求 header 字段。
`413 Request Entity Too Large`:与实体的大小无关。
`414 Request-URI Too Long`:也不是 URI 的大小。
`415 Unsupported Media Type`:请求中的实体正常(服务器知道 JSON)。
`416 Requested Range Not Satisfiable`:关于 `Range` 请求 header 。
`417 期望失败`:关于 `Expect` 请求 header 。
`423 Locked (WebDAV)` *423 (Locked) 状态码表示方法的源或目标资源已锁定*:此处没有锁定任何内容。
`424 Failed Dependency (WebDAV)` *424(Failed Dependency)状态码表示方法无法在资源上执行,因为请求的操作依赖于另一个操作并且该操作失败*:在当前上下文。
关于rest - 请求实体中断开的链接的适当响应是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16632167/