Exposing page and sort in REST endpoints
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A mobile app asks ShopLite for page 3 of the products, twenty at a time, cheapest first. Someone else asks for size=100000. The endpoint must serve the first request and protect the server from the second.
A Pageable controller parameter: ?page=0&size=20&sort=price,desc
A Pageable controller parameter is filled by Spring Data's web support from three query parameters: page (from 0), size and sort. sort=price,desc means by price, highest first; repeat sort for more fields.
GET /api/v1/products?page=0&size=20&sort=price,desc reaches the controller as one Pageable argument.
Example 1 · src/main/java/com/shoplite/product/ProductController.java
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
package com.shoplite.product;
import org.springframework.data.domain.Page;import org.springframework.data.domain.Pageable;import org.springframework.data.domain.Sort;import org.springframework.data.web.PageableDefault;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;
import com.shoplite.common.web.PageResponse;
@RestController@RequestMapping("/api/v1")class ProductController {
private final ProductService service;
ProductController(ProductService service) { this.service = service; }
// Returns Spring's Page as it is: the JSON shape belongs to Spring, not to us @GetMapping("/lab/products-page") Page<ProductResponse> rawPage(Pageable pageable) { return service.list(pageable); }
// Returns our own envelope; without ?sort=... the list is sorted by id @GetMapping("/products") PageResponse<ProductResponse> list(@PageableDefault(size = 20, sort = "id") Pageable pageable) { return PageResponse.from(service.list(pageable)); }
// Practice: deals screen, 5 cards per page, most expensive first unless the client sorts @GetMapping("/lab/cards") PageResponse<ProductCard> cards( @PageableDefault(size = 5, sort = "price", direction = Sort.Direction.DESC) Pageable pageable) { return PageResponse.from(service.cards(pageable)); }}(no output: Examples 2 to 4 call these endpoints)
What this code does
listtakes aPageablewith@PageableDefault(size = 20, sort = "id")and returns the recordPageResponse<ProductResponse>.rawPagereturns Spring'sPageas it is, only to show the JSON problem in Example 4.cardsis used in the practice tasks: a smaller DTO, 5 per page, most expensive first by default.
Example 2 · page, size and sort from the URL
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
curl -i "http://localhost:8080/api/v1/products?size=2"curl -i "http://localhost:8080/api/v1/products?page=1&size=2&sort=price,desc"curl -i "http://localhost:8080/api/v1/products?size=2&sort=stock&sort=name,desc"$ curl -i "http://localhost:8080/api/v1/products?size=2"
HTTP/1.1 200
Content-Type: application/json
{"content":[{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true},{"id":2,"sku":"MOB-GM35","name":"Samsung Galaxy M35","categoryId":2,"categoryName":"Mobiles","price":19999.00,"stock":25,"isActive":true}],"page":0,"size":2,"totalElements":14,"totalPages":7}
$ curl -i "http://localhost:8080/api/v1/products?page=1&size=2&sort=price,desc"
HTTP/1.1 200
Content-Type: application/json
{"content":[{"id":4,"sku":"LAP-IPS3","name":"Lenovo IdeaPad Slim 3","categoryId":3,"categoryName":"Laptops","price":42990.00,"stock":12,"isActive":true},{"id":2,"sku":"MOB-GM35","name":"Samsung Galaxy M35","categoryId":2,"categoryName":"Mobiles","price":19999.00,"stock":25,"isActive":true}],"page":1,"size":2,"totalElements":14,"totalPages":7}
$ curl -i "http://localhost:8080/api/v1/products?size=2&sort=stock&sort=name,desc"
HTTP/1.1 200
Content-Type: application/json
{"content":[{"id":8,"sku":"ACC-M331","name":"Logitech M331 Silent Mouse","categoryId":4,"categoryName":"Accessories","price":849.00,"stock":0,"isActive":true},{"id":5,"sku":"LAP-HPV15","name":"HP Victus 15 Gaming","categoryId":3,"categoryName":"Laptops","price":64990.00,"stock":5,"isActive":true}],"page":0,"size":2,"totalElements":14,"totalPages":7}What this code does
- Without
sort, the default from@PageableDefaultapplies: by id. 14 active products in pages of 2 make 7 pages. page=1&size=2&sort=price,descis the second page of the most expensive products: the Lenovo laptop and the Samsung phone.- Two
sortparameters sort by stock first (the out-of-stock mouse leads), then by name Z to A for equal stock.
Spring Boot switches this support on as soon as Spring Data and Spring MVC are both on the classpath. The controller passes the Pageable to the service, and the service passes it to the repository: the same PageRequest you built by hand in the earlier lessons now comes from the URL.
The sort names in the URL are entity property names (price, name), not column names. Whatever the client types goes into the ORDER BY, which is why the next sections add limits and an allow-list.
Limits: @PageableDefault and max-page-size
@PageableDefault(size = 20, sort = "id") sets the page size and sort order used when the client sends none. The property spring.data.web.pageable.max-page-size caps the size a client may ask for.
Without limits, the client chooses its own size. Example 3 shows what Spring does with a size that is too big, zero or negative.
Example 3 · max-page-size and the silent fixes
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
# src/main/resources/application-web.properties (the lab's web profile)spring.data.web.pageable.max-page-size=100curl -s "http://localhost:8080/api/v1/products?size=500" | jq -c "{page, size, totalElements, totalPages}"curl -s "http://localhost:8080/api/v1/products?size=0" | jq -c "{page, size, totalElements, totalPages}"curl -s "http://localhost:8080/api/v1/products?page=-1&size=2" | jq -c "{page, size, totalElements, totalPages}"curl -s "http://localhost:8080/api/v1/products?page=abc&size=2" | jq -c "{page, size, totalElements, totalPages}"curl -i "http://localhost:8080/api/v1/products?size=2&sort=cost"$ curl -s "http://localhost:8080/api/v1/products?size=500" | jq -c "{page, size, totalElements, totalPages}"
{"page":0,"size":100,"totalElements":14,"totalPages":1}
$ curl -s "http://localhost:8080/api/v1/products?size=0" | jq -c "{page, size, totalElements, totalPages}"
{"page":0,"size":20,"totalElements":14,"totalPages":1}
$ curl -s "http://localhost:8080/api/v1/products?page=-1&size=2" | jq -c "{page, size, totalElements, totalPages}"
{"page":0,"size":2,"totalElements":14,"totalPages":7}
$ curl -s "http://localhost:8080/api/v1/products?page=abc&size=2" | jq -c "{page, size, totalElements, totalPages}"
{"page":0,"size":2,"totalElements":14,"totalPages":7}
$ curl -i "http://localhost:8080/api/v1/products?size=2&sort=cost"
HTTP/1.1 500
Content-Type: application/json
{"timestamp":"2026-10-16T08:05:54.401Z","status":500,"error":"Internal Server Error","path":"/api/v1/products"}What this code does
- With
max-page-size=100,size=500comes back as a page of 100.size=0uses the default 20;page=-1andpage=abcbecome page 0. Every call answers 200. jq -c "{page, size, totalElements, totalPages}"keeps only the page fields of the long JSON so the change is easy to see.sort=costis not a property ofProduct, so Hibernate fails and the client gets a 500 from Spring Boot's default error page (the timestamp differs on every run).
Spring Boot's default cap is 2000, far too big for a phone screen and a risk for the server; spring.data.web.pageable.default-page-size (default 20) sets the size globally. The web support is lenient: size=500 quietly becomes 100, size=0 becomes 20, and page=-1 and page=abc both become page 0. The client gets a 200 with a page it did not ask for and cannot tell anything was changed.
Sort fields are not checked at all. sort=cost reaches Hibernate, which fails with UnknownPathException: Could not resolve attribute 'cost', and the client gets a 500 for its own typo. The ShopLite contract wants a 400 instead, and "never silently clamped" for size: the last section shows how.
A stable JSON shape: VIA_DTO or your own PageResponse
PageResponse is ShopLite's own page envelope: a small record with content, page, size, totalElements and totalPages, and a from(Page) method. Its JSON changes only when you change the record, not when Spring does.
Returning Page<T> straight from a controller writes Spring's internal class as JSON. Example 4 shows that shape, then a fixed one.
Example 4 · Returning Page directly, then with VIA_DTO
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
curl -s "http://localhost:8080/api/v1/lab/products-page?size=2"# src/main/java/com/shoplite/common/web/ViaDtoConfig.java switches the page format# @EnableSpringDataWebSupport(pageSerializationMode = PageSerializationMode.VIA_DTO)java -jar target/page-lab-0.1.0.jar --spring.profiles.active=web --lab.via-dto=truecurl -s "http://localhost:8080/api/v1/lab/products-page?size=2"$ curl -i "http://localhost:8080/api/v1/lab/products-page?size=2"
HTTP/1.1 200
Content-Type: application/json
{"content":[{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true},{"id":2,"sku":"MOB-GM35","name":"Samsung Galaxy M35","categoryId":2,"categoryName":"Mobiles","price":19999.00,"stock":25,"isActive":true}],"empty":false,"first":true,"last":false,"number":0,"numberOfElements":2,"pageable":{"offset":0,"pageNumber":0,"pageSize":2,"paged":true,"sort":{"empty":true,"sorted":false,"unsorted":true},"unpaged":false},"size":2,"sort":{"empty":true,"sorted":false,"unsorted":true},"totalElements":14,"totalPages":7}
(server log)
WARN o.s.d.w.c.SpringDataJackson3Configuration$PageModule$WarningLoggingModifier : Serializing PageImpl instances as-is is not supported, meaning that there is no guarantee about the stability of the resulting JSON structure!
For a stable JSON structure, please use Spring Data's PagedModel (globally via @EnableSpringDataWebSupport(pageSerializationMode = VIA_DTO))
or Spring HATEOAS and Spring Data's PagedResourcesAssembler as documented in https://docs.spring.io/spring-data/commons/reference/repositories/core-extensions.html#core.web.pageables.
(again, started with --lab.via-dto=true)
$ curl -s "http://localhost:8080/api/v1/lab/products-page?size=2"
{"content":[{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true},{"id":2,"sku":"MOB-GM35","name":"Samsung Galaxy M35","categoryId":2,"categoryName":"Mobiles","price":19999.00,"stock":25,"isActive":true}],"page":{"size":2,"number":0,"totalElements":14,"totalPages":7}}What this code does
- The direct
PageImplJSON haspageable, twosortobjects,numberOfElementsand more: about 590 bytes for two products, and a shape Spring does not promise to keep. - Spring Data logs the warning once, naming the two fixes: VIA_DTO or Spring HATEOAS.
- With VIA_DTO the same endpoint returns
contentplus apageobject. The lab'sViaDtoConfigonly turns it on whenlab.via-dto=trueis set.
Example 5 · src/main/java/com/shoplite/common/web/PageResponse.java
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
package com.shoplite.common.web;
import java.util.List;
import org.springframework.data.domain.Page;
/** The page envelope of the ShopLite contract. Our own type, so its JSON never changes by accident. */public record PageResponse<T>(List<T> content, int page, int size, long totalElements, int totalPages) {
public static <T> PageResponse<T> from(Page<T> page) { return new PageResponse<>(page.getContent(), page.getNumber(), page.getSize(), page.getTotalElements(), page.getTotalPages()); }}(no output: Example 2 shows the JSON it produces)
What this code does
- Five fields in the contract's order; Jackson writes a record's components in that order.
from(Page)copies the rows and the four numbers. It works for anyT, so products, customers and orders share it.- Spring's
Pagestays inside the server; clients see only this record.
That PageImpl JSON (content, pageable, sort, numberOfElements, empty and more) is not a promise: Spring Data logs a warning on the first such response, and its fields have changed between versions. @EnableSpringDataWebSupport(pageSerializationMode = VIA_DTO), or the property spring.data.web.pageable.serialization-mode=via-dto, sends Spring's PagedModel instead: content plus a page object with size, number, totalElements and totalPages. That is stable, but still Spring's format.
The ShopLite contract fixes its own envelope, so the controller returns PageResponse<ProductResponse> instead of Page.
Mapping Page<Product> to Page<ProductResponse> with page.map
page.map(function) turns a Page<Product> into a Page<ProductResponse>: every entity goes through the function, while the page number, size and totals stay the same.
Map each entity to a response record in the service, so the controller never sees an entity.
@Transactional(readOnly = true)public Page<ProductResponse> list(Pageable pageable) { return products.findActiveWithCategory(pageable) // Page<Product>, inside the transaction .map(ProductResponse::from); // Page<ProductResponse>: same totals, new rows}Call map in the service, inside the read-only transaction, so lazy fields such as the category name can still load.
If ProductController returned Page<Product>, Jackson would serialize the entity after the transaction ended, try to read the lazy category, and fail with a LazyInitializationException (with open-in-view off), or expose every column of the table.
Fix the error
Fix the controller
Read the real error, then pick the line that fixes it.
Round 1 of 2
The controller returns the entity page; the category is lazy.
Error
LazyInitializationException: could not initialize proxy [Category#2] - no Session
The ShopLite way: validated page, size and sort, with real curl output
Validated paging parameters are plain @RequestParam values with Bean Validation rules: page at least 0, size from 1 to 100, and sort matching an allow-list pattern. Wrong values come back as one 400 validation-failed problem.
ShopLite's lists check page, size and sort themselves, so a bad value gets a 400, not a silent fix. Example 6 shows the real responses.
Example 6 · ShopLite's validated parameters: GET /api/v1/customers
Runs in: the shoplite-api Spring Boot project
curl -i "http://localhost:8080/api/v1/customers?size=500&sort=password"curl -i "http://localhost:8080/api/v1/customers?page=-1"curl -i "http://localhost:8080/api/v1/customers?size=2&sort=createdAt,desc"$ curl -i "http://localhost:8080/api/v1/customers?size=500&sort=password"
HTTP/1.1 400
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/validation-failed","title":"Validation failed","status":400,"detail":"The request has 2 invalid fields.","instance":"/api/v1/customers","errors":[{"field":"size","message":"must be between 1 and 100"},{"field":"sort","message":"must be one of id, fullName, createdAt"}]}
$ curl -i "http://localhost:8080/api/v1/customers?page=-1"
HTTP/1.1 400
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/validation-failed","title":"Validation failed","status":400,"detail":"The request has 1 invalid field.","instance":"/api/v1/customers","errors":[{"field":"page","message":"must be 0 or more"}]}
$ curl -i "http://localhost:8080/api/v1/customers?size=2&sort=createdAt,desc"
HTTP/1.1 200
Content-Type: application/json
{"content":[{"id":8,"fullName":"Imran Khan","email":"imran.khan@example.com","phone":"9876543208","createdAt":"2026-09-01T08:10:00+05:30"},{"id":7,"fullName":"Divya Nair","email":"divya.nair@example.com","phone":"9876543207","createdAt":"2026-08-14T16:45:00+05:30"}],"page":0,"size":2,"totalElements":8,"totalPages":4}What this code does
CustomerController.listdeclares@Min(0) int page,@Min(1) @Max(100) int sizeand a@Patternallow-list onsort, as in the snippet in the Summary.- Both broken parameters come back in one
validation-failedproblem, in the contract's ProblemDetail format; nothing reaches the database. - A valid sort works as before: the two newest customers first, 8 customers in 4 pages.
The service turns the checked values into a PageRequest with an id tiebreaker. The 400 lists every bad parameter at once: Example 6 shows two broken parameters together, a negative page, and a valid request sorted by createdAt,desc.
A Pageable parameter with @PageableDefault is fine for internal or admin screens where silent fixes do no harm. For a public API, validate.
Next step
Check your understanding
11 quick questions