logo

JSON with APIs

Most web APIs speak JSON. The requests library makes this easy.

Receiving JSON:

import requests

response = requests.get("https://api.example.com/users")
data = response.json()  # Automatically parses JSON
print(data[0]["name"])

The .json() method parses the response body directly - no need to call json.loads() yourself.

Sending JSON:

payload = {"name": "Alice", "email": "alice@example.com"}
response = requests.post(
    "https://api.example.com/users",
    json=payload  # Automatically serializes and sets headers
)

Using json=payload does three things: serializes your dict to JSON, sets the Content-Type header, and sends it as the request body.

This pattern covers most API interactions.

I explain API patterns in my JSON with Python course.