当对一个语义无效或损坏的资源进行HTTP GET响应时,什么是最好的HTTP状态码呢?
例如,考虑对GET /person/1234
的请求,其中服务器存在ID为1234的人员数据,但违反了某些业务规则,因此服务器拒绝使用它。
- 404不适用(因为数据实际上存在)。
- 总的来说,4xx似乎不理想(因为问题在服务器端,而不是客户端控制之下)。
- 503似乎适用于整个服务,而不是特定的资源。
- 500确实适用,但在实际告诉客户端可能出错的情况下非常模糊。
有什么建议吗?
当对一个语义无效或损坏的资源进行HTTP GET响应时,什么是最好的HTTP状态码呢?
例如,考虑对GET /person/1234
的请求,其中服务器存在ID为1234的人员数据,但违反了某些业务规则,因此服务器拒绝使用它。
有什么建议吗?
我认为500是唯一适合这种情况的官方响应代码。并且没有任何阻止你包含一个描述失败原因的响应正文。
4xx: Client Error - The request contains bad syntax or cannot be fulfilled
5xx: Server Error - The server failed to fulfill an apparently valid request
我认为在内部服务器错误或迁移等情况下,没有任何一个4xx状态码应该作为响应。除非包括用户预填充的数据,比如用户的套餐不允许他在预定和已知日期之后访问该数据,在这种特定情况下,可能会使用403 Forbidden,就像@Bari建议的那样。
我不是专家,但我认为当服务器拒绝或决定将端点数据视为损坏或无效时,取决于接下来应该做什么。我看到3种可能的情况:
1. 预计以某种方式会修复此问题,并且应邀请客户端在未来的某个时刻重新请求它==>503 (服务不可用):
503 (Service Unavailable)
status code indicates that the server
is currently unable to handle the request due to a temporary overload
or scheduled maintenance, which will likely be alleviated after some
delay. The server MAY send a Retry-After header field
(Section 7.1.3) to suggest an appropriate amount of time for the
client to wait before retrying the request.
2. 有些问题出现了,这不是客户端的责任,但有一种替代方法可以访问数据,可能需要遵循特定的流程或发送更多详细信息 ==> 510未扩展
2. 服务器无法满足请求,但有一种替代方法需要包含更多详细信息。 例如:当请求的数据损坏时,服务器错误响应可能包括一个旧版本(或未保存、未版本化)的列表,并期望客户端更具体地选择要获取的版本,而不是损坏的版本。 ==> 510未扩展
510 Not Extended
The policy for accessing the resource has not been met in the
request. The server should send back all the information necessary
for the client to issue an extended request. It is outside the scope
of this specification to specify how the extensions inform the
client.
If the 510 response contains information about extensions that were
not present in the initial request then the client MAY repeat the
request if it has reason to believe it can fulfill the extension
policy by modifying the request according to the information provided
in the 510 response. Otherwise the client MAY present any entity
included in the 510 response to the user, since that entity may
include relevant diagnostic information.
3. 没有其他替代方法,没有期望的结果或者其他情况 ==> 500 应该是好的。
500 (Internal Server Error)
status code indicates that the server
encountered an unexpected condition that prevented it from fulfilling
the request.