HTTP 200 or 404 for empty list?

前端 未结 4 1642
旧巷少年郎
旧巷少年郎 2021-02-13 12:30

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

I\'ve been using django rest framework for a while now, but this is mostly irr

4条回答
  •  渐次进展
    2021-02-13 13:31

    This really boils down to the "null vs empty collection" argument. The cases for null are also cases for HTTP 404, and the cases for an empty collection are also cases for HTTP 200.

    if we had a route such as /articles/ to access a list of articles but it contained no items

    Assuming this is a global list of articles, i.e:

    http://mywebsite/articles

    then this response can never be null, and therefore should never be a 404. The global list of articles always exists, and therefore the collection is always not-null, regardless of whether it contains elements or not.

    A simple example here is thinking of a SQL query. If a table exists, even if it's empty, a query will return a result (be it empty or not), so use 200. If the table itself does not exist, you get a query error, so 404.

    But if the articles are contained within another resource, e.g. their author:

    http://mywebsite/authors/johndoe/articles

    Now we get to the part where null (and thus 404) is meaningfully possible.

    • If johndoe exists and has articles, you return a non-empty list
    • If johndoe exists and does not have articles, you return an empty list and HTTP status 200
    • If johndoe does not exist, then you return null and HTTP status 404

    This communicates the correct response to the user. 200 reveals that the data was correctly fetched, whereas 404 reveals that the requested resource simply does not exist.


    Note that this is slightly different when referring to a specific article instead of a list. When returning a specific resource (or not), instead of a list, 404 is the only correct HTTP status for a 'no item' response.

    http://mywebsite/article/1

    Here, you either return the article or null.

    http://mywebsite/authors/johndoe/articles/1

    Here, you return 404 when either author johndoe or article 1 does not exist.

提交回复
热议问题