# How to Fetch from a Paginated REST API

> How to walk an API that splits results into pages, handle rate limits and avoid duplicates, explained simply for your AI interview.

**In short:** Request one page, read the next token or link from the reply, and repeat until the API sends none. Wait when it answers 429, skip rows you have already seen, and save the last token so a failed run can resume.

AI and LLM interview question Q483, Coding and practical. Beginner, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/fetch-from-a-paginated-rest-api

## Say it in 30 seconds

Most APIs send results in pages, so one call never gets everything. I ask for a page, read the next token or link from the reply, and repeat until there isn't one. I don't build the next URL myself, and I don't stop just because a page is short. If the API answers 429, I wait the Retry-After time and ask again. I skip rows I've already stored, and I save the last token so a crash can resume.

## Say it in 2 minutes

The first problem is size. A billing API with 40,000 invoices won't send them in one reply. It sends a page of rows, plus a token or a link that points to the next page. My job is to follow that chain until the API stops giving me one. Every loop like this needs a clear stop, or it runs forever.

Three things go wrong in real systems. Page numbers repeat or skip rows when new data arrives between calls, so I use the token the API gives me. A rate limit returns 429, and retrying at once only adds to the count, so I wait the time the API asks for. And a bug can loop on the same token, so I cap the pages and fail loudly when I hit the cap.

For a month-end run I write the fetch as a generator. Each page is handed to the store as it arrives, so the full set of rows never sits in memory at once. Each row is written with its invoice id as a unique key, so a repeat after a restart is ignored by the database. I also save the last good token in a table. If the job dies on page 310, the next run resumes from that token and keeps its place.

Bulk pulls are a separate question. Microsoft's guidance says that large extracts from its Graph API should use a bulk product, so I check that first. The loop I've described is for a normal API. I'd say that out loud, because it shows I know where the pattern stops.

## What is pagination, in plain words?

A REST API is a web address that returns data when you ask for it. A paginated one is like a records clerk handing you a long file one tray at a time. Each tray holds a fixed number of rows, and a slip says where the next tray starts. You keep asking until the slip is blank. That slip is the next token, or the next link.

Here is a realistic case. A nightly job pulls 12,000 support tickets into the search index behind an AI assistant, and the API gives them out a page at a time. Get the paging wrong and the assistant quietly misses tickets, which is the kind of bug nobody notices for a month.

Microsoft's paging guide sets the rule: while more results exist, the reply carries a next link, and you keep calling with it until the link is gone. It also says a page can hold zero results, so an empty page doesn't prove you are at the end. And the page size you ask for might be ignored, so a short page doesn't prove it either.

- **Page:** One batch of rows the API sends back in a single reply.
- **Next token or link:** A value in the reply that says where the next batch starts. Also called a cursor. Treat it as opaque: pass it back untouched.
- **Rate limit:** A cap on how many calls an API takes in a time window. Going over it gets a 429.
- **429:** The API's reply when you go over a rate limit. It often sends a Retry-After note with the seconds to wait.
- **Generator:** A Python function that hands out one item at a time and remembers where it stopped.

## How does the fetch loop walk the pages?

The loop has three moves: ask for a page, keep the new rows, and follow the token. The chart shows the job and the API passing the token back and forth, and rows leave for storage only after they pass a check.

*Diagram, How a fetch loop walks the pages: The job asks for a page, and the API returns rows with the next token. Each row is checked against the rows already seen before it is stored. The job never builds a URL itself.*
1. The job asks for one page and passes the token it saved last time.
2. The rows and the next token come back. No token means the last page.
3. Each row is checked against the rows already seen, then stored.

1. **Ask with the saved token:** The first call has no token. Every later call passes the token from the reply before.
2. **Keep only rows you haven't seen:** A row can come back on the next page if data shifted. Skip ids already seen, and let the store's unique key catch any repeat after a restart.
3. **Stop when no token comes back:** A reply with no next link is the last page. Don't build the next URL yourself, and don't stop just because a page looks short.

> **Tip:** Asked how you'd write it: follow the server's token until the server says stop. Don't guess the end from the number of rows.

## Why are page numbers worse than a token?

Page numbers look simpler: page 1, page 2, page 3. The trouble is that page 2 means 'rows 101 to 200' right now, and that changes whenever a row is added or deleted during the run. A token marks a place in the data instead.

*Diagram, Page numbers break when rows move: A new row at the top pushes an old row onto the next page, so the job reads it twice. A saved token marks a place in the data, so the next page picks up where the last one stopped. A token cuts most repeats but not all, so keep the dedupe.*
1. A new row at the top pushes the last row of page 1 onto page 2.
2. The saved token marks the place, so the next page picks up after the last row read.

Microsoft's paging guide also says the token is not yours to open: "Don't try to extract the $skiptoken or $skip value and use it in a different request." Pass it back as it arrived.

## What do you do on a 429 or a crash?

Microsoft's throttling guide says that when a limit is hit, the API returns HTTP 429, a code for too many requests, and the request fails. The reply comes with a suggested wait time in the response header, usually Retry-After. Its advice is to back off for that time and then retry. Each instant retry adds to the same limit.

- **Weak: Retry at once.** A fast retry adds to the same limit, so the 429 keeps coming back.
- **Better: Wait, then resume.** Sleep for Retry-After, retry the same cursor, and keep the last good token.

> "To read all results, you must continue to call Microsoft Graph with the @odata.nextLink property returned in each response until the @odata.nextLink property is no longer returned." (Microsoft Graph, paging)
>
> "Wait the number of seconds specified in the Retry-After header." (Microsoft Graph, throttling)
>
> "Instead, persist the token from the last successful response and use it for the next page request." (Microsoft Graph, paging)

