Consuming Paginated APIs: Cursors, Pages and Link Headers
Fetch every record from an API that returns a few at a time: follow cursors and Link headers, avoid duplicates and gaps, cap page size, and verify that the client collected exactly the server's data with the expected number of requests.
In this lesson you will
- Recognise cursor, offset and Link-header pagination
- Write a generator that fetches all pages
- Handle data that changes during the fetch
- Check the result against the server
About 28 minutes
Two hundred and thirty-seven customers, fifty at a time
Noor wants to export all her customers from the email service to check them against her orders. The email API will not return 237 records in one response, and a limit of 50 per page is typical. Pagination styles differ. With offset or page numbers, you ask for page 3 or for records 100 to 149. With a cursor, each response contains an opaque token that you send to get the next page. With a Link header, the response tells you the URL of the next page in a standard header, the way the GitHub API does. The documentation says which one to use, and also the maximum page size and how to know that the last page has been reached.
A client should hide all this in one function: a generator that yields records one by one and fetches the next page only when needed. The loop ends when there is no next cursor or link. Three problems need care. The page size has a maximum, so asking for 1,000 may silently give 50, and the code must not assume the size it asked for. The data can change while you read it: with offset paging, an insert at the front shifts everything and you see a record twice, as the Back-end course showed, while a cursor is stable. And every page is a request that counts against the rate limit of lesson 5, so asking for the largest allowed page size reduces requests.
| Style | Request | Stable if data changes? |
|---|---|---|
| Page number | GET /customers?page=3 | No |
| Offset | GET /customers?offset=100&limit=50 | No |
| Cursor | GET /customers?cursor=abc123 | Yes |
| Link header | Follow rel=”next” | Depends on the server |
import json, threading, urllib.request, urllib.parse, re
from http.server import BaseHTTPRequestHandler, HTTPServer
customers = [{"id": i, "name": "Customer %03d" % i} for i in range(1, 238)]
MAX_PAGE = 50
requests_seen = []
class Mail(BaseHTTPRequestHandler):
def do_GET(self):
u = urllib.parse.urlparse(self.path); q = urllib.parse.parse_qs(u.query); requests_seen.append(self.path)
limit = min(int(q.get("limit", [20])[0]), MAX_PAGE)
if "cursor" in q or "offset" not in q:
after = int(q["cursor"][0]) if "cursor" in q else 0
rows = [c for c in customers if c["id"] > after][:limit]
nxt = rows[-1]["id"] if len(rows) == limit and rows[-1]["id"] < max(c["id"] for c in customers) else None
body = {"data": rows, "next_cursor": str(nxt) if nxt else None}
link = '<http://x/customers?cursor=%d&limit=%d>; rel="next"' % (nxt, limit) if nxt else None
else:
off = int(q["offset"][0]); rows = customers[off:off + limit]
body = {"data": rows, "next_offset": off + limit if off + limit < len(customers) else None}; link = None
b = json.dumps(body).encode(); self.send_response(200); self.send_header("Content-Type", "application/json"); self.send_header("Content-Length", str(len(b)))
if link: self.send_header("Link", link)
self.end_headers(); self.wfile.write(b)
def log_message(self, *a): pass
srv = HTTPServer(("127.0.0.1", 0), Mail); base = "http://127.0.0.1:%d" % srv.server_address[1]
threading.Thread(target=srv.serve_forever, daemon=True).start()
def get(path): r = urllib.request.urlopen(base + path); return json.loads(r.read()), r.headers.get("Link")
def all_by_cursor(limit=1000):
cursor = None
while True:
body, _ = get("/customers?limit=%d" % limit + ("&cursor=" + cursor if cursor else ""))
yield from body["data"]
cursor = body["next_cursor"]
if not cursor: return
def all_by_link():
path = "/customers?limit=50"
while path:
body, link = get(path); yield from body["data"]
m = re.search(r'<[^>]*(/customers\?[^>]*)>; rel="next"', link or ""); path = m.group(1) if m else None
def all_by_offset(on_page=None):
off = 0
while off is not None:
body, _ = get("/customers?offset=%d&limit=50" % off); yield from body["data"]
if on_page: on_page(off)
off = body["next_offset"]
a = list(all_by_cursor()); n_cursor = len(requests_seen); requests_seen.clear()
b = list(all_by_link()); n_link = len(requests_seen); requests_seen.clear()
c = list(all_by_offset()); n_off = len(requests_seen); requests_seen.clear()
print("cursor (asked for 1000, got 50 at a time):", len(a), "records in", n_cursor, "requests")
print("Link header:", len(b), "records in", n_link, "requests | offset:", len(c), "records in", n_off, "requests")
same = [x["id"] for x in a] == [x["id"] for x in b] == [x["id"] for x in c] == [x["id"] for x in customers]
print("all three methods return exactly the server's records in order:", same)
def insert_first(off):
if off == 0: customers.insert(0, {"id": 0, "name": "Early customer"})
d = list(all_by_offset(insert_first)); ids = [x["id"] for x in d]
dup = sorted({i for i in ids if ids.count(i) > 1})
customers.pop(0)
print("offset paging with an insert at the front during the fetch: repeated ids", dup, "| records seen", len(d))
print("DATA " + json.dumps({"n": [len(a), len(b), len(c)], "req": [n_cursor, n_link, n_off], "same": same, "dup": dup, "seen": len(d)}))
srv.shutdown()
cursor (asked for 1000, got 50 at a time): 237 records in 5 requests
Link header: 237 records in 5 requests | offset: 237 records in 5 requests
all three methods return exactly the server's records in order: True
offset paging with an insert at the front during the fetch: repeated ids [50] | records seen 238
The simulated email service has 237 customers and never returns more than 50 per page. The first client asked for 1,000 per page, and got 50 anyway: it did not assume otherwise, but followed the next_cursor token until it was empty, and collected 237 records in 5 requests. The second followed the Link header of each response, which names the URL of the next page, and the third used offsets. All three produced the same 237 records in the same order, and the same number of requests, 5, which is 237 / 50 = 4.74 rounded up. The cursor version of the client wrote the whole loop as one generator, so that the code that uses it simply writes “for customer in all_by_cursor()” and never sees pages.
The last experiment repeated the offset method while another process inserted a new customer at the front, after the first page was read. Every later record shifted by one position, so the offset-based client saw the last record of page 1, id 50, again at the start of page 2: it reported 238 records, one more than the 237 real ones, with a duplicate. A cursor does not have this problem, because “after id 50” means the same thing before and after the insert, although a new record that sorts before the cursor is not seen until the next export. If an export must be exact, use a stable ordering, a cursor and, where the API supports it, a snapshot or a filter on the update time, and deduplicate by id on your side as a safeguard.
Independent check: the list of ids collected by each method was compared with the server’s own list, which the client has no access to, and they are identical: 1 to 237 with no gaps and no repeats. The request counts come from the server’s log, not from the client, and equal the predicted ceil(237 / 50) = 5 for each method. A good test of any paginated client is to run it against a server with a known number of records, a number that is not a multiple of the page size, as 237 is not a multiple of 50, because the short last page is where off-by-one bugs live.
Check by hand: four full pages of 50 make 200 records, and the fifth page holds the remaining 37, so 5 requests in all. A cursor request for the next page after the fifth would return nothing, but the server tells the client that there is no next cursor when the page is short, which saves a request.
Servers silently cap limit parameters. Loop until the server says there is nothing more, and never compute the number of pages from the size you requested.
Keep a set of seen ids during a long export, and log duplicates. They tell you that the data changed while you were reading it, which matters for reports and billing.
Every program in this lesson was run while the course was written, with Python 3.13 (standard library only) against small mock APIs that the lesson itself starts on a local port, and cross-checked with curl, OpenSSL, Node.js or a second calculation. The services are invented stand-ins, not real vendors: always read the current documentation of the real API you use. Cursor formats are opaque, and you must pass them back unchanged. Link header parsing follows RFC 8288, and libraries handle its details, so check the documentation of the real service.
Practice
Add a maximum total of 100 records to the generator. Make the client stop and report when a page returns fewer records than expected. Export the records to a CSV file as they arrive, without keeping them all in memory.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
Which pagination style is stable when data changes?
- Page number
- Offset
- Cursor
- None
A cursor refers to a position in the data, not a count.
What does a Link header with rel=”next” contain?
- The size of the page
- The URL of the next page
- A password
- The cursor secret
Follow it until it is absent.
Why should a generator fetch pages lazily?
- It is required by JSON
- Memory stays small and code stays simple
- It is faster to type
- It hides errors
Yield records one by one.
How many requests do 237 records need at 50 per page?
- 5
- 4
- 6
- 237
Round up.
Why compare with the server’s own data in a test?
- It is the ground truth
- It is shorter
- It speeds up the test
- It avoids HTTP
No gaps and no repeats.
Summary
- Pagination styles: page, offset, cursor and Link header.
- Wrap paging in a generator and loop until the server says stop.
- Never assume the requested page size.
- Test with a known number of records that is not a multiple of the page size.
Questions
Should I request the maximum page size?
Usually yes, to reduce the number of requests, unless larger pages are slower or risk timeouts. Check the documentation for the maximum and for advice.
What if the API has no pagination?
Then the response is complete, or it is truncated at a limit without telling you, which is dangerous. Check the documentation and compare counts with another source.
Can I fetch pages in parallel?
Offset pages can be requested in parallel if the total is known, which speeds up exports but uses the rate limit faster. Cursors are sequential by nature.
