HTTP 200或404是否为空列表? [英] HTTP 200 or 404 for empty list?

查看:129
本文介绍了HTTP 200或404是否为空列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个相当常见的问题,但我还没有找到满足我的答案。

I know this is a fairly common question, but I haven't found an answer that satisfies me.

我一直在使用django rest框架一段时间现在,但除了给出的例子之外,这几乎是无关紧要的。它的默认行为是在访问具有空列表项的路由时返回带有空列表资源的HTTP 200。
例如:如果我们有一个诸如 / articles / 之类的路径来访问文章列表但它不包含任何项目我们会得到如下json的响应:

I've been using django rest framework for a while now, but this is mostly irrelevant other than the example given. Its default behaviour is to return an HTTP 200 with an empty list resource when accessing a route with an empty list of items. E.g.: if we had a route such as /articles/ to access a list of articles but it contained no items we would get a response like the following json:

{"count":0, "next":null, "previous":null, "items": []}

哪个完全没问题。我们在/ articles /找到了我们正在寻找的资源,它恰好没有任何项目。

Which is perfectly fine. We found the resource we were looking for at /articles/, it just happens to have no items in it.

如果我们访问路线 / article /?page = 1 ,我们得到完全相同的回复。

If we access the route /articles/?page=1, we get the exact same response.

到目前为止一切顺利。现在我们尝试访问 / articles /?page = 2 ,响应代码也会更改。现在得到一个 404 ,好像找不到资源,并显示一条错误消息,指出该页面没有结果。哪个是与?page = 1相同的情况...

So far so good. Now we try to access /articles/?page=2, and the response code changes. Now get get a 404 as if the resource could not be found with an error message saying that the page contains no results. Which is the same case as with ?page=1...

我对此行为完全没问题,但今天我开始质疑这个设计。 ?page = 1 的情况如何与?page = 2 不同?而且,在发出HEAD请求时,如何判断请求是否有效?在包含任何结果的意义上是有效的。

I was perfectly ok with this behaviour, but today I started questioning this design. How is the ?page=1 case different than ?page=2 ? And what's more, how could you tell if the request was "valid" when issuing a HEAD request? Valid in the sense of containing any results.

这在过滤列表检查某个字段的可用性(例如,发出<$ c)的情况下非常有用。 $ c> HEAD 请求 / users /?username = ted )。

This could be useful in cases like filtering a list checking the availability of a certain field (for example, issuing a HEAD request to /users/?username=ted).


  • 200响应显然意味着请求被理解并且找到了项目。

  • 404意味着请求被理解,但在该位置没有找到任何项目/ URI(AFAIK查询参数也是URI的一部分)

  • 如果无法理解请求,则会返回400语法错误,并返回422语义错误。

这是一个好的设计吗?为什么大多数人似乎不同意它并且有什么缺点?

Is this a good design? Why do most people seem to disagree with it and what drawbacks are there in it?

推荐答案

我会去 200 因为资源是文章
用户中查询 ted 同样适用,用户是资源,只要它存在,从我的角度来看, 200 是可以的。
如果你 GET users / ted a 404 410(GONE)一样好。

I would go for 200 because the resource is articles. While querying for ted in users the same applies, users is the resource and as long it is there, a 200 is okay from my point of view. If you would GET users/ted a 404 would be as good as a 410 (GONE) if a user named ted was there in the past (may better applies to articles than users).

这篇关于HTTP 200或404是否为空列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