AI Hints
Home›Spring Boot Tutorial›PATCH, Filtering with Query Parameters and Pagination in the API
Spring Boot · Lesson 87 of 120

Pagination in the API

?page=0&size=20.

⏱ 2 min read▶ Video at 1:55:49🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

We met Page and Pageable in the repository. Now let's let clients choose the page, the size, and the order, right from the URL.

  • Page and Pageable
  • Chosen by the client
  • From the URL

Pageable from the URL

A Pageable parameter in a controller is filled from the URL automatically. Page picks the page, starting at zero. Size picks how many per page. And sort picks the order, like price comma desc.

keyvalue
page0, 1, 2 ...
sizeitems per page
sortprice,desc
Defaultpage 0, size 20

A page response

Returning a Page directly gives messy JSON, so we use our own record. It holds the items, the page number, the size, and the totals. Of copies them from a Page.

PageResponse.javajava
public record PageResponse<T>(List<T> items, int page, int size, long total, int pages) {

    static <T> PageResponse<T> of(Page<T> p) {
        return new PageResponse<>(p.getContent(), p.getNumber(), p.getSize(),
                                  p.getTotalElements(), p.getTotalPages());
    }
}

Paged and sorted

The controller takes a Pageable, and maps each book to a response. We ask for page one, with three books per page, sorted by price, most expensive first. Run it. Page zero would hold the three most expensive books, so page one shows the next three. And the totals say eight books, in three pages.

BookController.javajava
@RestController
public class BookController {

    private final BookRepository books;

    public BookController(BookRepository books) { this.books = books; }

    @GetMapping("/books")
    public PageResponse<BookResponse> list(Pageable pageable) {
        return PageResponse.of(books.findAll(pageable).map(BookResponse::from));
    }
}
Output
{
  "items":[
    {"id":5,"title":"Song of Achilles","author":"Madeline Miller","price":9.49},
    {"id":2,"title":"The Hobbit","author":"J.R.R. Tolkien","price":8.99},
    {"id":4,"title":"Children of Dune","author":"Frank Herbert","price":8.49}
  ],
  "page":1,
  "size":3,
  "total":8,
  "pages":3
}
Also uses Book.java
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String author;
    private double price;

    protected Book() {}
    public Book(String title, String author, double price) {
        this.title = title; this.author = author; this.price = price;
    }
    public Long getId() { return id; }
    public String getTitle() { return title; }
    public String getAuthor() { return author; }
    public double getPrice() { return price; }
    public void setTitle(String title) { this.title = title; }
    public void setAuthor(String author) { this.author = author; }
    public void setPrice(double price) { this.price = price; }
}
Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {}
Also uses CreateBook.java
public record CreateBook(
    @NotBlank String title,
    @NotBlank String author,
    @Positive double price
) {}
Also uses BookResponse.java
public record BookResponse(Long id, String title, String author, double price) {

    static BookResponse from(Book b) {
        return new BookResponse(b.getId(), b.getTitle(), b.getAuthor(), b.getPrice());
    }
}
Also uses BookNotFoundException.java
@ResponseStatus(HttpStatus.NOT_FOUND)
public class BookNotFoundException extends RuntimeException {
    public BookNotFoundException(long id) { super("Book " + id + " was not found"); }
}
Also uses GlobalErrors.java
@RestControllerAdvice
public class GlobalErrors {

    @ExceptionHandler(BookNotFoundException.class)
    public ProblemDetail notFound(BookNotFoundException ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
    }
}
Also uses data.sql
INSERT INTO book (title, author, price) VALUES
  ('Dune', 'Frank Herbert', 9.99),
  ('The Hobbit', 'J.R.R. Tolkien', 8.99),
  ('Circe', 'Madeline Miller', 10.99),
  ('Children of Dune', 'Frank Herbert', 8.49),
  ('Song of Achilles', 'Madeline Miller', 9.49),
  ('The Fellowship of the Ring', 'J.R.R. Tolkien', 11.99),
  ('Emma', 'Jane Austen', 6.99),
  ('Persuasion', 'Jane Austen', 7.49);
Also uses application.properties
spring.jpa.defer-datasource-initialization=true
Also uses PageResponse.java
public record PageResponse<T>(List<T> items, int page, int size, long total, int pages) {

    static <T> PageResponse<T> of(Page<T> p) {
        return new PageResponse<>(p.getContent(), p.getNumber(), p.getSize(),
                                  p.getTotalElements(), p.getTotalPages());
    }
}
Also uses _curl.sh
curl "localhost:8080/books?page=1&size=3&sort=price,desc"

Summary

A Pageable parameter reads page, size, and sort from the URL. Wrap the result in your own page record. Next, API versioning.

Key takeaways
  • ?page=0&size=2
  • &sort=price,desc
  • PageResponse record
Next up: API Versioning — change without breaking