Which HTTP code to use for an empty subresource in

2019-02-08 08:21发布

Let's say I've a resource articles at /articles.

These articles may have related articles, so I fetch them by GETting /articles/{id}/related.

What should I return is there is no related articles?

I can think of:

  • 404 Not Found, maybe with an empty collection
  • 204 No Content
  • 200 Found with an empty collection

Any advices? (please give arguments)

By the way, it may applies to pagination. If I request page 3 of 2, then the page 3 will return an empty set, should It be a 404?

3条回答
Juvenile、少年°
2楼-- · 2019-02-08 08:43

404 is not what you are looking for. It's an error condition. Your case is not an error. The client currently doesn't know if there are any related articles and wants to know. That is not an error.

204 is not appropriate either. RFC 2616 states:

  The server has fulfilled the request but does not need to return an
  entity-body, and might want to return updated metainformation. The
  response MAY include new or updated metainformation in the form of
  entity-headers, which if present SHOULD be associated with the
  requested variant.

204 doesn't specify that there are no related articles. It just says that the server doesn't need to send the data.

200 with empty collection on the other hand would satisfy your need.

查看更多
男人必须洒脱
3楼-- · 2019-02-08 08:46

Return 200 with an empty array.

查看更多
SAY GOODBYE
4楼-- · 2019-02-08 08:48

I wouldn't use 404 -- that would tell the client it "I'm unable to tell you whether there are any releated articles". It would be appropriate if the {id} given is not recognized at all. What you want is a positive response to tell the client, yes, good question, and here is the (empty) list of related articles.

204 is not good either, for related reasons. It specified that there is no answer, which is still different from an answer that is there but happens to be the empty list. Its description makes more sense for a POST than for a GET.

200 with an empty list is just right.

查看更多
登录 后发表回答