Spring Boot
pagination
configuration
Java
software development

How to configure Spring boot pagination starting from page 1, not 0

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Spring Data pagination is zero-based by default, so page index 0 means the first page. Many APIs prefer one-based paging for client ergonomics. You can support one-based requests cleanly by translating incoming values while keeping repository internals unchanged.

Core Sections

Understand Spring Data Defaults

PageRequest.of(page, size) expects page starting at zero. If clients send page 1 for first page, you need a conversion step.

java
PageRequest.of(0, 20); // first page
PageRequest.of(1, 20); // second page

Changing this behavior globally requires careful API boundary handling.

Convert Request Parameters Explicitly

A common approach is subtracting one in controller logic and clamping at zero.

java
1@GetMapping("/users")
2public Page<UserDto> listUsers(
3        @RequestParam(defaultValue = "1") int page,
4        @RequestParam(defaultValue = "20") int size) {
5
6    int internalPage = Math.max(page - 1, 0);
7    Pageable pageable = PageRequest.of(internalPage, size, Sort.by("id").descending());
8    return userService.findAll(pageable);
9}

This keeps one-based API semantics while preserving Spring internals.

Return Pagination Metadata in One-based Form

If request uses one-based indexing, response metadata should match to avoid confusion.

java
1public record PageResponse<T>(
2        List<T> items,
3        int page,
4        int size,
5        long totalElements,
6        int totalPages
7) {}
8
9public PageResponse<UserDto> toResponse(Page<UserDto> pageData) {
10    return new PageResponse<>(
11            pageData.getContent(),
12            pageData.getNumber() + 1,
13            pageData.getSize(),
14            pageData.getTotalElements(),
15            pageData.getTotalPages()
16    );
17}

Consistent request and response conventions reduce client-side bugs.

Configure Argument Resolver Option

Spring can accept one-indexed pageable parameters through resolver customization.

java
1@Configuration
2public class WebConfig implements WebMvcConfigurer {
3    @Override
4    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
5        PageableHandlerMethodArgumentResolver r = new PageableHandlerMethodArgumentResolver();
6        r.setOneIndexedParameters(true);
7        r.setMaxPageSize(200);
8        resolvers.add(r);
9    }
10}

If you use this path, verify behavior across all endpoints using Pageable directly.

Validate Inputs and Edge Cases

Reject or normalize invalid values such as negative page numbers or oversized page size.

java
int safePage = Math.max(requestedPage, 1);
int safeSize = Math.min(Math.max(requestedSize, 1), 100);

Defensive boundaries protect database performance and avoid unexpected empty-page responses.

Testing Strategy

Write integration tests for first page, middle page, last page, and out-of-range cases. Include tests that assert one-based values in API responses. These tests prevent regressions if resolver configuration changes.

Design Consistent API Contracts Across Services

If multiple services expose pagination, standardize request and response fields such as page, size, and totalPages. Inconsistent indexing conventions across services create subtle client bugs and duplicate adapter code. A shared pagination contract document and validation tests can prevent drift.

When using generated API clients, define one-based behavior in your OpenAPI specification so SDKs communicate expectations clearly. Include examples showing first and second page requests to remove ambiguity.

yaml
1parameters:
2  - in: query
3    name: page
4    schema:
5      type: integer
6      minimum: 1
7    example: 1

Even with global resolver settings, keeping boundary conversion logic explicit in code reviews helps avoid accidental behavior changes during framework upgrades.

In distributed systems, consistent pagination semantics should be treated as part of compatibility policy. Documenting this in API governance prevents accidental breaking changes during refactors.

Contract tests in CI should assert first-page and last-page semantics explicitly for every paginated endpoint.

A single shared pagination helper module across controllers can enforce boundaries and default values consistently, which reduces copy-paste bugs and keeps behavior predictable during maintenance.

This approach also simplifies API client generation and documentation maintenance.

Common Pitfalls

  • Subtracting one in some endpoints but not others, causing inconsistent API behavior.
  • Returning zero-based page numbers in responses while accepting one-based requests.
  • Allowing very large page sizes that degrade query performance.
  • Forgetting to clamp invalid client values.
  • Assuming resolver settings apply identically in every Spring Boot setup without tests.

Summary

  • Spring repositories are zero-based; client-facing APIs can still be one-based.
  • Translate page parameters at boundaries or configure resolver behavior globally.
  • Keep response metadata aligned with request indexing semantics.
  • Validate page and size inputs defensively.
  • Cover paging contracts with integration tests.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.