Python JSON & APIs
In this page:
What is an API?
An API (Application Programming Interface) is a defined contract that lets separate systems exchange data programmatically, most commonly by returning structured JSON that any client language can parse without special tooling.
Example: What is an API?
# APIs typically exchange data as JSON
import json
print(json.dumps({"status": "ok"}))
Parsing JSON Responses
After fetching data with requests, calling .json() on the response parses the raw JSON body directly into native Python dictionaries and lists, skipping the manual step of calling json.loads() on the response text yourself.
Example: Parsing JSON Responses
from unittest.mock import patch
import requests
with patch("requests.get") as mock_get:
mock_get.return_value.json.return_value = {"id": 1, "name": "Alex"}
response = requests.get("https://api.example.com/user/1")
print(response.json())
Query Parameters
Many APIs support filtering or customizing results through query parameters appended to the URL. Passing a dictionary to requests.get(url, params={...}) builds the correctly-encoded query string for you, handling special characters that would otherwise need manual URL-escaping.
Example: Query Parameters
from unittest.mock import patch
import requests
with patch("requests.get") as mock_get:
mock_get.return_value.status_code = 200
requests.get("https://api.example.com/search", params={"q": "python"})
mock_get.assert_called_with("https://api.example.com/search", params={"q": "python"})
print("Query sent")
Handling HTTP Errors
Not every failed request raises an exception on its own -- a 404 or 500 response still returns normally as far as requests is concerned. Calling .raise_for_status() on the response explicitly raises an HTTPError if the status code indicates failure, which is the reliable way to catch API errors instead of silently working with bad data.
Example: Handling HTTP Errors
from unittest.mock import patch
import requests
with patch("requests.get") as mock_get:
mock_get.return_value.raise_for_status.side_effect = requests.exceptions.HTTPError("404")
response = requests.get("https://api.example.com/missing")
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print("HTTP error:", e)
API Keys and Authorization
Most non-trivial public APIs require registering for an API key to authenticate requests and enforce rate limits. That key is typically sent either as a custom request header (like Authorization: Bearer <key>) or as one of the query parameters, depending on what the specific API documents.
Example: API Keys and Authorization
from unittest.mock import patch
import requests
with patch("requests.get") as mock_get:
mock_get.return_value.status_code = 200
headers = {"Authorization": "Bearer my-api-key"}
requests.get("https://api.example.com/data", headers=headers)
print("Sent with Authorization header")
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first:
- Python NumPy Introduction
- Python NumPy Arrays
- Python Pandas Introduction
- Python Pandas DataFrame
- Python Matplotlib Basics
- Python Data Visualization
- Python Statistics Module
- Python CSV & Data Analysis
- Python requests Module
- Python JSON & APIs
- Python Web Scraping Basics
- Python Flask Introduction
- Python Django Introduction
- Python MongoDB