Best way to create pagination endpoint in RESTful web service
I have an endpoint /entities
on my RESTful web service that returns all persisted objects in the database if called with a request GET
.
What I would like to create now is the pagination functionality. The ability to fetch only the page of these results, not all objects, just to minimize the size of the response.
I am thinking of two ways to do this.
-
Send pagination information using query parameters on the endpoint
/entities
with the queryGET
. For example,/entities?page=1&size=10
-
Use another
HTTP Method
one for exampleOPTIONS
(I know it is not meant to be used for this kind of thing). I am not handling requestsOPTIONS
on my web service, and I can take advantage of this while still keeping the essence of a RESTful web service, i.e. using differentHTTP Methods
for different actions. In this case, the endpoint might be something like this/entities/1/10
, which is (I think) more user-friendly .
Both alternatives can be implemented and I would like to know in advance which one would be more consistent with the REST design standard.
source to share
As mentioned above, there is no official standard. But looking at best practices I came across this site:
http://www.restapitutorial.com
There is a .pdf download link on the resources page that contains the full REST guidelines as suggested by the author. Which has, among other things, a section on pagination.
The author suggests adding support for both using the Range header and using query string parameters.
Request
Example HTTP header:
Range: items=0-24
Example of query string parameters:
GET http://api.example.com/resources?offset=0&limit=25
Where offset is the starting position number and limit is the maximum number of items to return.
answer
The response must contain a Content-Range header indicating how many items are returned and how many items are still not found.
Examples of HTTP headers:
Content-Range: items 0-24/66
Content-Range: items 40-65/*
There are several other suggestions in the .pdf for more specific cases.
source to share
I believe there is no official "standard" for RESTful web services. But there are many recommendations / implementations from different vendors.
Your first way, using query parameters, will be correct. Different HTTP methods (GET, PUT, DELETE, POST) are used for different kinds of operations. I've never heard of them being used to modify existing operations.
See Wikipedia - REST
source to share