← Back to Python Course | Chapter 13: Data Science & Web | Lesson 10 of 14

Python JSON & APIs

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?

python
# 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

python
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

python
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

python
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

python
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")

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.