API响应状态代码的最佳实践

时间:2022-03-06 00:12:21

I am building an API and I am returning this kind of status codes for each method (e.g., "register_user"):

我正在构建一个API,我正在为每个方法返回这种状态代码(例如,“register_user”):

  • 200 (OK) when the user has been registered successfully
  • 200(OK)用户注册成功后

  • 403 (forbidden) when there are missing parameters in the request
  • 403(禁止)请求中缺少参数

  • 409 (conflict) when a user was already registered
  • 409(冲突)用户已经注册

In addition to the status code, I return a "message" field explaining what happened. Do you consider returning these codes in this example a good practice? Or should I return 200 in all of them but an error in the "message" field?

除了状态代码,我还会返回一个“消息”字段来解释发生了什么。你认为在这个例子中返回这些代码是一个好习惯吗?或者我应该在所有这些中返回200但在“消息”字段中出错?

1 个解决方案

#1


0  

The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).

403(禁止)状态代码表示服务器理解请求但拒绝授权。希望公开请求被禁止的服务器可以在响应有效负载中描述该原因(如果有的话)。

-- RFC 7231, 6.5.3

- RFC 7231,6.5.3

That doesn't sound like what you've got at all. The other two are reasonable. Missing parameters are typically handled with a 400 response code.

这听起来并不像你所拥有的那样。另外两个是合理的。缺少参数通常使用400响应代码处理。

#1


0  

The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).

403(禁止)状态代码表示服务器理解请求但拒绝授权。希望公开请求被禁止的服务器可以在响应有效负载中描述该原因(如果有的话)。

-- RFC 7231, 6.5.3

- RFC 7231,6.5.3

That doesn't sound like what you've got at all. The other two are reasonable. Missing parameters are typically handled with a 400 response code.

这听起来并不像你所拥有的那样。另外两个是合理的。缺少参数通常使用400响应代码处理。