Three guards keep a run safe. Cap the retries on a 429. Cap the number of pages, so a bug in the token can't loop forever. When the job crashes, restart from the last token saved after a good page, not from a guess.

## What does a small version look like?

Here is a runnable version with a fake billing API. It has three pages, and its second call returns a 429 with a 3-second wait. The wait is recorded instead of slept, so the output is the same every run.

```python
# A month-end job pulls invoices from a billing API. Made-up data: 2 rows a page.
PAGES = {
    None: (["INV-101", "INV-102"], "c2"),
    "c2": (["INV-103", "INV-104"], "c3"),
    "c3": (["INV-104", "INV-105"], None),  # INV-104 moved here when a new invoice landed
}
calls, waits = [], []
def get_page(cursor):
    calls.append(cursor)
    if len(calls) == 2:  # the second call is rate limited once
        return 429, 3  # 429 Too Many Requests, Retry-After: 3 seconds
    return 200, PAGES[cursor]
def fetch_invoices():
    cursor, seen = None, set()
    while True:
        status, body = get_page(cursor)
        while status == 429:  # wait as told, then ask again
            waits.append(body)
            status, body = get_page(cursor)
        rows, cursor = body
        for row in rows:
            if row not in seen:  # a row can repeat when data shifts
                seen.add(row)
                yield row
        if cursor is None:  # no next token means the last page
            return
invoices = list(fetch_invoices())
print(len(invoices), "invoices:", invoices)
print("waited (seconds):", waits)
print("API calls:", len(calls))
```

Output:

```text
5 invoices: ['INV-101', 'INV-102', 'INV-103', 'INV-104', 'INV-105']
waited (seconds): [3]
API calls: 4
```

Notice the duplicate. INV-104 appears on two pages because a new invoice landed in between, and the seen set keeps it once. A real job also needs a cap on 429 retries, a cap on pages and a real sleep, which I left out to keep it short.

### How would you pull 12,000 tickets overnight?

Say a support assistant needs last month's tickets in its search index by 7 a.m. The made-up API sends 100 tickets a page, and it sometimes answers 429 under load.

1. **Run the fetch as a job:** A worker pulls pages, saves the token after each good page, and writes rows to the index in batches. Each ticket id is a unique key, so a repeat is ignored.
2. **Plan for 429s:** Back off for the Retry-After time, and share one limit across workers so they don't all hit the same wall.
3. **Test the resume:** Stop the job on page 40, restart it, and check that no ticket is missing or stored twice.

> **Tip:** Say what you would measure: tickets counted at the source against tickets in the index, every night.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] The loop: ask, keep new rows, follow the next token, stop when there is none.
- [ ] Why a token beats a page number when data changes during a run.
- [ ] Retry a 429 only after the Retry-After wait, with a cap.
- [ ] Dedupe and resume: a generator, a unique key in the store and a saved token.
- [ ] Stop rules that never guess from page size or a short page.
- [ ] When a bulk export is the better tool than REST.

**Common traps**

- Trap: "Keep asking until a page comes back with fewer rows." Better: A short page can still have a next token. Follow the token, and treat an empty page as normal.
- Trap: "Retry right away when you get a 429." Better: Wait the Retry-After time first. An instant retry only adds to the count.
- Trap: "Page numbers are simpler, so use them." Better: They skip or repeat rows when data changes. A token marks the place.

## Can you spot the bug?

**Spot the bug:** Assume the first page is fetched before each loop starts. Which loop can stop before the last page and miss invoices?

A. while cursor is not None: rows, cursor = get(cursor)
B. while True: rows, cursor = get(cursor); if not rows: break
C. while cursor: rows, cursor = get(cursor); save(rows)

**Answer:** B. The middle one stops at the first empty page. An empty page can still carry a next token, so the loop quits early. The other two follow the token until the API sends none.

**Quick check:** A 429 reply says to wait 30 seconds. What should the job do?

A. Retry at once, three times
B. Wait 30 seconds, then retry the same cursor
C. Skip the page and move on
D. Start again from page 1

**Answer:** B. Wait the time the API gives, then ask again for the same cursor. Retrying at once adds to the limit, skipping loses rows, and starting over repeats work.

## Can you answer these from memory?

**Flash cards**

- **What is pagination?** The API sends results in batches, each with a token or link to the next batch.
- **Why not page numbers?** Rows added mid-run shift the pages, so rows repeat or get skipped. Use the token.
- **When do you stop?** When the reply has no next token or link. Never guess from the page size.
- **What does a 429 mean?** Too many requests. Wait the Retry-After time, then retry the same cursor.
- **Why dedupe?** A row can appear on two pages after a change. Keep seen ids, plus a unique key in the store.
- **What if the job crashes?** Resume from the last token saved after a good page, not from page 1.

## Likely follow-up questions

- Q330 How do you handle rate limits and 429 errors? https://designervenkat.online/interview/ai/how-do-you-handle-rate-limits-and-429-errors
- Q337 Timeouts, retries and backoff? https://designervenkat.online/interview/ai/timeouts-retries-and-backoff
- Q331 When do you use batch APIs? https://designervenkat.online/interview/ai/when-do-you-use-batch-apis
- Q471 Implement a rate limiter (per-user and global). https://designervenkat.online/interview/ai/implement-a-rate-limiter
- Q473 Run an LLM over 50,000 documents with concurrency limits and 429 retries. https://designervenkat.online/interview/ai/run-an-llm-over-50000-documents

## Learn it in depth

- [APIs as a data source](https://designervenkat.online/learn/machine-learning/apis)
