Reputation: 42100
I am defining a simple REST API to run a query and get the results with pagination. I would like to make both client and server stateless if possible.
The client sends the query, offset
and length
. The server returns the results. For example, if there are 1000 results and client sends offset
= 10 and length
= 20, the server either returns 20 results since #10 till #29 if the total number of the results >= 30 or all results since #10 if the total < 30.
Client also needs to know to the total number of the results. Since I would like to keep both client and server stateless the server will always return total
with the results.
So the protocol looks like following:
Client: query, offset, length ----------->
<----------- Server: total, results
The offset
and length
can be defined optional. If offset
is missing the server assumes it is 0. If length
is missing the server returns all the results.
Does it make sense ? How would you suggest define such a protocol ?
Upvotes: 2
Views: 2257
Reputation: 919
My way to implement pagination uses implicit information.
The client can only get "Pages". NO OFFSET OR LIMIT given by client.
GET /users/messages/1
The server in giving the first page with predefined amount of elements, e.g., 10. The Offset is calculated from the page number. Therefore the client dont have to worry about total amount of elements. This information can be provided in a header. To retrieve all elements (exceptional case) the client hast to write a loop and increment the page count.
Advantages: Cleaner URI; true pagination; offset, limit, lenght are clear defined.
Disadvantages: Getting all elements is hard, flexibility lost
Dont overload URIs with meta information. URIs are for resources identification
Upvotes: 2
Reputation: 10328
There is no standard in REST API design.
Since it's a query, not retrieving resource by its id, the search criteria is put into query string parameter, followed by the optional offset and length parameter.
GET /resource?criteria=value&offset=10&length=3
Assume your'd like to use JSON as response presentation, the result can be like this:
{
"total":100,
"results":[
{
"index":10,
"id":123,
"name":"Alice"
},
{
"index":11,
"id":423,
"name":"Bob"
},
{
"index":12,
"id":986,
"name":"David"
}
]
}
Upvotes: 4