Python Master Course V2 — 099. Building a Robust API Client
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 09 — WEB AND API ENGINEERING · LESSON 099 / 200
Building a Robust API Client
Study time: 90–120 minutes. Prerequisites: HTTP, JSON, functions, exceptions and Lesson 98.
Video lesson
Video not yet available. This is a reserved space for a verified video URL/player.
Outcomes
Design a reusable client with validation. You should also be able to identify security implications, test expected and error behavior, and explain your design choices.
Detailed concepts
A client centralizes base URLs, headers, serialization, error handling and response validation. Inject a transport or mock for tests instead of requiring live network calls.
Professional API workflow: model the resource, define request and response schemas, validate inputs, enforce authorization, choose suitable status codes, set timeouts and resource limits, and test normal and failure scenarios. Treat all network data as untrusted. Avoid leaking credentials in logs, URLs or error responses.
Maintainability: separate transport code from business logic, document assumptions, use dependency injection for testable clients, and prefer bounded operations over unbounded retries or pagination loops.
Understand and apply: Building a Robust API Client
A client turns protocol details into a small domain interface
A reusable API client centralizes controlled base URLs, request metadata, timeouts, transport errors and response validation. Callers should ask for a product or a page of products rather than repeat URL construction and dictionary indexing everywhere. Keep the interface narrow enough that its behavior and failure cases can be tested.
The client below delegates actual I/O to a supplied transport callable. The transport contract is GET of a controlled URL with a timeout, returning a parsed JSON object after status, media type and body-size checks. A real adapter can reuse the fetch logic from Lesson 094 and the retry policy from Lesson 098. A fake exercises domain behavior without credentials or live network access. This teaching API returns at most two products per page and permits one to one hundred pages. SKU normalization follows Lesson 095: trim whitespace, require nonblank text, and preserve case; duplicate normalized identifiers fail validation.
Python example
from urllib.parse import urlencode
class InventoryClient:
def __init__(self, transport, max_pages=10):
if not callable(transport):
raise TypeError("transport must be callable")
if type(max_pages) is not int or not 1 <= max_pages <= 100:
raise ValueError("max_pages must be between 1 and 100")
self.transport = transport
self.max_pages = max_pages
self.base = "https://example.org/v1/products"
def list_products(self):
products, seen_skus = [], set()
page = 1
for _ in range(self.max_pages):
payload = self.transport(self.base + "?" + urlencode({"page": page, "limit": 2}), timeout=3.0)
if not isinstance(payload, dict) or not isinstance(payload.get("items"), list):
raise ValueError("invalid page shape")
if len(payload["items"]) > 2:
raise ValueError("page exceeds the two-item contract")
for item in payload["items"]:
if not isinstance(item, dict):
raise ValueError("product must be an object")
sku, qty = item.get("sku"), item.get("qty")
if not isinstance(sku, str) or not sku.strip() or type(qty) is not int or qty < 0:
raise ValueError("invalid product")
sku = sku.strip()
if sku in seen_skus:
raise ValueError("duplicate SKU across pages")
seen_skus.add(sku)
products.append((sku, qty))
if "next_page" not in payload:
raise ValueError("next_page required")
following = payload["next_page"]
if following is None:
return products
if type(following) is not int or following <= page:
raise ValueError("pagination did not advance")
page = following
raise ValueError("page limit exceeded")
pages = iter([{"items": [{"sku": "PEN", "qty": 3}], "next_page": 2},
{"items": [{"sku": "BOOK", "qty": 0}], "next_page": None}])
urls = []
def fake_transport(url, timeout):
urls.append(url)
return next(pages)
print(InventoryClient(fake_transport).list_products())
print(len(urls))
assert urls == ["https://example.org/v1/products?page=1&limit=2", "https://example.org/v1/products?page=2&limit=2"]
def check_pages(payloads, max_pages=10):
sequence = iter(payloads)
def transport(url, timeout):
assert timeout == 3.0
return next(sequence)
return InventoryClient(transport, max_pages=max_pages).list_products()
assert check_pages([{"items": [], "next_page": None}]) == []
invalid_cases = [
([{"items": [], "next_page": 1}], 10),
([{"items": []}], 10),
([{"items": [{"sku": "PEN", "qty": 1}], "next_page": 2}, {"items": [{"sku": " PEN ", "qty": 2}], "next_page": None}], 10),
([{"items": [{"sku": "PEN", "qty": True}], "next_page": None}], 10),
([{"items": [], "next_page": 2}], 1),
([{"items": [{"sku": str(i), "qty": 1} for i in range(3)], "next_page": None}], 10),
]
for payloads, max_pages in invalid_cases:
try:
check_pages(payloads, max_pages)
except ValueError:
pass
else:
raise AssertionError("invalid response accepted")
print("Client checks passed")
Expected output
[('PEN', 3), ('BOOK', 0)]
2
Client checks passed
The loop validates each page before accepting its records. A null next_page ends traversal; a missing field is a schema error. The next page must advance, and max_pages limits even a server that invents endless increasing page numbers. Repeated SKUs are rejected because this method promises a unique inventory snapshot rather than silently overwriting earlier values.
Control memory, URLs and error meaning
This method deliberately returns a complete list, so memory grows with accepted products. The transport body-size limit, two-item response limit, and page-count bound constrain that growth but do not make it a streaming client. A future iterator version can yield one page at a time. Use a snapshot or cursor contract if the server’s records may change during traversal.
Do not feed untrusted absolute URLs into urljoin and assume the configured host remains in control: an absolute reference can replace it. This client builds query strings on a fixed resource URL. For item lookup, validate or encode the SKU as one path component rather than concatenating arbitrary slashes or accepting server-supplied next URLs blindly.
Document which exceptions mean transport failure, missing product, invalid response and exhausted pagination. Tests should inspect requested URLs and timeout values as well as returned products. Add fixtures for a repeated page, missing next_page, duplicate SKU, boolean quantity and a page limit reached before completion. A typed public model can later replace tuples without changing where validation belongs.
Controlled relative-URL warm-up
Python 3.10+. Save as lesson99.py and run locally. The sample is deterministic and does not make external requests.
from urllib.parse import urljoin
base='https://example.org/api/'
print(urljoin(base,'products/7'))
Expected output:
https://example.org/api/products/7
This warm-up demonstrates one controlled relative reference. It is not a complete client. An absolute second argument can replace the host; the reusable client above builds queries on a fixed resource URL and uses an injected transport.
Walkthrough
Trace the input value, the library operation and the output. Explain what the same concept would mean for a real HTTPS request. Change one input and predict the effect. For real services, check timeouts, response status, content type and JSON structure before trusting the response.
Additional validation example
def validate_page(page):
if isinstance(page,bool) or not isinstance(page,int) or page < 1:
raise ValueError("page must be a positive integer")
return page
assert validate_page(2)==2
print("Page accepted")
Expected: Page accepted. Validation prevents invalid pagination requests.
Guided real-world project
Create a validated API client with timeouts, bounded pagination and test doubles, returning SKU/quantity tuples. A later extension may add a typed public model.
- Write a requirements specification and sample JSON schema.
- Separate transport, validation, domain logic and persistence layers.
- Implement the simplest successful request/response scenario.
- Handle malformed input, missing resources and authorization failures.
- Test pagination boundaries, timeouts or rate limits where applicable.
- Document setup, security assumptions and rollback procedures.
Acceptance criteria: predictable behavior, no exposed credentials, tests for at least three failure conditions and documented error responses. This project is assigned for implementation; it has not been independently deployed or tested.
Common mistakes and debugging
- Sending credentials through query parameters or printing them in logs.
- Retrying non-idempotent operations without safeguards.
- Ignoring response status, timeouts or malformed JSON.
- Using unchecked URLs from untrusted sources.
- Assuming client-side validation replaces server-side authorization.
Debug by reproducing the request with a safe mock, checking status and headers, inspecting sanitized payloads, and adding regression tests.
Practice with explained answers
Make a prediction before opening each answer. Then trace the example and explain the result in your own words.
Optional hint for question 1
Separate HTTP mechanics from the validated inventory values returned to a caller.
1. Why inject a transport instead of calling urlopen everywhere?
It separates HTTP mechanics from inventory behavior and enables deterministic tests. A single adapter can enforce consistent timeouts, limits and error mapping.
2. Why reject a missing next_page instead of treating it as null?
The documented contract requires the field. Treating absence as completion could silently truncate results after a provider bug or schema change.
3. Does max_pages make list_products constant-memory?
No. It accumulates every accepted product. It bounds the number of requests, while response limits bound each page; a streaming interface is a separate design.
4. How can urljoin change a supposedly fixed host?
An absolute second argument overrides the base URL. Validate dynamic destinations or build only controlled relative components rather than trusting arbitrary next URLs.
5. Why reject a pagination value that does not advance?
It detects repeated or backward page states before an endless loop. The separate max_pages cap also catches endless increasing sequences.
Mastery checkpoint
Reproduce the sample, explain the protocol implications, complete the project specification, and write at least three meaningful tests. Video and account-synchronized completion are not yet available.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.