Tutorials / Python: Intermediate to Advanced / Working with HTTP APIs and JSON

Working with HTTP APIs and JSON

15 min read python
Course contents (15 lessons)
  1. Iteration the Python way
  2. List, dict and set comprehensions
  3. Iterators and generators
  4. Functions as building blocks
  5. Closures and decorators
  6. Context managers and the with statement
  7. Object-oriented Python in depth
  8. Classes and dataclasses
  9. Properties and special (dunder) methods
  10. Inheritance versus composition
  11. Quality: types, packaging and tests
  12. Type hints and mypy
  13. Packaging a project with pyproject.toml
  14. Testing with pytest
  15. Async code and web APIs
  16. async and await with asyncio
  17. Working with HTTP APIs and JSON
  18. Performance, concurrency and a final project
  19. Performance and profiling
  20. Concurrency: threads versus processes
  21. Final project: a price tracker command-line tool

APIs are how programs talk

A REST API is a web address that returns data instead of a page. You send an HTTP request, and you get an HTTP response with a status code and usually a JSON body. Weather, payments, maps and your own company's services all work this way.

We will use Open-Meteo, a free weather API that needs no key. It returns the current weather for a latitude and longitude. I use it in demos because nobody has to sign up for anything.

A first request

import requests

URL = "https://api.open-meteo.com/v1/forecast"


def current_weather(latitude: float, longitude: float) -> dict:
    params = {
        "latitude": latitude,
        "longitude": longitude,
        "current": "temperature_2m,wind_speed_10m",
    }
    response = requests.get(URL, params=params, timeout=10)
    response.raise_for_status()          # raise an error for 4xx and 5xx
    return response.json()["current"]


if __name__ == "__main__":
    lahore = current_weather(31.5204, 74.3587)
    print(f"Lahore: {lahore['temperature_2m']} C, wind {lahore['wind_speed_10m']} km/h")

The output looks like Lahore: 24.3 C, wind 8.1 km/h, with whatever the weather is when you run it. Install the library first with pip install requests.

What each part does

The params dictionary is turned into a query string and properly encoded. Never build URLs by gluing strings together, because special characters will break them. The timeout is the most important argument. Without it, requests waits forever if the server does not answer. That is the number one mistake in scripts that call APIs: one day the server stalls, and your program hangs with it. Always set a timeout.

raise_for_status() turns an error status such as 404 or 500 into an exception, so you do not process an error page as if it were data. Then .json() parses the body into dictionaries and lists.

Handling failures

Networks fail. Plan for it.

import time
import requests


def get_json(url: str, params: dict | None = None, retries: int = 3) -> dict:
    last_error: Exception | None = None
    for attempt in range(1, retries + 1):
        try:
            response = requests.get(url, params=params, timeout=10)
            if response.status_code == 429 or response.status_code >= 500:
                raise requests.HTTPError(f"server returned {response.status_code}")
            response.raise_for_status()
            return response.json()
        except (requests.ConnectionError, requests.Timeout, requests.HTTPError) as error:
            last_error = error
            time.sleep(2 ** attempt * 0.5)     # 1s, 2s, 4s: back off
    raise RuntimeError(f"giving up after {retries} attempts") from last_error

We retry only the cases that might work on a second try: connection problems, timeouts, server errors and rate limiting (429). A 404 or 400 is our own fault, and retrying will not help. Waiting longer after each failure, called exponential backoff, avoids hammering a server that is already struggling. Be careful with retries on requests that change data, such as creating an order, since a retry could create it twice.

Sending data

payload = {"title": "Pay bill", "done": False}
response = requests.post("https://example.com/api/tasks", json=payload, timeout=10)
print(response.status_code)       # 201 means created

Passing json= encodes the dictionary and sets the right header. For private APIs you normally send a key in a header, for example headers={"Authorization": f"Bearer {token}"}. Keep tokens in environment variables, never in your source code.

Sessions

If you make many calls to the same server, use a Session. It reuses the connection, which is faster, and shares headers.

with requests.Session() as session:
    session.headers["Accept"] = "application/json"
    for city in [(31.52, 74.36), (24.86, 67.01)]:
        r = session.get(URL, params={"latitude": city[0], "longitude": city[1], "current": "temperature_2m"}, timeout=10)
        print(r.json()["current"]["temperature_2m"])

JSON and Python types

JSON objects become dictionaries, arrays become lists, and null becomes None. Numbers become int or float. Never trust the shape of data from outside. A field can be missing or null on one record out of a thousand. Use .get() with defaults, or validate the data into a dataclass or a pydantic model at the boundary of your program.

from dataclasses import dataclass

@dataclass
class Weather:
    temperature: float
    wind: float

    @classmethod
    def from_api(cls, data: dict) -> "Weather":
        return cls(float(data["temperature_2m"]), float(data["wind_speed_10m"]))

The async version

For many requests at once, use httpx with the asyncio ideas from the last lesson.

import asyncio
import httpx

async def fetch_all(places):
    async with httpx.AsyncClient(timeout=10) as client:
        tasks = [client.get(URL, params={"latitude": la, "longitude": lo,
                                         "current": "temperature_2m"})
                 for la, lo in places]
        responses = await asyncio.gather(*tasks)
    return [r.json()["current"]["temperature_2m"] for r in responses]

Good API manners

  • Read the documentation for rate limits and respect them.
  • Cache results that do not change often, such as a currency rate that is updated daily.
  • Log the status code and URL (without secrets) when something fails.

Try it yourself

Write a script that asks for a city name from a small dictionary of coordinates you define, fetches the current temperature, and prints it. Add a timeout, handle connection errors with a friendly message, and cache the answer in a JSON file for ten minutes so repeated runs do not call the API again.

python
import requests

URL = "https://api.open-meteo.com/v1/forecast"


def current_weather(latitude: float, longitude: float) -> dict:
    params = {
        "latitude": latitude,
        "longitude": longitude,
        "current": "temperature_2m,wind_speed_10m",
    }
    response = requests.get(URL, params=params, timeout=10)
    response.raise_for_status()          # raise an error for 4xx and 5xx
    return response.json()["current"]


if __name__ == "__main__":
    lahore = current_weather(31.5204, 74.3587)
    print(f"Lahore: {lahore['temperature_2m']} C, wind {lahore['wind_speed_10m']} km/h")

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account