Search code examples
restpaginationoffset

REST API pagination - How to handle offset exceeding total count


I have a RESTful API that uses limit & offset to handle pagination (as described here). Each request also returns the total number of items available in order to allow clients to display pagination properly.

I'm wondering how to handle calls where the offset exceeds the total number of items. I can detect that case easily, because the total count is checked before fetching any records - which allows me to skip the record fetching call as a micro-optimisation, as I know it will return nothing.

I see two options:

  1. Business as usual: I return a standard response, but with an empty array of items.
  2. 404: No results were found matching this request. This has the advantage of allowing me to send an empty body, but also has the ambiguity that the endpoint is not valid.

I'm not sure which option to go with, or if there is a better one.

Edit: It seems like the proper solution is to return a 204. It allows me to send an empty body, without the ambiguity of endpoint invalidity.


Solution

  • As I stated in the other answer, I would use one of:

    • HTTP 200 with count=0 and no items in the returned list.
    • HTTP 400 because invoker asked for an url that is invalid
    • HTTP 404 because items to return are not found

    I think it's safe to return an error (4xx + error info) in this situation because the offset can be exceeded by one of these assumptions:

    • A coding error
    • Invoker is not fetching data from begining (no fresh state)
    • Invoker ignored pagination data (present on each response)

    HTTP 204 in pagination response is not factible because of the payload. When paginating you should return pagination information like, items returned, total items, offset, etc. which is not allowed with HTTP 204.