Pulling from an API

Part of the free LogicWiz Data Engineering course, Module 3: Python for data wrangling. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 7:05 on Tuesday. Tess's dashboard shows 20 orders for yesterday. The store took 80. Last night's job asked Dana's orders API for page 1, got 20 rows and stopped: no error, a quiet day on paper. Tonight it has to fetch every page while 400 other workers hit the same API. And from tomorrow, Nora wants it to fetch only what changed.

You'll learn to

  • Follow pagination to the end and check the count
  • Retry only temporary errors, with backoff, a cap and jitter
  • Pull only what changed, with a cursor saved last
  • Explain why a keyset cursor is safe to replay

Learn

A quiet day that was not quiet

Start with last night. The job made one call to the orders API and loaded whatever came back. What came back was 20 orders, because an API never hands over everything at once. It sends one page and waits for you to ask for the next.

That is the first of three ways an API is harder than a file. It pages. It fails, sometimes on purpose, to slow you down. And it is slow and metered, so downloading everything every night does not last.

This page cannot reach the internet, so a small module called swiftkart_api in your working folder stands in for Dana's API. It pages, filters by change time and fails on demand, the same way on every run. Open swiftkart_api.py and read it: it is short.

One page

import swiftkart_api as api

resp = api.get_orders(page=1, page_size=5)
print(sorted(resp.keys()))
print("page", resp["page"], "next", resp["next_page"], "total", resp["total"])
for o in resp["data"][:2]:
    print(o)

The response is a dict. data holds this page's orders, oldest change first. next_page says what to ask for next, and total says 80. Last night's job read data and never looked at the other two. Real APIs return the same kind of JSON over HTTP.

Follow the pages to the end

A paged response always tells you how to get the rest. This API sends next_page, which is None on the last page. Others use an offset, or a token that you pass back unchanged.

Whatever the style, the loop is the same. Ask. Keep the data. Move to whatever the response says comes next. Stop only when it says there is nothing more.

Do not work out the number of pages yourself from total. Totals change while you read, integer division drops the last partial page, and many APIs send no total at all. Follow the API's own "next", then check your count against the total when there is one.

Fetch every page

import swiftkart_api as api

def fetch_all(page_size=20):
    rows, page = [], 1
    while page is not None:
        resp = api.get_orders(page=page, page_size=page_size)
        rows.extend(resp["data"])
        page = resp["next_page"]
    return rows

orders = fetch_all(page_size=30)
print(len(orders), "orders in", api.calls(), "calls")
print(len({o["order_id"] for o in orders}), "distinct ids")

api.calls() counts the requests made so far. Comparing distinct ids with the row count catches an API that repeats rows across pages. The picture shows the same three calls one at a time.

Three calls for 80 orders

A loader follows next_page through three pages of an API holding 80 orders: 30 rows, then 60, then all 80, stopping when next_page is None.

  1. Call 1. You ask for page 1 and get 30 orders. The response says next_page is 2, so the loop goes on.

  2. Call 2. Page 2 brings 30 more: 60 so far. A loop that had worked out 80 // 30 = 2 pages would stop here, 20 orders short.

  3. Call 3. Page 3 brings the last 20, and next_page is None. Now the loop stops: 80 rows, 80 distinct ids, and total says 80.

The left box is the API, the right box is your list. Last night's job stopped after the first step.

Night two: the API pushes back

Tonight 400 workers across the company call the same API, and it starts to refuse: HTTP 429 and 503.

Errors come in two kinds, and the status code tells you which. Some mean try again later: 429 Too Many Requests (you hit the rate limit), 503 Service Unavailable (the server is busy), and network timeouts. Others mean trying again will not help: 400 Bad Request, 401 Unauthorized, 404 Not Found. Retrying those wastes calls and hides real bugs.

For the first kind, wait, then retry, and wait longer each time: 1 s, 2 s, 4 s, 8 s. That is exponential backoff. It gives a struggling server room to recover. After a few attempts, give up and raise: a job that fails loudly beats one that hangs all night.

Retry with backoff

import swiftkart_api as api
from swiftkart_api import RateLimited, ServerError

