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

Python JSON & APIs

An API is a menu a website offers so programs can ask for information, and JSON is the neat format the answer comes in. Python reads the answer and picks out what it needs.
Syntax
python
import requests

response = requests.get("api_url", params={"key": value})
data = response.json()

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())  # parses the JSON body directly into a dict

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"})  # builds the query string automatically
    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()  # explicitly raises for a failing status code
    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"}  # common way to send an API key
    requests.get("https://api.example.com/data", headers=headers)
    print("Sent with Authorization header")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Calling response.json() on a reply that is not JSON, which raises an error such as JSONDecodeError.
  2. Putting query values into the URL by hand, when params={...} encodes them safely.
  3. Hard-coding an API key in code that is shared or committed, instead of reading it from an environment variable.

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.