1. Concept library
  2. Python Foundations
  3. Module 10: Working with APIs

Concept

Handling API errors

A request can fail in several ways: no network, a timeout, a 4xx or 5xx status, or a body that is not the JSON you expected. Good client code checks each one and reports it clearly.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Name the ways a request can fail: no network, timeout, 4xx, 5xx, bad body
  2. Write client code that checks the status before parsing the body
  3. Catch connection and timeout errors and report them clearly

In practice

A few lines that show Handling API errors doing its job.

Python
import requests

def fetch_user(name):
    try:
        r = requests.get(f"https://api.github.com/users/{name}", timeout=5)
        r.raise_for_status()
        return r.json()
    except requests.Timeout:
        raise RuntimeError("GitHub took too long")
    except requests.HTTPError as e:
        raise RuntimeError(f"GitHub said {e.response.status_code}")

The common mistake

Watch for

Calling response.json() without checking the status. A 404 or 500 often comes with an HTML or empty body, and the real error is hidden behind a confusing JSONDecodeError.

What to know first

Your roadmap puts these before Handling API errors, unless you already know them.

How it stays learned

Once a session shows you understand Handling API errors, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled
Previous in the module← JSON data