更正 HTTP 状态代码以用于超出已知数据的查询

Correct HTTP status code to use for query beyond known data

我正在定义一个 API 并且遇到了一个我以前不必处理的问题。我想知道这里的共识是什么,用于在结果未知(尚未)的情况下响应的最佳状态代码。

解释一下,有问题的 GET 端点不是 return 资源,它只是 return 关于已知日期的特定信息的工具。

用于执行此操作的后端日历数据是定期手动加载的。因此,如果用户查询超出(或早于)已加载日期范围的日期,API 应如何响应?

最初我以为是 4xx 错误,但语法和查询在技术上是有效的。在另一个时间尝试完全相同的查询(当该日期的数据已加载时)将导致成功响应。

查看 5xx 错误,non 似乎是一个理想的匹配项。 503 Service Unavailable 看起来最接近我,但似乎专注于临时错误。这种情况可能会持续数月之久。一个复杂的问题是 API 本身不知道什么时候会加载更多数据,所以我们也不能轻易地使用 Retry-After header。

你会怎么做? 谢谢!

202 Accepted 表示服务已成功接受请求,到目前为止,它没有任何问题(即没有立即的数据验证问题),但它无法创建资源,直到它做进一步处理。不过,此响应并不承诺会创建资源。因此,它非常适合待处理的请求,因为待处理的请求在处理过程中可能会被拒绝。

附加 Location header 端点服务异步操作的实际状态也很重要,以便客户端能够定期监控它。

不要为此使用 4xx 或 5xx HTTP 状态代码。

只有在请求或响应中出现错误时才应使用它们,而实际上没有。

4xx 错误表示请求失败(实际上没有),5xx 表示服务器错误。

绝对使用 2xx 回复,200 OK 或 202 Accepted

To explain, the GET endpoint in question doesn't return a resource, it just a tool to return specific information about known dates.

REST 的意义上说,这是一种资源。

The key abstraction of information in REST is a resource. Any information that can be named can be a resource: a document or image, a temporal service (e.g. "today's weather in Los Angeles"), a collection of other resources, a non-virtual object (e.g. a person), and so on. In other words, any concept that might be the target of an author's hypertext reference must fit within the definition of a resource. A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time.

特别是,某物是资源这一事实绝不取决于用于提供资源表示的实现。

if a user makes a query for a date that is beyond (or prior to) the date range that has been loaded, how should the API respond?

通常通过返回一个向客户解释问题所在的消息正文,并在元数据中包含一个响应代码来指示对通用组件的响应的性质。

特别是,您需要注意 缓存 应该如何与您的响应交互,因为它们只会查看元数据,而不是负载。

在像这种情况的大多数情况下,您想报告错误并指示缓存存储响应以备后用

因此您需要使用状态代码 404 Not Found

The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

404 实际上是在暗示目标 uri 的拼写错误,或者客户端不应该请求此特定资源。无论哪种情况,都是请求的问题,应该这样处理。

Trying the exact same query at another time (when the data for that date has been loaded) would result in a successful response.

请注意,HTTP 标准明确指出 404 可用于 临时 条件:

A 404 status code does not indicate whether this lack of representation is temporary or permanent