Getting Started With REST Pagination - Spring Boot

 


When you have a large set of data returned as your response, it's not the best practice to serve the bulk data at once as the response, data may contains hundred thousands of records and it may cause your server or the frontend crash. Pagination comes in to the picture to handle serving bulk responses, instead of serving the response at once it will serve the response by pages meaning we can define how many records we needs for a page (page size) and the page number.  We are going to build a response like below. Let's get started.


 {

   "totalItems": 100,

   "totalPages": 2,

   "page": 0,

   "size": 50,

   "students": [

      "-----"

   ]

}


Project Structure and setup.


Clone the project from - https://github.com/Rajithkonara/spring-boot-pagination

I have used a mysql database to fetch data for the API, we can either set up mysql locally or use docker. I have use docker, docker-compose file can be found in the project. Also you will need to update the application.yml configurations accordingly.  Once mysql is up and running and all your configuration in place, run the project.


Generate Data.


To generate dummy data I have used the javafaker library, once you started the application send a GET request to http://localhost:8080/api/v1/all endpoint.


Classes.


Spring boot by default supports pagination, all we need to do is pass a pageable to the repository method, spring will handle the pagination for us.


StudentRepository - This is our class use to access our data from mysql database.


StudentService -  Here we access the repository class and return data as a Page.


public Page<Student> getStudentPage(Pageable pageable) {
return studentRepository.findAll(pageable);
}


PageResponse - Class to map the paging details.


StudentResponse - Response class used as the API response. (Paging data with the response data)

StudentController - Here for the students endpoint we are passing the page and size as query parameters, page represent the current page and size represent the amount of data should be in the page. Request URL will be


Above request will return the 1'st page with each 50 elements per page.

In the student database we have 100 records, Let's send a request to students endpoint and get the first 10 records.



According to the response, we have received totalItems: 100 which equals to the total number of records in the database, totalPages: 10 since we requested 10 items per page it have total of 10 pages, page: 0 is the first page and the size: 10 is the number of students records per page. 
Play with the request by changing the query parameters and observe the response behavior. Please refer the official documentation you can do more with paging like sorting and filtering.

Reference: 

Comments