Pagination and Sorting in Spring Boot REST APIs

When your API deals with large datasets — like fetching thousands of users or records — loading everything at once is inefficient. That’s where pagination and sorting come in. They help limit the data sent to the client while giving control over how data is retrieved and displayed.

In this post, you’ll learn how to:

  • Add pagination and sorting in Spring Boot to a REST API
  • Use Spring Data’s Pageable and Sort
  • Customize response structure for frontend consumption
Pagination and Sorting in Spring Boot REST APIs

⚙️ Basic Setup

We’ll build a simple API to demonstrate paginated and sorted retrieval of User entities.

✅ Dependencies

Ensure you have Spring Data JPA and Web in your pom.xml:

📦 Entity & Repository

✅ User Entity

✅ User Repository

🔄 Implement Pagination & Sorting

Spring Data JPA automatically supports Pageable and Sort.

✅ Service Layer

🚀 REST Controller

🔍 Test via Postman or Browser

Try the following URL:


GET http://localhost:8080/api/users?page=0&size=5&sort=name,asc

This retrieves the first page, with 5 users, sorted by name in ascending order.

🧾 Custom Page Response DTO (Optional)

Instead of returning Page directly, wrap it for better frontend readability:

And map it in controller:

Sorting by Multiple Fields

Spring also supports multi-field sorting:


GET /api/users?sort=name,asc&sort=age,desc

In this case, modify the controller to handle multiple sort[] parameters:

🧠 Best Practices

PracticeDescription
✅ Validate page/size inputsAvoid invalid or excessive sizes
✅ Limit max page sizePrevent performance issues
✅ Default sortingFallback to id or createdAt
✅ Paginate large collectionsNever return entire datasets
✅ Use DTOs instead of EntitiesFor better control and flexibility

📌 Conclusion

Pagination and sorting in Spring Boot are essential features for building scalable REST APIs. With Spring Boot and Spring Data JPA, you can implement them with minimal configuration and maximum flexibility.

Use Pageable and Sort wisely to optimize both user experience and performance of your REST services.

References

Pagination and Sorting docs