Pagination and HTTP semantics
What you will learn
Pagination and HTTP semantics are part of the public API contract. Stable ordering, bounded query parameters and meaningful status codes matter more than framework convenience.
- Implement bounded pagination with a deterministic tie breaker.
- Distinguish safe and idempotent methods and media negotiation.
- Compare OpenAPI documentation, MockMvc and live HTTP tests.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. MVC examples require the separate pinned companion Maven project. Their predicted results are not execution evidence.
Stable ordering across equal names
import java.util.*;final class InventoryStore { private record Entry(String sku, String name, int quantity, String internalNote) {} public record Item(String sku, String name, int quantity) {} public record Page(List<Item> items, int page, int size, int total) { public Page { items = List.copyOf(items); } } public static final class Missing extends RuntimeException { private static final long serialVersionUID = 1L; } public static final class Conflict extends RuntimeException { private static final long serialVersionUID = 1L; } private final Map<String, Entry> entries = new TreeMap<>(); public InventoryStore() { create("A1", "Notebook", 5); create("B2", "Pencil", 8); create("C3", "Notebook", 2); } private static Item dto(Entry e) { return new Item(e.sku(), e.name(), e.quantity()); } public synchronized Item get(String sku) { Entry e = entries.get(sku); if (e == null) throw new Missing(); return dto(e); } public synchronized Item create(String sku, String name, int quantity) { if (sku == null || !sku.matches("[A-Z0-9]{1,12}") || name == null || name.isBlank() || name.length() > 80 || quantity < 0 || quantity > 10000) throw new IllegalArgumentException("Invalid item"); if (entries.containsKey(sku)) throw new Conflict(); Entry e = new Entry(sku, name, quantity, "warehouse-only"); entries.put(sku, e); return dto(e); } public synchronized Page page(int page, int size, String sort) { if (page < 0 || page > 10000 || size < 1 || size > 100) throw new IllegalArgumentException("Invalid page"); Comparator<Item> order = switch (sort) { case "sku" -> Comparator.comparing(Item::sku); case "name" -> Comparator.comparing(Item::name).thenComparing(Item::sku); default -> throw new IllegalArgumentException("Invalid sort"); }; List<Item> all = entries.values().stream().map(InventoryStore::dto).sorted(order).toList(); int from = Math.min(all.size(), page * size); int to = Math.min(all.size(), from + size); return new Page(all.subList(from, to), page, size, all.size()); }}
public class Main { public static void main(String[] args) {var store = new InventoryStore();System.out.println(store.page(0, 2, "name").items().stream().map(InventoryStore.Item::sku).toList());System.out.println(store.page(1, 2, "name").items().stream().map(InventoryStore.Item::sku).toList());} }Expected output:
[A1, C3][B2]The SKU tie breaker orders the two Notebook items deterministically.
Page policy
This API uses zero-based page numbers, size 1–100, and page at most 10000. It sorts by sku or name then sku, bounds multiplication by the validation limits, clamps an offset beyond the end, and returns a snapshot. Empty pages are valid. A stable tie breaker prevents arbitrary order among equal names but concurrent changes between requests can still shift offset pages; cursor pagination is an alternative. An allowlist of sort keys avoids arbitrary expressions. Do not fetch an entire database just to slice it; the small in-memory list is instructional.
HTTP and versioning
GET is safe and idempotent in intent; PUT and DELETE are idempotent in intent, not guaranteed to return identical status on repeats. POST generally is not idempotent; the sample duplicate returns 409. PATCH is not inherently idempotent. 204 has no response content. Use explicit /api/v1 paths here; header versioning is another approach. Content negotiation may produce 406; unsupported body media can produce 415. OpenAPI describes the agreed interface, but does not prove implementation behavior. MockMvc exercises MVC without a real listening socket; a separate loopback HTTP run checks transport and server integration.
Page boundaries and validation
import java.util.*;final class InventoryStore { private record Entry(String sku, String name, int quantity, String internalNote) {} public record Item(String sku, String name, int quantity) {} public record Page(List<Item> items, int page, int size, int total) { public Page { items = List.copyOf(items); } } public static final class Missing extends RuntimeException { private static final long serialVersionUID = 1L; } public static final class Conflict extends RuntimeException { private static final long serialVersionUID = 1L; } private final Map<String, Entry> entries = new TreeMap<>(); public InventoryStore() { create("A1", "Notebook", 5); create("B2", "Pencil", 8); create("C3", "Notebook", 2); } private static Item dto(Entry e) { return new Item(e.sku(), e.name(), e.quantity()); } public synchronized Item get(String sku) { Entry e = entries.get(sku); if (e == null) throw new Missing(); return dto(e); } public synchronized Item create(String sku, String name, int quantity) { if (sku == null || !sku.matches("[A-Z0-9]{1,12}") || name == null || name.isBlank() || name.length() > 80 || quantity < 0 || quantity > 10000) throw new IllegalArgumentException("Invalid item"); if (entries.containsKey(sku)) throw new Conflict(); Entry e = new Entry(sku, name, quantity, "warehouse-only"); entries.put(sku, e); return dto(e); } public synchronized Page page(int page, int size, String sort) { if (page < 0 || page > 10000 || size < 1 || size > 100) throw new IllegalArgumentException("Invalid page"); Comparator<Item> order = switch (sort) { case "sku" -> Comparator.comparing(Item::sku); case "name" -> Comparator.comparing(Item::name).thenComparing(Item::sku); default -> throw new IllegalArgumentException("Invalid sort"); }; List<Item> all = entries.values().stream().map(InventoryStore::dto).sorted(order).toList(); int from = Math.min(all.size(), page * size); int to = Math.min(all.size(), from + size); return new Page(all.subList(from, to), page, size, all.size()); }}
public class Main { public static void main(String[] args) {var store = new InventoryStore();System.out.println(store.page(10000, 100, "sku").items().size());try { store.page(0, 101, "sku"); } catch (IllegalArgumentException e) { System.out.println("invalid size"); }try { store.page(0, 2, "price"); } catch (IllegalArgumentException e) { System.out.println("invalid sort"); }} }Expected output:
0invalid sizeinvalid sortA far offset yields an empty snapshot; unsupported size and sort are rejected before work.
Contract tests with MockMvc
Source-reviewed, NOT RUN. File lab-fixtures/mvc-v39/src/test/java/example/inventory/InventoryContractTest.java; use the companion lab README.
package example.inventory;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.annotation.DirtiesContext;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;@SpringBootTest@AutoConfigureMockMvc@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)class InventoryContractTest { @Autowired MockMvc mvc; @Test void readAndPage() throws Exception { mvc.perform(get("/api/v1/items/A1").accept("application/json")) .andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith("application/json")) .andExpect(jsonPath("$.sku").value("A1")).andExpect(jsonPath("$.internalNote").doesNotExist()); mvc.perform(get("/api/v1/items?size=2&sort=name")) .andExpect(status().isOk()).andExpect(jsonPath("$.items[1].sku").value("C3")); } @Test void errors() throws Exception { mvc.perform(get("/api/v1/items/Z9")).andExpect(status().isNotFound()) .andExpect(content().contentTypeCompatibleWith("application/problem+json")) .andExpect(jsonPath("$.status").value(404)); mvc.perform(post("/api/v1/items").contentType("application/json").content("{\"sku\":\"Z8\",\"name\":\"Pen\"}")) .andExpect(status().isBadRequest()); mvc.perform(get("/api/v1/items?size=101")).andExpect(status().isBadRequest()); mvc.perform(post("/api/v1/items").contentType("text/plain").content("bad")).andExpect(status().isUnsupportedMediaType()); mvc.perform(get("/api/v1/items/A1").accept("image/png")).andExpect(status().isNotAcceptable()); } @Test void createThenConflict() throws Exception { String body = "{\"sku\":\"D4\",\"name\":\"Eraser\",\"quantity\":3}"; mvc.perform(post("/api/v1/items").contentType("application/json").content(body)) .andExpect(status().isCreated()).andExpect(header().string("Location", "/api/v1/items/D4")); mvc.perform(post("/api/v1/items").contentType("application/json").content(body)) .andExpect(status().isConflict()).andExpect(jsonPath("$.status").value(409)); }}Predicted behavior: Selected success, error, media and Location assertions pass when executed.
The full context is used with MockMvc, not a real server. Restart between live runs to reset state.
Machine-readable API contract
Source-reviewed, NOT RUN. File lab-fixtures/mvc-v39/openapi.json; use the companion lab README.
{ "openapi": "3.1.1", "info": { "title": "Inventory teaching API", "version": "1.0.0" }, "servers": [ { "url": "http://127.0.0.1:18081" } ], "paths": { "/api/v1/items": { "get": { "parameters": [ { "name": "page", "in": "query", "schema": { "type": "integer", "minimum": 0, "maximum": 10000, "default": 0 } }, { "name": "size", "in": "query", "schema": { "type": "integer", "minimum": 1, "maximum": 100, "default": 20 } }, { "name": "sort", "in": "query", "schema": { "type": "string", "enum": [ "sku", "name" ], "default": "sku" } } ], "responses": { "200": { "description": "Page", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Page" } } } }, "400": { "description": "Invalid query", "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/Problem" } } } }, "406": { "description": "Not acceptable" } } }, "post": { "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item" } } } }, "responses": { "201": { "description": "Created", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item" } } }, "headers": { "Location": { "schema": { "type": "string" } } } }, "400": { "description": "Invalid body", "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/Problem" } } } }, "406": { "description": "Not acceptable" }, "409": { "description": "Duplicate SKU", "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/Problem" } } } }, "415": { "description": "Unsupported media type" } } } }, "/api/v1/items/{sku}": { "get": { "parameters": [ { "name": "sku", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "description": "Found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item" } } } }, "404": { "description": "Missing", "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/Problem" } } } }, "406": { "description": "Not acceptable" } } } } }, "components": { "schemas": { "Item": { "type": "object", "required": [ "sku", "name", "quantity" ], "properties": { "sku": { "type": "string", "pattern": "^[A-Z0-9]{1,12}$" }, "name": { "type": "string", "minLength": 1, "maxLength": 80 }, "quantity": { "type": "integer", "minimum": 0, "maximum": 10000 } } }, "Page": { "type": "object", "required": [ "items", "page", "size", "total" ], "properties": { "items": { "type": "array", "items": { "$ref": "#/components/schemas/Item" } }, "page": { "type": "integer" }, "size": { "type": "integer" }, "total": { "type": "integer" } } }, "Problem": { "type": "object", "properties": { "type": { "type": "string" }, "title": { "type": "string" }, "status": { "type": "integer" }, "detail": { "type": "string" }, "instance": { "type": "string" } } } } }}Predicted behavior: A client can inspect documented paths and schemas.
This hand-authored contract needs OpenAPI schema validation and live contract checks; it is not generated from the controller.
Common mistakes
Do not expose an unlimited size, accept arbitrary sort expressions, assume offset pages are consistent under writes, or claim a documented contract is tested merely because JSON parses.
Practice
Fetch page 1 of size 2 sorted by sku, print the SKUs and total; then confirm page 2 is empty.
Expected output:
[C3]3trueCompare with the manual review criteria.
Official reading: HTTP · OpenAPI · Tests · Dependencies. MVC execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Pagination and HTTP semantics — knowledge check
REST API engineering and HTTP contract reasoning.
Why sort by name and then SKU?
What is the intended effect of an idempotent method?
What does MockMvc not establish by itself?
What does an OpenAPI document establish alone?
What should a page past the end return here?