Versioning and Pagination

Harry · 11 Sep 2026 · 14 views

Versioning and Pagination

As your API evolves, you need versioning to avoid breaking existing clients. And as your data grows, you need pagination to avoid overwhelming clients with massive responses.

API Versioning Strategies

There are four common approaches to versioning. Each has trade-offs.

# URL path versioning (most common)
GET /api/v1/products
GET /api/v2/products

# Query parameter versioning
GET /api/products?version=2

# Header versioning
GET /api/products
Accept: application/vnd.myapi.v2+json

# Content negotiation versioning
GET /api/products
API-Version: 2

URL path versioning is the most visible and easiest to test. Most public APIs use it. Spring Boot supports it naturally:

@RestController
@RequestMapping("/api/v1/products")
public class ProductV1Controller { ... }

@RestController
@RequestMapping("/api/v2/products")
public class ProductV2Controller { ... }

Pagination Basics

Never return all records at once. Use page-based or cursor-based pagination:

@GetMapping
public Page<Product> getAll(
        @RequestParam(defaultValue = "0") int page,
        @RequestParam(defaultValue = "20") int size) {
    return productService.findAll(PageRequest.of(page, size));
}

The response includes metadata:

{
  "content": [{"id": 1, "name": "Widget"}, ...],
  "page": 0,
  "size": 20,
  "totalElements": 156,
  "totalPages": 8
}

Cursor-Based Pagination

For large datasets, cursor-based pagination is more efficient. Instead of offset, use the last item ID as a cursor:

GET /api/products?cursor=42&limit=20

This avoids the performance penalty of OFFSET in SQL queries on large tables.

Sorting

Add a sort parameter for flexibility:

GET /api/products?sort=price,asc
GET /api/products?sort=-createdAt

Key Points

  • URL path versioning (/v1/, /v2/) is the most common approach.
  • Always paginate large collections using page or cursor-based approaches.
  • Spring Data PageRequest provides built-in pagination support.
  • Cursor-based pagination is more efficient for very large datasets.
  • Include pagination metadata (total, page, size) in every paginated response.
Share this post:

Comments (0)

Please login or register to comment.