rest - POST 数据不正确时的 HTTP 状态(使用不存在的资源 ID)

标签 rest http-status-codes http-status-code-422

什么是 正确的 HTTP 状态返回 当我执行 POST 请求以创建新用户,但其中一个参数不正确时 - 数据库中不存在我包含在用户数据中的公司 ID。

邮政
数据:{用户名:'newuser',年龄:99,公司 ID:34 }

数据库中不存在 ID 为 34 的公司。

我在想这是否可能是:

  • 400,一种无效数据,但它是有效但不存在的id
  • 404 - 但不清楚哪个资源不存在
  • 409,因为这是一种冲突,用户可以通过更改公司 ID
  • 来解决这个问题。
  • 422?
  • 或 500 - 因为这是一种数据库错误,而不允许存在不存在的 ID
  • 最佳答案

    400422
    首先,请记住它是 client error ,所以 5xx 状态代码不适合这里。你应该选择一个 4xx 然后状态码。

    最明显的选项是 400 422 :

  • 如果 JSON 在语法上无效,则返回 400 .
  • 如果 JSON 在语法上有效但其内容无效,则返回 422 表示服务器无法处理请求实体。

  • 请参阅以下来自 RFC 4918 的引用(对于您的情况,只需在显示 XML 时读取 JSON):

    11.2. 422 Unprocessable Entity

    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.



    answer 中解决了类似的情况。 .

    例如,GitHub API v3也返回 422 如果有效负载的内容包含无效值(但在语法上有效):

    There are three possible types of client errors on API calls that receive request bodies:

    1. Sending invalid JSON will result in a 400 Bad Request response. [...]

    2. Sending the wrong type of JSON values will result in a 400 Bad Request response. [...]

    3. Sending invalid fields will result in a 422 Unprocessable Entity response. [...]



    Michael Kropat拼凑一个set of diagrams在选择最合适的状态代码时,这是非常有见地的。 4xx见下图状态代码:

    Picking the right 4xx status code

    关于rest - POST 数据不正确时的 HTTP 状态(使用不存在的资源 ID),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50643217/

    相关文章:

    nginx - CORS 和非 200 statusCode

    rest - 更新资源时,更新成功返回什么HTTP状态码?

    android - 如何从 422 Unprocessable Entity 响应中获取错误消息

    java - 如何解析 Retrofit 2 响应以显示数据?

    java - java中处理多个http状态错误码的最佳实践

    rest - 在 RESTful API 的上下文中,使用 RSA 签署 JWT 比 SHA 有什么优势?

    angular - 错误 : 422 (Unprocessable Entity). Angular4

    mysql - 相关对象的 RESTful API

    java - Jackson JSON 动态键值绑定(bind)到 Java Bean