Consuming APIs
Lesson opener
In one line: A client must bound its wait, follow only the pagination that API documents, and retry only when a repeat is safe.
Why it matters: Northline's night job called the warehouse API with no timeout. One stalled connection held the job until morning. The analytics store still showed Friday's stock, and purchasing bought fasteners that had already arrived.
Before this lesson: Building APIs with Python.
What you will be able to do
- Call an HTTP API with an explicit timeout.
- Follow a documented next page and stop.
- Retry only idempotent calls, or a POST that carries an idempotency key the server defines.
- Honour a rate limit instead of looping harder.
Prerequisites
Lessons 2 and 5. This lesson pins requests 2.34.2 (PyPI https://pypi.org/project/requests/, released 2026-05-14; documentation https://requests.readthedocs.io/). The decision function below uses the standard library. A live call needs a network and is not required to finish the lesson.
Timeouts, pages, retries, rate limits
Every requests call in this course passes timeout as a number of seconds. No timeout means the call can wait forever. Northline's illustrative budget is 5 seconds for a single item read. That number is a choice, not a standard.
Pagination is whatever that API's docs describe. Some return a next URL. Some return a page number. Do not assume either. Stop when the documented signal says there is no further page, or when you have reached a maximum page count you set so a bug cannot loop. Do not invent a universal page size.
Retries. Retry GET, PUT, and DELETE when the status is 429, 500, 502, or 503, up to a small cap, with a pause between tries. Do not retry POST unless the request carries the idempotency key that API documents and you send the same key again. A 404 is not a reason to retry. If the response includes Retry-After, wait at least that long before a 429 retry. RFC 9110 (https://www.rfc-editor.org/rfc/rfc9110) defines Retry-After.
Rate limits are the provider's documented allowance. A 429 means slow down. It does not mean the data is wrong.
Error handling: branch on the status code. Log the method, the path, and the status. Do not log the Authorization header.
def should_retry(method, status, attempt, has_idempotency_key, max_attempts=3):
if attempt >= max_attempts:
return False
if status not in (429, 500, 502, 503):
return False
if method in ("GET", "PUT", "DELETE"):
return True
if method == "POST" and has_idempotency_key:
return True
return False
assert should_retry("GET", 503, 1, False) is True
assert should_retry("POST", 503, 1, False) is False
assert should_retry("POST", 503, 1, True) is True
assert should_retry("GET", 404, 1, False) is False
assert should_retry("GET", 503, 3, False) is False# requires: network
import requests
response = requests.get(
"https://example.com/items/FX-100",
headers={"Authorization": "Bearer <token-from-secret-store>"},
timeout=5,
)Replace the URL with the API you are actually allowed to call. example.com is a documentation host, not Northline's ERP.
Teacher walkthrough: read every bin page
Illustrative. The warehouse API documents GET /items?page=1 and a field next_page that is null on the last page. Page size is 2 in this example so the walk is visible. It is not a recommended page size.
- Request page 1 with timeout 5. Status 200. Items FX-100 and FX-200.
next_pageis 2. - Request page 2. Item FX-300.
next_pageis null. Stop. - If page 1 returns 503, retry the GET up to 3 attempts. If it returns 404, stop and report the path. Do not walk further pages.
- If page 2 returns 429 and
Retry-After: 2, wait 2 seconds and retry that GET. - Validation: the three SKUs match a warehouse count you do by hand for this tiny set. A job that stopped at page 1 is incomplete, not successful.
A second workplace case
A CRM export offers no next field and no page parameter. The client invents ?offset= and receives 400. The correction is to read the CRM's actual paging docs or to use the export it does document. An undocumented query name is not a hidden feature you may rely on.
Failure example: retrying a payment POST
Symptom: A 503 on "create payment" is retried with no idempotency key. The supplier is paid twice.
Diagnosis: POST is not idempotent. The retry created a second payment. The root cause is treating every 5xx as safe to repeat.
Correction: Either send the idempotency key that the payments API documents and retry with the same key, or do not retry automatically. A person reconciles the unknown payment before a second POST.
Validation: One key produces one payment row even when the first response was lost and the client retried.
Guided practice: classify four outcomes
Scenario: The night job sees these results. Figures are illustrative. Max attempts are 3. The payment call has no idempotency key. The item read is a GET.
Hints:
- Apply
should_retry. - A timeout is not a 200.
- 429 is a pause, not a data error.
Complete solution:
| Call | Result | Action |
|---|---|---|
| GET item, 503, attempt 1 | Retry | Yes, GET is idempotent |
| GET item, 404, attempt 1 | Retry | No. The SKU is not found |
| POST payment, 503, no key | Retry | No. You would risk a second payment |
| GET item, 429, attempt 1 | Retry | Yes, after Retry-After if present |
The job logs path and status only. It does not log the token.
Independent practice
Describe the client for one read API you are allowed to call, or for the illustrative warehouse pages.
Acceptance criteria:
- You set a timeout and say it is your choice or the provider's documented limit.
- You name the pagination signal from that API's docs, or you say the docs do not provide one and you will not invent it.
- You state which statuses you retry and why the method allows it.
- You say what you do on 429.
- You list what you log and you exclude the credential.
- You pin requests as 2.34.2 if you show a call.
Common mistakes
- Omitting
timeout. - Inventing a page parameter the server does not document.
- Retrying POST by default.
- Logging the Authorization header "to debug."
Quick check
- Why does every requests call in this course pass
timeout? - Which methods may be retried on 503 without an idempotency key?
- What do you do with
Retry-Afteron a 429? - Is a 404 a retry?
- What must not appear in the log line?
Answers:
- Without it the call can wait indefinitely, and the job looks running while the data is stale.
- GET, PUT, and DELETE.
- Wait at least that long before another try.
- No.
- The credential. Log method, path, and status.
Lesson summary
Bound the wait, page only as documented, retry only safe repeats, and slow down on 429. A lost response on POST is a reconciliation problem unless the server gave you an idempotency key.
Bridge to the next lesson
The next lesson uses these calls inside ERP work: customers, suppliers, inventory, sales, and procurement, and what happens when both sides changed the same record.