def with_retries(fn, max_attempts=4, sleep=lambda seconds: None):
    for attempt in range(1, max_attempts + 1):
        try:
            return fn()
        except (RateLimited, ServerError) as e:
            if attempt == max_attempts:
                raise
            wait = 2 ** (attempt - 1)
            print(f"  attempt {attempt} failed ({e}); waiting {wait}s")
            sleep(wait)

api.flaky(every=3)
rows, page = [], 1
while page is not None:
    resp = with_retries(lambda: api.get_orders(page=page, page_size=20))
    rows.extend(resp["data"])
    page = resp["next_page"]
print(len(rows), "orders in", api.calls(), "calls")

Here every third call fails. Call 3 answers 429, the wrapper waits and asks again: 80 orders in 5 calls, where a clean run takes 4. sleep is a parameter: in production you pass time.sleep, and here a function that does nothing keeps the run instant. Only RateLimited and ServerError are caught, so a NotFound still fails at once. fn is a function (here a lambda) so the wrapper can call it again.

A thousand clients retry in the same second

Backoff alone has a flaw. Clients that failed together retry together. A thousand workers that got a 503 at the same moment all come back after 1 s, then 2 s later, then 4 s later, and knock the server over each time. People call this a thundering herd.

The cure is a little randomness, called jitter. With full jitter a client does not wait exactly 1, 2, 4 seconds. It waits a random time between 0 and that number, and the herd spreads out.

Two more rules. Put a cap on the wait, so a long outage does not produce hour-long sleeps. And when the server sends a Retry-After header, obey it: it knows better than your formula.

Three clients after one 503

Six lanes over eight seconds: three clients fail together; with plain backoff they retry together at 1.2, 3.4 and 7.6 seconds; with full jitter the same three clients retry at scattered times.

  1. The failure. Three clients call at the same moment and all get a 503. Each call takes 0.2 s. The base wait is 1 s and the cap is 8 s.

  2. Plain backoff. Each client waits 1 s, then 2 s, then 4 s. So all three come back together at 1.2 s, 3.4 s and 7.6 s. The server gets three bursts.

  3. Full jitter. Each wait is now a random time between 0 and the plain wait. The same nine retries arrive one by one. No wait is longer than before, so the average delay drops as well.

Read each lane left to right, in seconds. The jittered times come from the next card, which uses random.Random(1) so they are the same on every run. With full jitter the expected wait is half the ceiling.

The schedules, computed

import random

def plain(n, base=1, cap=8):
    return min(cap, base * 2 ** n)

print("waits, base 1, cap 30:", [min(30, 2 ** n) for n in range(8)], "worst case", sum(min(30, 2 ** n) for n in range(8)), "s")

rng = random.Random(1)
for client in "ABC":
    end, starts = 0.2, []
    for n in range(3):
        start = round(end + rng.uniform(0, plain(n)), 1)
        starts.append(start)
        end = start + 0.2
    print(client, "full jitter retries at", starts)

rng = random.Random(1)
for name, wait in [("none", lambda: 2), ("equal", lambda: 1 + rng.uniform(0, 1)), ("full", lambda: rng.uniform(0, 2))]:
    buckets = {}
    for _ in range(1000):
        b = int(wait() * 10)
        buckets[b] = buckets.get(b, 0) + 1
    print(f"{name:5} jitter: busiest 100 ms holds {max(buckets.values())} of 1000 retries")

Line 1: with base 1 s and cap 30 s, eight retries wait 1, 2, 4, 8, 16, 30, 30, 30: 121 s in the worst case. That sum has to fit inside the task's timeout. Lines 2 to 4 are the jittered times from the picture. The last three lines put a thousand clients on their second retry: with no jitter all 1,000 land in the same 100 ms, with equal jitter 115 do, with full jitter 60.

Remember: retry only what a retry can fix. Wait longer each time, cap the wait, add jitter, and retry at one layer only.

Night three: pull only what changed

The job now gets all 80 orders, even on a bad night. But downloading everything every night only works while "everything" is small. 80 orders, fine. 50 million, no.

An incremental pull asks only for records that changed since the last run: get_orders(updated_since="2025-06-14 08:00:00").

The value you pass has a name: a cursor (also called a watermark or high-water mark). It is the greatest updated_at you have already loaded. After a successful run you save the new maximum in a small state store: a file, a table, a variable in your scheduler. The next run starts from it. Module 6 builds this pattern in SQL. Here it is in its plainest form.

