REST API: 400 Bad Request 或 404 Not Found 在传递带有无效数据的参数时应使用哪一个

REST API: 400 Bad Request or 404 Not Found which one should be used when passing parameter with invalid data

我正在构建一个 REST API,但我对以下情况应该抛出什么错误感到困惑。

剩下的 API url 是, https://myapp.com/users/search?q=<search_query>&access_token=<token>&user_type=<type> 在上述端点中,user_type 参数具有有效值 'admin' 和 'standard'。如果我得到一些其他值而不是 'admin' 或 'standard' 我应该抛出什么 http 错误? 应该是 400 Bad Request 或 404 Not Found。

嗯 - 你在这里征求我们的意见。为什么不靠自己?

由于您提出了两种错误类型:404 代表 "Resource not found"。显然不是这样。您的资源(您的 API)已找到。 HTTP 错误代码 400 表示客户端发送了错误的请求 - 好的,您的客户端没有提供正确的查询变量。

但是,请检查 RFC 7231,第 6.5.1 节(我为您做的;)):

The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

由于您没有提供更多信息,您的客户可以请求什么以及为什么(是用户输入?)很难回答您的问题。

我的意见:通过 HTTP 200 OK 回答(请求可以!)但提供信息让客户知道由于某些更高(与 HTTP 无关)的错误而无法接受该请求。

干杯。

状态代码 404 不适用于此处,因为此代码表示资源无法找到当前表示。对我来说,资源甚至在尝试获取表示之前也不接受客户端提供的查询参数。

我会说使用状态代码 400 和描述问题的负载。类似的东西:

{
    "code": "errorcode",
    "description": "The value 'a value' isn't supported for parameter user_type"
}

这就是一些具有 REST API 的工具以这种方式处理此类错误的方式。例如:

希望对你有帮助, 蒂埃里