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
Timeoutfires when the server is too slow.HTTPErrorcarries the failing status code.RequestExceptionis the catch-all base.
Keywords and builtins used here
asexcepttry
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.
Step 4 of 5 in requests, step 4 of 9 in Web scraping.