Intermediate Chapter 165 · 30 min read · Module 12: Python Database and APIs
JSON API Responses
- After this chapter you can explain what JSON is and how its types map to Python types.
- You can convert a JSON string into Python data with json.loads and back with json.dumps.
- You can read nested dictionaries and lists from an API response.
- You can use .get() and defaults to handle missing fields safely.
- You can catch invalid JSON and work with pagination style responses.
When your program talks to a web service, the answer usually comes back as text written in a format called JSON. JSON is short for JavaScript Object Notation, but you do not need to know JavaScript to use it. It is simply a way to write objects, lists, numbers and words so that two different programs can understand each other.
Python has a built-in json module that does the hard work. It can read a JSON text and give you normal Python dictionaries and lists, and it can turn your Python data back into JSON text. Once the data is in Python form, you can use all the tools you already know: indexing, loops, comprehensions and f-strings.
In this chapter we use small JSON strings that look like real API responses, so every example runs on your own computer without internet. The same code works on real responses too, because a real response body is just a longer piece of the same text.
What does an API response look like?
An API (Application Programming Interface) is a door that lets one program ask another program for data. A weather service, a book catalog or a payment system can all offer an API. You send a request, and the server sends back a response. The response has a status code such as 200 for success, some headers, and a body. For most modern APIs the body is JSON.
JSON text looks very much like a Python dictionary, but it is only text until you parse it. It has objects in curly braces, arrays in square brackets, strings in double quotes, numbers, the words true and false, and null. Keys in an object must always be strings in double quotes.
JSON types and Python types
| JSON | Python |
|---|---|
| object {} | dict |
| array [] | list |
| string | str |
| number without dot | int |
| number with dot | float |
| true / false | True / False |
| null | None |
Notice that the words true, false and null are written in lowercase in JSON, while Python uses True, False and None. The json module converts between them for you, so you never need to change the spelling yourself.
Reading JSON with json.loads
The function json.loads() takes a string and returns Python data. The letter s means string. There is also json.load() without the s, which reads from an open file. In an API program you usually have the body as a string, so loads is the one you meet most often.
import json
body = '{"id": 7, "name": "Asha", "active": true, "manager": null, "score": 4.5}'
data = json.loads(body)
print(type(data).__name__)
print(data["name"])
print(data["active"], data["manager"])
print(data["score"] + 1)After parsing, data is an ordinary dictionary. The true became True and the null became None. The number 4.5 became a float, so we can add 1 to it. Remember that the original body is still just a string, and changing data does not change it.
Nested data and lists
Real responses are rarely flat. A user object may contain an address object, and a list of orders may contain many small objects. You reach inside by chaining square brackets: use a key for an object and a number for an array. Read the structure from the outside in, one level at a time.
import json
body = """
{
"user": {"name": "Ravi", "address": {"city": "Pune", "pin": "411001"}},
"orders": [
{"id": 1, "total": 250.0},
{"id": 2, "total": 99.5}
]
}
"""
data = json.loads(body)
print(data["user"]["address"]["city"])
print(len(data["orders"]))
print(data["orders"][1]["id"])
total = sum(o["total"] for o in data["orders"])
print(total)A generator expression such as sum(o["total"] for o in data["orders"]) is a short way to add a field from every item in a list. This pattern is very common when you work with lists of records from an API.
Missing keys and safe access
APIs change over time, and some fields are optional. If you write data["phone"] and the key is not there, Python raises a KeyError and your program stops. The method .get(key, default) returns the default instead. For nested data you can chain .get() calls, giving an empty dictionary as the default for the middle steps.
import json
data = json.loads('{"name": "Meera", "profile": {"bio": "Likes maps"}}')
print(data.get("phone", "not given"))
print(data.get("profile", {}).get("bio", "none"))
print(data.get("settings", {}).get("theme", "light"))
try:
print(data["phone"])
except KeyError as e:
print("missing key:", e)Writing JSON with json.dumps
When you send data to an API, for example in a POST request, you need to turn Python data into JSON text. The function json.dumps() does that. Useful options are indent for a readable layout and sort_keys=True for a stable key order. Only some Python types can be written. Dictionaries, lists, strings, numbers, booleans and None work, but sets, dates and custom objects need to be converted first.
import json
payload = {"title": "Learn JSON", "done": False, "tags": ["python", "api"], "due": None}
print(json.dumps(payload))
print(json.dumps(payload, indent=2, sort_keys=True))Look at the output: False became false and None became null. The compact form is good for sending over the network, and the indented form is good for reading.
Invalid JSON
Servers sometimes send an error page in HTML or an empty body instead of JSON. Parsing it raises json.JSONDecodeError, which is a subclass of ValueError. Always wrap parsing of outside data in try and except. A common mistake is using single quotes in the text, because JSON allows only double quotes.
import json
for text in ['{"ok": true}', "{'ok': true}", ""]:
try:
print(json.loads(text))
except json.JSONDecodeError as e:
print("bad json:", e.msg)Pagination and envelopes
Many APIs do not return a bare list. They wrap the list in an envelope, an object with extra fields such as count, page and next. The real records are inside a key like results or data. To get everything, you loop through pages until next is null. Reading the documentation of the API tells you the exact names.
import json
pages = [
'{"results": ["a", "b"], "next": 2}',
'{"results": ["c"], "next": null}',
]
items = []
for text in pages:
page = json.loads(text)
items.extend(page["results"])
if page["next"] is None:
break
print(items)In a real program each page would come from a new request, but the parsing logic is the same. With requests you can call response.json(), which does json.loads on the body for you.
import requests
response = requests.get("https://api.example.com/users/7", timeout=10)
data = response.json()
print(data["name"])Python syntax
import json
data = json.loads(text) # str -> Python
text = json.dumps(data) # Python -> strvalue = data.get("key", default)
nested = data["a"]["b"][0]json.dumps(data, indent=2, sort_keys=True)Real-world applications
- Reading weather, news or currency data from public APIs.
- Sending form data to a server as a JSON body.
- Saving program settings in a .json file.
- Processing exported data from tools such as databases and analytics services.
Common mistakes
Fix: Call json.loads(body) or response.json() first; a body is only a string.
Fix: JSON needs double quotes. Build the text with json.dumps instead of typing it by hand.
Fix: Use data.get('key', default) for fields that may be missing.
Fix: Compare with None using is None.
Important tips
- Print the parsed data with json.dumps(data, indent=2) to understand its shape quickly.
- Read the API documentation to learn which fields are optional.
- Keep sample responses as strings in your tests so they run without the network.
Key points summary
- JSON is text; Python dict and list are data.
- json.loads parses a string, json.dumps writes a string.
- true, false and null become True, False and None.
- Use .get() for optional fields.
- Invalid JSON raises json.JSONDecodeError.
Exam and interview points
- Know the table of JSON to Python type conversions.
- json.loads and json.dumps work with strings; load and dump work with files.
- JSONDecodeError is a subclass of ValueError.
- dict.get returns None or a default instead of raising KeyError.
Quick revision
- loads: str to Python.
- dumps: Python to str.
- null is None.
- Use get for optional keys.
- Wrap parsing in try/except.
Frequently asked questions
What is the difference between json.load and json.loads?
load reads from a file object, while loads reads from a string. The s stands for string.
Why does my dictionary print with single quotes but JSON needs double quotes?
Printing a dict shows Python's own format. JSON is a different text format, so use json.dumps to produce real JSON.
Can JSON store dates?
Not directly. Dates are usually sent as strings such as 2025-01-31 and you convert them yourself with the datetime module.
Are the keys in a parsed dictionary always strings?
Yes, JSON object keys are always strings, so a key like 1 becomes the string '1' after a round trip.
Practise this chapter
20 practice questions Take the chapter quiz