Testing Paginated API Responses: Edge Cases Agents Miss
Pagination looks simple: request a page, get some records, ask for the next one. In practice it's one of the most reliably broken areas of an API. A team writes a test that fetches page one with ten results, it passes, and everyone moves on. Then a client hits the last page with zero items, or sends limit=0 and gets a 500, or a record is deleted mid-traversal and a row silently disappears from an export.
Two things make this more pressing now that coding agents are part of the work. First, when I ask GitHub Copilot or a coding agent for "tests for the products endpoint", the first thing it writes is that same page-one happy path. It's the most common pattern in the code it learned from. Second, agents increasingly consume paginated APIs through tools. An agent whose list tool only reads the first page will answer a question confidently from partial data, and nothing in the output tells you.
So pagination tests now protect two kinds of client: the apps your team builds, and the agents calling your API on someone's behalf. Here are the scenarios I cover, with pytest examples you can adapt.
Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.
Seed the data so the counts mean something
Pagination assertions are about counts, and counts are meaningless against a shared environment where anyone can add records. Before writing a single boundary test, I make each test own its data. A fixture creates a known number of records under a unique tag, the tests filter by that tag, and teardown removes them.
import uuid
import pytest
PAGE_SIZE = 10
TOTAL = 25
@pytest.fixture
def seeded_products(api):
tag = f"pagetest-{uuid.uuid4().hex[:8]}"
ids = []
for i in range(TOTAL):
resp = api.post("/products", json={"name": f"item {i}", "tag": tag})
assert resp.status_code == 201
ids.append(resp.json()["id"])
yield tag, ids
for product_id in ids:
api.delete(f"/products/{product_id}")
Here api is a small client fixture that wraps a requests.Session and prefixes the base URL. Twenty-five records with a page size of ten gives you two full pages and a partial third, which is exactly the shape you want. How far to take this isolation is a judgement call, and I cover the trade-offs in how much test data isolation is actually enough.
Boundaries: first page, last page and the one after that
The tests most often missing are the transitions at the edges of the data set:
def get_page(api, tag, offset):
resp = api.get("/products", params={"tag": tag, "limit": PAGE_SIZE, "offset": offset})
assert resp.status_code == 200
return resp.json()
def test_first_page_is_full_and_has_next(api, seeded_products):
tag, _ = seeded_products
page = get_page(api, tag, 0)
assert len(page["items"]) == PAGE_SIZE
assert page["pagination"]["has_next"] is True
def test_last_page_holds_the_remainder(api, seeded_products):
tag, _ = seeded_products
page = get_page(api, tag, 20)
assert len(page["items"]) == TOTAL % PAGE_SIZE
assert page["pagination"]["has_next"] is False
def test_offset_past_the_end_is_empty_not_an_error(api, seeded_products):
tag, _ = seeded_products
page = get_page(api, tag, TOTAL + PAGE_SIZE)
assert page["items"] == []
assert page["pagination"]["has_next"] is False
That last test is the one teams skip. A request past the end should return 200 with an empty list, not a 404 or a 500, because clients use that response to decide the loop is finished. I also add a run where the total is an exact multiple of the page size. "Is has_next true on a full final page?" is a classic off-by-one, and it only shows up with that exact count.
The empty case belongs here too: a filter that matches nothing should return 200, an empty array (not null), a total of zero and no next cursor.
Walk every page and check the whole set
Single-page assertions can all pass while the traversal as a whole is wrong: duplicates across pages, a missing row at a boundary, or a cursor that loops. So I walk the entire result and compare it to what I seeded, with a page cap so a cycling cursor fails the test instead of hanging CI.
def walk_all(api, tag, max_pages=50):
seen, cursor = [], None
for _ in range(max_pages):
params = {"tag": tag, "limit": PAGE_SIZE}
if cursor:
params["cursor"] = cursor
resp = api.get("/products", params=params)
assert resp.status_code == 200
body = resp.json()
seen.extend(item["id"] for item in body["items"])
cursor = body.get("next_cursor")
if not cursor:
return seen
pytest.fail(f"pagination did not end after {max_pages} pages")
def test_traversal_returns_every_item_exactly_once(api, seeded_products):
tag, ids = seeded_products
seen = walk_all(api, tag)
assert len(seen) == len(set(seen)), "duplicate items across pages"
assert set(seen) == set(ids)
This example uses cursor pagination. For offset pagination the loop is the same idea with an incrementing offset.
Malformed parameters should be client errors
Zero or negative limits, non-numeric values, negative offsets and garbage cursors will all arrive eventually, from client bugs more often than attackers. They should get a clear 4xx, never a 500.
@pytest.mark.parametrize("params", [
{"limit": 0},
{"limit": -1},
{"limit": "ten"},
{"offset": -1},
{"cursor": "not-a-real-cursor"},
])
def test_bad_paging_params_are_client_errors(api, params):
resp = api.get("/products", params=params)
assert resp.status_code == 400
Check what your API documents before you lock in the status code. Some return 422, some return 400, and either is fine as long as it's consistent. Oversized limits deserve their own test. If the API silently clamps limit=500 to 100, assert the clamped count and whatever metadata signals it, because a client that assumes it got 500 will quietly miss data. Structuring pytest parametrize for API edge cases covers how I keep tables like this readable as they grow.
Data that changes during a traversal
Offset pagination has a known weakness: if a record is deleted between page one and page two, everything shifts up and the client skips a row. An insert causes a duplicate. You usually can't fix that in a test, but you can document the guarantee the API actually makes. Fetch page one, delete one of its records, fetch page two, and assert there's no overlap. For cursor pagination, assert the stronger guarantee: nothing skipped, nothing repeated. Also test what an expired or tampered cursor returns. A 400 or 410 with an error body is fine. A 200 with the wrong data is not.
When the client is an agent
If an agent reaches your API through a tool (an MCP server or a function the agent can call), that tool is a pagination client with a new failure mode. A model can't tell that a list was cut off unless the tool says so. I make the tool report truncation explicitly and test that contract:
def list_products_tool(api, tag, max_items=100):
"""Tool exposed to an agent. Never drops results silently."""
items, cursor = [], None
while True:
params = {"tag": tag, "limit": PAGE_SIZE}
if cursor:
params["cursor"] = cursor
body = api.get("/products", params=params).json()
items.extend(body["items"])
cursor = body.get("next_cursor")
if not cursor or len(items) >= max_items:
break
truncated = bool(cursor) or len(items) > max_items
return {"items": items[:max_items], "truncated": truncated}
def test_tool_flags_truncation(api, seeded_products):
tag, _ = seeded_products
result = list_products_tool(api, tag, max_items=15)
assert len(result["items"]) == 15
assert result["truncated"] is True
def test_tool_returns_everything_when_it_fits(api, seeded_products):
tag, ids = seeded_products
result = list_products_tool(api, tag, max_items=100)
assert {item["id"] for item in result["items"]} == set(ids)
assert result["truncated"] is False
The same seeded fixture drives these tests, so the tool is checked against known data, not whatever happens to be in staging.
On the other side, when an agent is writing your pagination tests, give it the checklist. A few lines in .github/copilot-instructions.md (or your agent's equivalent file) asking for seeded data, the past-the-end case, the exact-multiple case and a full traversal will get you much better first drafts. Then review them against the scenarios above. The usual gaps in generated API tests are the ones I describe in where AI-generated tests get API testing wrong.
Pagination bugs hide between requests, so test the whole sequence, not one response. Seed the data, cover the edges, walk every page, and make any agent-facing tool say when it stopped early. If you want to build suites like this step by step, with Copilot in the loop, my API testing courses walk through it.