11

How can we handle empty collection on a RESTful interface, with Content-Range's items header?

For instance, having 42 records, a request Range: items=0-41 would return everything, and the response header would be: Content-Range: items 0-41/42.

However, how can we deal with Content-Range header when there is not any records? Thanks for any help.

Edit:

I mean, returning an empty collection, the server may want to return Content-Range: items x-y/0, where x and y are a value which would be different than 0. But which one? I think this is a sticky question, and the spec does not mention it.

T5i
  • 1,470
  • 1
  • 18
  • 34

2 Answers2

6

Actually the server should respond with an HTTP 416 Request Not Satisfiable, with Content-Range: */0.

T5i
  • 1,470
  • 1
  • 18
  • 34
  • Really? A completely different status code for when the collection is empty? I would expect status 200 with an empty array as result. `Content-Range: */0` makes sense though. – Stijn de Witt Jul 03 '17 at 19:00
  • 1
    Looking into it some more, I think the 416 status was meant for when the request includes a `Range` header that specifies an invalid range. However if no range was specified, you'd still want to apply a default range. Personally I think 416 is very unfriendly even if a range was specified. If I request `Range: 0-99` I just want to get the first 'page' of 100 items. Who cares if there are actually less? I'll read the response header to figure that out. But if it returns status 416 we basically force the client to request the total number of results first, separately. It makes no sense. – Stijn de Witt Jul 03 '17 at 19:08
  • I think 416 does make sense if the *start* of the range was out of bounds. But to force clients to first get the total so they can adjust the *end* of the range to stay within the total makes you end up with a very unintuitive (and slow) API. – Stijn de Witt Jul 03 '17 at 19:11
0

If you're getting non-zero numbers for X-Y/0 - then the response from the server is invalid (broken). File a bug.

Kylar
  • 8,876
  • 8
  • 41
  • 75
  • 1
    Okay. So what should answer the server if the collection is empty? Having `Content-Range: 0-0/0` would be impossible, because `0-0` means *1 record* inside the collection. – T5i Oct 28 '13 at 21:49
  • 1
    There's no content, so you wouldn't return a Content-Range header. If you *must*, the spec allows you to return an asterisk ("*") in the cases where (From RFC): "instance-length is unknown at the time when the response was generated." – Kylar Oct 29 '13 at 22:21
  • 1
    *"There's no content, so you wouldn't return a Content-Range header."*, not sure whether that makes sense. Why treat an empty collection as an exception (with no range header and 416 status suggested by the accepted answer)? It makes no sense in my mind. An empty collection is normal. No reason to treat it as if it was some weird edge case. – Stijn de Witt Jul 03 '17 at 19:02