API Pagination Test Data: Page, Cursor, and Offset Scenarios
API Pagination Test Data: Page, Cursor, and Offset Scenarios
When an API returns a collection, the contract usually includes a pagination mechanism. The three most common styles—page‑based, cursor‑based, and offset/limit—behave differently under load, with filters, and when the underlying data changes. If your test suite only exercises the happy‑path “first page, 20 items” you will miss bugs that appear on the second page, after a delete, or when a client switches from page tokens to cursors.
Below is a practical, evidence‑driven guide to building pagination test data that covers the real‑world scenarios QA teams encounter. It includes decision criteria, worked examples, validation checklists, and a short note on tooling (including QA3’s free test data generator at /tools/test-data-generator).
1. Why Pagination Test Data Is a Distinct Problem
| Symptom | Root cause | What a good data set reveals |
|---|---|---|
| Flaky “next page” tests | Tests use static IDs that disappear after a delete | Data that simulates insert/delete between page requests |
| Cursor‑based tests break after schema change | Cursor encodes internal fields (e.g., created_at, id) | Data that exercises opaque cursor round‑trips |
| Offset/limit tests return duplicates or gaps | Concurrent writes shift the window | Data that models concurrent modifications |
| Performance regressions only visible on page > 10 | Index usage changes after a certain row count | Data sets sized to cross the optimizer threshold |
Pagination is not a “single endpoint” problem; it is a stateful sequence of requests. Test data must therefore capture state transitions (add, remove, update) and the shape of each pagination style.
2. Pagination Styles at a Glance
| Style | Typical request | Response payload | Statefulness | Common edge cases |
|---|---|---|---|---|
| Page‑based | GET /items?page=3&size=20 | { "page": 3, "size": 20, "total": 1234, "data": [...] } | Stateless (page number) | Missing total, page > last, size > max |
| Cursor‑based | GET /items?after=eyJpZCI6MTIzfQ==&limit=20 | { "next_cursor": "eyJpZCI6MTI0fQ==", "data": [...] } | Stateful (opaque token) | Expired cursor, cursor tampering, reverse pagination (before) |
| Offset/Limit | GET /items?offset=40&limit=20 | { "offset": 40, "limit": 20, "data": [...] } | Stateless (numeric offset) | Large offset performance, negative offset, offset > count |
Rule of thumb – If the API returns a total count you can compute the last page; if it returns only a cursor you must treat the cursor as an opaque token and never assume its internal structure.
3. Decision Matrix – Choosing the Right Test Data Strategy
| Question | Page‑based | Cursor‑based | Offset/Limit |
|---|---|---|---|
| Does the API expose a stable total count? | ✅ | ❌ | ✅ |
| Is the cursor opaque (base64, hash)? | ❌ | ✅ | ❌ |
| Do you need to test reverse pagination? | ❌ (rare) | ✅ (before) | ❌ |
| Is the dataset expected to grow > 10 k rows? | ✅ (page calc) | ✅ (cursor stable) | ⚠️ (offset degrades) |
| Are concurrent writes a realistic scenario? | ✅ (page shift) | ✅ (cursor stability) | ✅ (offset shift) |
| Do you need to validate metadata (total, hasNext)? | ✅ | ✅ (via next_cursor) | ✅ |
Use the matrix to decide which pagination style(s) your test suite must cover. Most production APIs expose one style, but a platform that aggregates multiple services may need all three.
4. Generating Pagination Test Data – A Repeatable Workflow
- Define the domain model – list the fields that appear in each item (e.g.,
id,name,created_at,status). - Pick a size strategy –
- Small (≤ 50 rows) for unit‑level contract tests.
- Medium (≈ 500 rows) for integration tests that cross page boundaries.
- Large (≥ 10 k rows) for performance / stress tests.
- Inject mutation scenarios – create separate data sets that simulate:
- Insert between page 1 and page 2.
- Delete of the last item on page 1.
- Update of a sort key used by the cursor.
- Serialize to the wire format – JSON is the de‑facto standard; keep the exact envelope the API returns (including pagination metadata).
- Version the data sets – store them under
test-data/pagination/<style>/v1/so CI can pin a known good baseline.
Tip – Automate step 3 with a script that clones the base data set, applies a mutation, and writes the new files. This keeps the “happy path” and “mutation” data in sync.
5. Worked Example – Page‑Based Pagination
5.1. Base Data Set (200 items, page size = 20)
{
"page": 1,
"size": 20,
"total": 200,
"data": [
{ "id": 1, "name": "Item 1", "created_at": "2024-01-01T00:00:00Z", "status": "active" },
{ "id": 2, "name": "Item 2", "created_at": "2024-01-02T00:00:00Z", "status": "active" }
/* … 198 more items … */
]
}
File: test-data/pagination/page/v1/page-1.json … page-10.json.
5.2. Mutation – Insert Between Page 1 and Page 2
- Clone
page-1.json→page-1-insert.json. - Insert a new item with
id: 201and acreated_atthat sorts after item 20 but before item 21. - Increment
totalto 201. - Adjust
pagenumbers for pages 2‑10 (they now start at item 21).
Resulting page-2-insert.json now contains the new item 201 as its first element. A test that requests page 1, then page 2, will see the inserted record appear only on the second request—exactly the race condition you want to catch.
5.3. Validation Checklist (Page‑Based)
-
pageandsizeecho the request values. -
totalequals the number of items in the current data snapshot. -
data.length ≤ size. - No duplicate
idacross consecutive pages. - Requesting
page > ceil(total/size)returnsdata: []andtotalunchanged. - Requesting
size > max_allowedreturns 400 with a clear error message.
6. Worked Example – Cursor‑Based Pagination
6.1. Cursor Construction
Assume the service encodes a cursor as a base64‑url JSON object:
{ "id": 42, "created_at": "2024-03-15T12:34:56Z" }
→ "eyJpZCI6NDIsImNyZWF0ZWRfYXQiOiIyMDI0LTAzLTE1VDEyOjM0OjU2WiJ9"
The cursor is opaque to the client; the server decodes it and runs a WHERE (created_at, id) > (cursor.created_at, cursor.id) query.
6.2. Base Data Set (500 items, limit = 50)
Create ten files: cursor-0.json (first page, no after), cursor-1.json … cursor-9.json.
Each file contains:
{
"next_cursor": "eyJpZCI6NTA...",
"data": [ /* 50 items */ ]
}
The last page (cursor-9.json) omits next_cursor or sets it to null.
6.3. Mutation – Delete the Item Referenced by next_cursor
- Identify the item that produced
next_cursorincursor-3.json(e.g.,id: 151). - Remove that item from the source data set.
- Regenerate
cursor-3.jsonand all subsequent pages (cursor-4.json…). - The new
next_cursorincursor-3.jsonnow points to the next surviving item (id: 152).
A test that:
GET /items?limit=50 → cursor-0.json
GET /items?after=<cursor0>&limit=50 → cursor-1.json
GET /items?after=<cursor1>&limit=50 → cursor-2.json
GET /items?after=<cursor2>&limit=50 → cursor-3.json (deleted item)
GET /items?after=<cursor3>&limit=50 → cursor-4.json
will verify that the client does not crash when a cursor becomes stale and that the server gracefully skips the missing row.
6.4. Validation Checklist (Cursor‑Based)
-
next_cursoris a valid base64‑url string (ornull). - Decoding the cursor yields the exact
id/created_atof the last item indata. - Supplying a tampered cursor (bit‑flipped) returns 400 with “invalid cursor”.
- Supplying an expired cursor (older than retention window) returns 410 or an empty page, per spec.
- Reverse pagination (
before=<cursor>) works symmetrically. - Concurrent insert that sorts before the cursor does not appear in the current page (cursor stability).
7. Worked Example – Offset/Limit Pagination
7.1. Base Data Set (1 000 items, limit = 100)
Files: offset-0.json (offset=0), offset-100.json, … offset-900.json.
Each file:
{
"offset": 0,
"limit": 100,
"data": [ /* 100 items */ ]
}
7.2. Mutation – Concurrent Insert at Offset = 50
- Insert a new item with a sort key that places it at logical position 51.
- Regenerate all offset files after the insertion point (i.e.,
offset-100.json…). - The original
offset-0.jsonremains unchanged (first 100 items).
A test that:
GET /items?offset=0&limit=100 → offset-0.json
GET /items?offset=100&limit=100 → offset-100.json (now starts at old item 101)
will expose the classic offset shift bug where the client sees a duplicate or misses a record.
7.3. Validation Checklist (Offset/Limit)
-
offsetandlimitecho the request. -
data.length ≤ limit. - Requesting
offset >= totalreturnsdata: []. - Negative
offsetorlimitreturns 400. - Large
offset(e.g., 100 000) does not cause a timeout; verify the service caps or paginates efficiently. - After a concurrent insert/delete, the same offset request returns a different set—document the expected behavior (usually “offset is unstable”).
8. Cross‑Style Validation – What to Assert in Every Test
| Assertion | Why it matters |
|---|---|
| Schema compliance (JSON Schema / OpenAPI) | Guarantees contract stability across pagination styles. |
| Idempotent pagination metadata (total, next_cursor, has_next) | Prevents UI flicker when the same page is requested twice. |
Deterministic ordering (explicit ORDER BY on a unique key) | Without it, page 2 can differ between runs. |
| Boundary conditions (first, last, empty, oversize) | Catches off‑by‑one errors. |
| Error payload shape (error code, message, docs link) | Clients rely on consistent error handling. |
| Performance budget (p95 < 200 ms for page ≤ 10) | Pagination is often the first latency hotspot. |
Automate these assertions in a shared test library so each pagination style re‑uses the same validation code.
9. Common Pitfalls & How to Avoid Them
| Pitfall | Symptom | Fix |
|---|---|---|
Assuming total is static | Tests break after a background job adds rows. | Treat total as snapshot; generate data sets per test run or mock the count. |
| Hard‑coding cursor values | Cursor tests fail after any schema change. | Generate cursors programmatically from the same data used for the response. |
| Using sequential IDs as the only sort key | Insert/delete shifts page contents unpredictably. | Add a secondary immutable key (created_at + id) and test with both. |
| Ignoring max‑page‑size limits | Production returns 400, test passes with size = 1000. | Enforce the documented max_page_size in the test data generator. |
| Testing only forward pagination | Reverse (before) path untested. | Add a reverse‑pagination suite for cursor APIs. |
| Running pagination tests against a shared DB | Flaky results due to other test suites. | Spin up an isolated DB per test run or use a deterministic in‑memory store. |
| Not testing cursor expiration | Stale cursors silently return empty pages. | Include a “cursor TTL” scenario in the data set. |
10. Tooling Considerations
| Need | Recommended Approach |
|---|---|
| Rapid JSON payload creation | Use a scriptable data generator (Python faker, Go go-faker, or a dedicated CLI). |
| Version‑controlled data sets | Store generated files in Git LFS or a separate artifact repository. |
| CI integration | Add a generate-pagination-data step that runs before the test suite; fail the build if any file is missing. |
| Schema validation | ajv (JS), jsonschema (Python), or go-jsonschema (Go) as a pre‑test gate. |
| Performance baseline | Record p95 latency for each pagination style in a nightly benchmark job. |
| Free, zero‑config generator | QA3’s test data generator at /tools/test-data-generator can emit page, cursor, and offset payloads from a single YAML spec. |
How to use the QA3 generator – Define a
pagination:block in the
Read more
Generate Realistic API Error Payloads for Negative Testing
A practical guide to “Generate Realistic API Error Payloads for Negative Testing,” with worked scenarios, tool considerations, validation checks, and actionable advice for QA teams.
Idempotency Test Data for Safe API Retry Testing
A practical guide to “Idempotency Test Data for Safe API Retry Testing,” with worked scenarios, tool considerations, validation checks, and actionable advice for QA teams.
Rate-Limit Test Data for 429 and Retry-After Validation
A practical guide to “Rate-Limit Test Data for 429 and Retry-After Validation,” with worked scenarios, tool considerations, validation checks, and actionable advice for QA teams.