web-services - POST Restful API 的响应代码 400 或 403

标签 web-services rest

我正在设计一个 POST Restful API,在这种情况下,我必须根据请求正文中提供的元素之一授权用户。
例如。

{
division : "1",
name : "MyName",
address:{
no : 123,
street : "abc",
pincode : 222111
}
....
}

所以发出 POST 请求的用户应该被授权在第 1 部分工作。我不能在没有获取请求正文的情况下授权用户。

还要验证一些属性,我必须在 DB 中进行大量 DB 调用,例如,检查上述地址是否具有有效的 pincode 值。

所以我的问题是我应该如何将错误代码返回给用户 -
  • [编辑]如果请求中的除法无效(系统中不存在的东西) - 400 或 403 ?
  • 如果提供了除法,但用户未被授权且密码无效 - 400 为无效密码或 403 ?
  • 如果 pincode 是必需属性并且请求中未提供,则错误代码应该是什么。我应该先检查 403 然后检查 400 还是反转?

  • 基本上哪个错误代码继续另一个?

    也可以做类似的事情:
    400 – request is bad, syntactically (division/pincode or other mandatory values not provided)
    403 – authorize user
    400 – request is bad, data specific validation (heavier operation, requiring to hit DB)
    

    [编辑] 我们宁愿不使用 422 错误代码

    最佳答案

    如有疑问,请查看 RFC

    400 Bad Request

    The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.



    403 Forbidden

    The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.



    如果请求中未提供除法 - 400 还是 403?

    我认为两者都不适用。语法 - 尽管缺少一些数据 - 是 不是 畸形。
    由于引用中提到的原因,403 似乎也不正确:授权无济于事等。

    怎么样422 Unprocessable Entity ?

    422 Unprocessable Entity (WebDAV; RFC 4918)

    The request was well-formed but was unable to be followed due to semantic errors.



    这就是我在这种情况下通常使用的方法。

    如果提供了除法,但用户未被授权且密码无效 - 400 表示无效密码或 403?

    同样,我不认为 400 或 403 在这里是一个很好的例子。专门针对这种情况,401存在

    401 Unauthorized

    Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource. See Basic access authentication and Digest access authentication.

    关于web-services - POST Restful API 的响应代码 400 或 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29912305/

    相关文章:

    ios - 异步使用 NSXMLParser 的问题

    web-services - 如何将soap web服务转换为wso2 ESB中的Rest

    api - REST API,具有关系的POST实体?

    java - 我的 REST 方法应该有一个单独的 Controller 吗?

    REST API设计: do,然后撤消

    java网络服务: how to identify user

    java - 如何使用库 java web 应用程序

    java - 基于 REST token 的身份验证不起作用

    rest - 不同的资源表示(REST API)

    javascript - 使用另一个 Web 应用程序从一个 Web 应用程序打开文件?