Suppose we have an endpoint that return a list of users, list can be paginated
/users?offset=20&limit=10
What to return when total count of users is less than offset? An empty list, an error or ...?
Should we also return total count of users in response? Or this should be another endpoint?
I would return an empty array. The URL is not technically wrong. It also makes it easier for the client to handle such cases.
I would also return some meta data about the response, including the total number of returned items and an URL from which the client can request the next set of results.
Example:
"meta": {
"cursor": {
"current": "0",
"next": "20",
"count": 20,
"next_url": "/items?cursor=20&limit=20"
}
}
I would make sure that the client uses the URL instead of trying to parse the offset and calculate the next URL by itself. This will make it more flexible and allow you to change the implementation details later.
For example, if you use the offset value to construct an OFFSET
query for an SQL database, you might want to change the implementation later if the database gets really big, and use a more efficient offsetting. For example, you could change your API to output a timestamp as the offset if you items are always sorted by time. This might allow for more efficient queries.
If the next URL is null, there's no need for the client to try to fetch more items. However, if the next URL exists, there still might not be any more results depending on your implementation (it's hard to count the total result count in a large database, in which case you don't know the total number in advance).