Skip to content

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.

Beginner 10 min read·Lesson 245 of 306 in Python Programming

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

Python
body = json.loads(text)
if body.get("status") != "ok":
raise RuntimeError(body.get("error", {}).get("message", "unknown error"))
name = body["data"]["user"].get("name", "unknown")
  • Navigate nested dicts and lists.
  • Use .get for optional fields.
  • Check status before using data.

Code examples

Navigating nested data

Python
import json
raw = '{"status": "ok", "data": {"user": {"id": 7, "name": "Asha", "roles": ["admin", "editor"]}, "posts": [{"id": 1, "title": "Hello", "likes": 12}, {"id": 2, "title": "Python tips", "likes": 40}]}, "meta": {"page": 1}}'
resp = json.loads(raw)
user = resp["data"]["user"]
print(user["name"], user["roles"])
print(max(resp["data"]["posts"], key=lambda p: p["likes"])["title"])
print(resp["meta"].get("next_page", "no next_page field"))
Output
Asha ['admin', 'editor']
Python tips
no next_page field

Errors and invalid JSON

Python
import json
responses = [
'{"status": "ok", "data": {"temp": 31.5}}',
'{"status": "error", "error": {"code": 429, "message": "rate limited"}}',
'not json at all',
]
for text in responses:
try:
body = json.loads(text)
except json.JSONDecodeError:
print("invalid JSON")
continue
if body.get("status") == "ok":
print("temp:", body["data"]["temp"])
else:
err = body.get("error", {})
print(f"API error {err.get('code')}: {err.get('message')}")
Output
temp: 31.5
API error 429: rate limited
invalid JSON

More examples

Collecting paginated results

Python
import json
PAGES = {
1: '{"items": [{"id": 1, "name": "pen", "price": {"amount": 20}}, {"id": 2, "name": "book", "price": {"amount": 250}}], "next": 2}',
2: '{"items": [{"id": 3, "name": "bag", "price": {"amount": 1200}}], "next": null}',
}
def fetch_page(n):
return json.loads(PAGES[n]) # stands in for an HTTP request
def all_items():
page = 1
while page is not None:
data = fetch_page(page)
yield from data["items"]
page = data["next"]
rows = [(item["id"], item["name"], item["price"]["amount"]) for item in all_items()]
print(rows)
print("total:", sum(r[2] for r in rows))
Output
[(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:

TextOutput
[(1, 'pen', 20), (2, 'book', 250), (3, 'bag', 1200)]
total: 1470

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

phone = user["contact"]["phone"]

Prefer

phone = user.get("contact", {}).get("phone")

Missing optional data shouldn't crash the program.

Reading only the first page

Avoid

items = fetch_page(1)["items"]

Prefer

items = list(all_items())

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

  1. 1
    Given a nested weather response, print each day's date with its minimum and maximum temperature.
  2. 2
    Write 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.