Last updated: 2024-06-25
Pagination in a Spring Boot REST API
Spring Boot provides many features to support Pagination natively. What steps are necessary to provide an endpoint with pagination as REST API in our application?
As of Spring version 3.3
, a class PagedModel
is available to enable the serialization of a page in the API. The last section describes the old approach providing our own implementation.
Adding pagination to our application
First, we want to add pagination to our Spring Boot application. To do this, we first create an endpoint in our @RestController
and add a parameter of type Pageable
there.
Example RestController with an endpoint supporting pagination
The query parameters "page", "size" and "sort" are automatically bound to the pageable object by Spring Boot. Default values can be specified by adding annotations or adjusting certain application properties.
The called service loads the requested page from the repository and maps the entities to DTOs.
Example intermediate Service
Since our repository extends JpaRepository
, we can pass our pageable object directly to the findAll()
method. The repository will return an object of type Page
containing the requested page and its content.
Our repository providing paged access by default
Configuration and usage of PagedModel
However, if we execute our application without any further configuration, we will get the following log warning.
The class PageImpl
is not intended to be serialized and returned by a REST API. For this purpose, a class PagedModel
is provided in the spring-data-commons
library. This dependency should be integrated for this purpose - it is automatically included if, for example, we have already integrated a database with Spring Data.
To remove the warning and serialize the PageImpl
class properly, we just have to add the following annotation to one of our configs.
Enabling automatic mappings
This provides a converter that automatically transforms every PageImpl
object to PagedModel
. In a setup with HATEOAS, the spring-data-hateoas
library provides its own PagedModel
class, which can be created via the PagedResourcesAssembler
.
The SimplePage class with full Jackson support
In older Spring versions, a separate implementation of PageImpl
had to be provided. This simplifies the JSON structure and supports serialization at the same time. The constructor is necessary so that Jackson can initialize the class from an input string.
The SimplePage class
Bootify helps you to create the first version of your next Spring Boot application including database schema and REST API. Pagination for the REST endpoints is available in the Professional plan, which also includes generation of integration tests for the REST API using Testcontainers.