首页 > 解决方案 > REST API response status code - search GET that returns a single result

问题描述

In case we have a search GET REST API endpoint that returns one or zero results for the currently logged in customer, I am wondering what the correct response status code would be, for instance:

api/subscriptions?productId=1

According to the specifications, the customer can either have ONE subscription, or be WITHOUT a subscription for the product.

As far as I understand, and according to the convention, this should be a 200 result, no matter if the result exists or not (the same logic as for a search endpoint that returns a list of objects). I believe it would be incorrect to return 404 here, as this result is only a resource that MIGHT exist?

I understand that this kind of query might even seem as unconventional, as it's purpose is not only to get the subscription, but also to check if it even exists.

I had the idea to wrap the response model in an object result, with the status code 200:

public class ActiveSubscriptionModel
{
    public bool HasActiveSubscription { get; set; }
    public SubscriptionModel Subscription { get; set; }
}

标签: c#apirestasp.net-web-apihttp-status

解决方案


TL;DR: 200 是正确的状态码


据我了解,根据惯例,这应该是 200 结果,无论结果是否存在(与返回对象列表的搜索端点的逻辑相同)。

不是按照惯例,而是按照规范- 200 是状态代码,这意味着 HTTP 响应的有效负载是所请求资源的表示

“您要求我提供由 /api/subscriptions?productId=1 标识的网页的表示,这就是我要发回给您的内容。” -- 200。

请注意,状态代码(它是通过网络域传输文档的元数据)与域中文档的语义完全没有关系。


204 没有内容可能是合适的。状态码可能有点主观。

不是一个很好的选择。 204声明响应的有效负载是零字节长,并暗示用户代理不应离开当前视图。

比较我们“应该”对 Web 浏览器的期望:一个 200 响应和零长度的正文将遍历到“空”网页的视图;204 响应会让我们查看之前的视图(可能会混淆查看网页的人)。

204 的亮点是我们在符合 HTTP 的编辑器中,对资源进行本地更改并与服务器共享它们的场景。我们点击编辑器上的保存按钮,表示被 PUT 到服务器,服务器按原样接受它,我们可以继续编辑而不刷新页面。

(您会看到205 Reset类似——适用于我们使用 Web 表单进行数据输入时)。


选择适当状态代码的部分技巧是记住服务器不控制客户端——我们不一定要向我们控制的 java 脚本代码发送响应。因此,我们希望确保我们发送的信息让每个人都能以同样的方式理解。


推荐阅读