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

我正在设计一个POST Restful API,我有一种情况,我必须根据请求体中提供的元素之一授权用户.

例如.

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

因此,发出POST请求的用户应该被授权在第1部分工作.我无法在没有获得请求主体的情况下授权用户.

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

所以我的问题是如何将错误代码返回给用户 –

> [编辑]如果请求中的分区无效(系统中不存在的东西) – 400或403?
>如果提供了分割,但用户未获得授权且密码无效 – 400无效密码或403?
>如果密码是强制属性且请求中未提供,则错误代码应该是什么.我应先检查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.

点赞