Module 16 · External Libraries and APIs — topic 11 of 12
JSON responses
Working with API responses: navigating nested JSON, handling missing fields and error payloads, validating structure, paginated results, and flattening data for further processing.
Learning objectives
- Navigate nested JSON responses
- Handle missing fields, error payloads and invalid JSON
- Collect paginated results and flatten records
Definition
Most APIs return JSON documents describing results or errors. Working with them means parsing the text, navigating nested dictionaries and lists, coping with missing or unexpected fields, and transforming the data into the shape your program needs.
Introduction
An API response is rarely a flat list: users contain addresses, orders contain items, and results arrive one page at a time. Extracting what you need takes a few careful patterns.
Why it matters
Real responses change, omit fields and report errors in their own formats. Defensive handling keeps programs working when the data isn't perfect.
Detailed explanation
Parse with json.loads (or response.json()); then use normal dictionary and list operations.
Navigate step by step: resp["data"]["user"]["name"]. For optional fields use .get with defaults to avoid KeyError.
Many APIs wrap results in an envelope such as {"status": ..., "data": ..., "meta": ...} and report errors as {"error": {"code": ..., "message": ...}}.
Check the status (HTTP code and any status field) before reading data.
Large collections are paginated: each response includes items plus a next page number, cursor or URL. Loop until there is no next page — a generator keeps this tidy.
Flatten nested records into simple tuples or rows for CSV export, databases or pandas.
Validate assumptions (types, required keys) at the boundary, and fail with clear messages when the shape is wrong.
Syntax
- Navigate nested dicts and lists.
- Use .get for optional fields.
- Check status before using data.
Code examples
Navigating nested data
Asha ['admin', 'editor'] Python tips no next_page field
Errors and invalid JSON
temp: 31.5 API error 429: rate limited invalid JSON
More examples
Collecting paginated results
[(1, 'pen', 20), (2, 'book', 250), (3, 'bag', 1200)] total: 1470
Step-by-step explanation
- Each page is JSON text, as an API would return; null becomes None.
- The generator keeps requesting pages until next is None, yielding items one at a time.
- The comprehension flattens each nested item into a simple (id, name, amount) row.
Expected output
Running “Collecting paginated results” prints exactly:
Practical applications
- Downloading all of a user's repositories or orders page by page.
- Converting API data into CSV reports.
Best practices
- Check status and error fields first.
- Use .get for optional data and fail clearly on required data.
- Handle pagination with a generator.
Common mistakes
Assuming optional fields exist
Avoid
Prefer
Missing optional data shouldn't crash the program.
Reading only the first page
Avoid
Prefer
Paginated APIs return only part of the data per request.
Important notes
- Validation libraries such as pydantic turn JSON into typed objects and report shape errors precisely.
Key takeaways
- Navigate nested JSON step by step.
- Handle errors, missing fields and invalid JSON.
- Follow pagination and flatten records.
Try it yourself
- 1Given a nested weather response, print each day's date with its minimum and maximum temperature.
- 2Write a function that safely reads a deeply nested key path and returns a default if any level is missing.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
Test yourself across the whole course in the Python practice bank.