Three runs, one saved cursor

Three runs against the orders API with a cursor saved in a state file: the first run takes all 80 orders and saves the newest change time, the second finds nothing, order 1042 changes overnight, and the third run fetches only that order and moves the cursor forward.

  1. Run 1: no cursor yet. The state file does not exist, so the run asks for everything and gets 80 orders. They are written to storage, and only then is the cursor saved: the greatest updated_at among them.

  2. Run 2: nothing new. The run asks for changes after the cursor and gets 0 rows. The cursor stays where it is.

  3. Overnight, order 1042 changes. The store marks it returned at 09:00 on 16 June. Nothing else moves, and no run has happened yet.

  4. Run 3: one row. The run asks for changes after the cursor and gets exactly that one order. Once it is stored, the cursor moves forward to 09:00:00 on 16 June.

Three boxes: the API, tonight's run, and the tiny file that remembers where the last run stopped. The next card runs exactly these three runs.

Save the cursor last. If you save it before the rows are safely written and the write then fails, the next run starts after rows you never stored, and they are lost for good. And never retry a non-idempotent call blindly: a POST that timed out may have succeeded. APIs that create things accept an idempotency key for this; Stripe's Idempotency-Key header returns the saved first response for a repeated key, and its keys can be pruned after 24 hours.

Three runs with a saved cursor

import json, os
import swiftkart_api as api

STATE = "state.json"

def load_cursor():
    if not os.path.exists(STATE):
        return None
    with open(STATE) as f:
        return json.load(f)["orders_cursor"]

def save_cursor(value):
    with open(STATE, "w") as f:
        json.dump({"orders_cursor": value}, f)

def run():
    since = load_cursor()
    rows, page = [], 1
    while page is not None:
        resp = api.get_orders(page=page, page_size=50, updated_since=since)
        rows.extend(resp["data"])
        page = resp["next_page"]
    # ... write rows to storage here, and only then:
    if rows:
        save_cursor(max(r["updated_at"] for r in rows))
    print(f"since {since}: {len(rows)} changed, cursor now {load_cursor()}")

run()
run()
with open("data/orders.csv", "a") as f:
    f.write("1042,26,2025-06-08 20:03:30,returned,USD,2025-06-16 09:00:00\n")
run()

Three output lines, one per run: 80 changed, then 0, then 1. The appended line stands in for the store changing order 1042 overnight. Look at where save_cursor sits inside run(): after the rows are written, never before.

A cursor you can replay

One question decides whether an incremental pull is safe. If the run crashes and starts again from the same cursor, does it get the same rows? If yes, the cursor is idempotent: a rerun leaves no gaps and no duplicates.

Paging by offset ("skip 20 rows, give me the next 20") fails the test. If a row on an earlier page changes while you read, every later row shifts by one. A row is skipped, or read twice.

Keyset paging asks a different question: "give me the rows after the last one I saw". Nothing shifts.

But "after" needs an order with no ties, and updated_at alone ties: three orders can change in the same second. Add a unique tie-breaker, the id, and compare the pair (updated_at, id).

Offset paging while the source changes

The loader reads page one by offset, an order on page one changes and moves to the end of the sort order, so the request for offset 20 starts one row late and row 21 is never read; a keyset request after the last seen key reads it.

Read it top to bottom. Above the line, offset paging loses old row 21 when row 5 moves. Below the line, a keyset request names the last row it saw, so the changed order shows up later, once.

A timestamp-only cursor drops tied rows

rows = [  # (updated_at, order_id), in cursor order
    ("2025-06-14 09:00:00", 1031), ("2025-06-14 09:00:00", 1032), ("2025-06-14 09:00:00", 1033),
    ("2025-06-14 09:05:00", 1034), ("2025-06-14 09:07:00", 1035),
]

def page_by_ts(cursor, limit):
    return [r for r in rows if cursor is None or r[0] > cursor][:limit]

def page_by_key(cursor, limit):
    return [r for r in rows if cursor is None or r > cursor][:limit]

def pull(page, key, limit=2):
    seen, cursor = [], None
    while True:
        batch = page(cursor, limit)
        if not batch:
            return seen
        seen += [r[1] for r in batch]
        cursor = key(batch[-1])

