typestar

Handling request errors in Python

Catching the specific ways an HTTP call can fail.

import requests

try:
    response = requests.get("https://api.example.com/data", timeout=5)
    response.raise_for_status()
    payload = response.json()
except requests.Timeout:
    payload = {"error": "timed out"}
except requests.HTTPError as exc:
    payload = {"error": f"status {exc.response.status_code}"}
except requests.RequestException:
    payload = {"error": "request failed"}

How it works

  1. Timeout fires when the server is too slow.
  2. HTTPError carries the failing status code.
  3. RequestException is the catch-all base.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
364
Tokens
88
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 50 seconds.

Type this snippet

Step 4 of 5 in requests, step 4 of 9 in Web scraping.

← Previous Next →