Learn with diagrams, code, systems and practical examples.
APIs, JSON, and Data
Read structured data and prepare for real HTTP API work.
Modern Python scripts and services often exchange JSON with APIs and other systems.
Start with the idea
JSON represents objects, arrays, strings, numbers, booleans, and null values. Python can decode JSON into dictionaries and lists, then your code should validate the shape it expects.
Small working example
Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.
import json
payload = '{"name": "Maya", "active": true}'
data = json.loads(payload)
print(data["name"]) JSON represents objects, arrays, strings, numbers, booleans, and null values. Python can decode JSON into dictionaries and lists, then your code should validate the shape it expects.
- JSON maps naturally to common Python structures.
- External data is untrusted input.
- API code needs error and timeout handling.
MayaThe example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.
Common beginner mistake
Assuming external API responses always contain every field and correct type.
Validate required fields, handle error responses, timeouts, and malformed data explicitly.
Quick recap
- JSON maps naturally to common Python structures.
- External data is untrusted input.
- API code needs error and timeout handling.
Try it yourself
These are deliberately small. If you can complete them without copying the example, you are ready to continue.
- Decode a small JSON array.
- Safely read an optional field from decoded data.