print("updated_at only:", pull(page_by_ts, key=lambda r: r[0]))
print("(updated_at, id):", pull(page_by_key, key=lambda r: r))

The first line is missing 1033. The second has all five: the tuple cursor compares the id when the timestamps tie, so every row is reached exactly once. Run pull again and you get the same list: that is idempotence. One gap remains. A transaction that commits late can carry an older updated_at than rows you already passed. So real loaders re-read a small overlap, upsert by key, and save the cursor in the same transaction as the data.

Numbers to remember

WhatNumber or ruleGood to know
Errors worth a retry429, 503 and timeoutsnever 400, 401 or 404: a retry cannot fix them
Capped backoff: the wait before retry nmin(cap, base 2n), counting n from 0with base 1 s, five retries wait 1 + 2 + 4 + 8 + 16 = 31 s
Total wait for k retries below the capbase (2k - 1)plus cap for every retry above it: base 1, cap 30, eight retries is 121 s
Full jitteruniform(0, min(cap, base 2n))in the AWS Architecture Blog's study it did the least work, for slightly more time
Equal jitter, decorrelated jitterhalf fixed and half random; min(cap, uniform(base, previous 3))two other ways to spread the herd
Retries across layers5 layers that each try 3 times: 3^5 = 243 callsthe AWS Builders' Library example: retry at one layer only
urllib3 Retrybackofffactor 2 (retries so far), capped at backoffmax (120 s)backoffjitter is 0 by default; honours Retry-After on 413, 429 and 503; by default retries only idempotent methods (no POST)
Keyset paging in SQLWHERE (updatedat, id) (:ts, :id) ORDER BY updatedat, id LIMIT 20the key must have no ties

Python teams use requests or httpx with urllib3's Retry or tenacity. Managed connectors (Fivetran, Airbyte) and dlt keep the incremental cursor as state between runs, and Azure Data Factory's REST connector has pagination rules for the same reason.

What changed at SwiftKart

Three nights, three fixes. The job follows next_page to the end and checks its count against total: 80, not 20. It retries 429 and 503 with a capped, jittered wait, and fails at once on anything else. And from tonight it asks only for what changed after its cursor, compares (updated_at, id), and saves the cursor after the rows are safe.

Tess's dashboard shows 80 orders for Monday. On Dana's API graphs, your job is a thin steady line where there used to be bursts.

Everything you fetch is now complete. Whether it is right is another matter: prices as text, dates in four formats, a quantity of minus one. That is the next lesson.

In one line

Follow the API's own "next" to the end, retry only temporary errors with capped, jittered backoff, and pull changes with an (updated_at, id) cursor that you save after the data is safe.

Interview corner

Why add jitter to exponential backoff, and which kind?

Clients that fail together retry together, so without randomness a thousand workers hit a recovering server at exactly +1 s, +3 s and +7 s and push it over again. Full jitter sleeps a uniform random time between 0 and min(cap, base * 2**n), which spreads the herd over the whole window and halves the average wait; in the AWS Architecture Blog's study it did the least work. I also cap the wait, honour Retry-After, budget the worst case (five retries at base 1 s add 31 s), and retry at one layer only, because three attempts at each of five layers is 243 calls at the bottom.

Your incremental API pull sometimes loses an order and sometimes loads one twice. What is wrong and how do you fix it?

Usually offset pagination over a list that changes while you page, or a cursor that is not a total order. With offsets, a changed row moves to the end and shifts every later row, so one is skipped and one repeats. With updated_at alone, a page that ends inside a group of tied timestamps loses the rest of the group under > or repeats it under >=. I page by a keyset (updated_at, id) > (last_ts, last_id), re-read a small overlap for late commits, upsert by key so the overlap is harmless, and save the cursor only after the load commits.

Which errors do you retry, and which requests are safe to retry?

Only temporary errors: 429, 5xx and timeouts; 400, 401, 403 and 404 fail at once, because a retry cannot fix them. A retry is safe only if the request is idempotent: GET, PUT and DELETE by design, which is why urllib3 retries only those methods by default. For a POST that creates something I send an idempotency key, such as Stripe's Idempotency-Key header, so a retried request returns the first result instead of creating a second charge.