Call a REST API with `requests`, handle timeouts and non-2xx responses properly.

BeginnerHands-onPython for DevOps
Answer
import requests

try:
    r = requests.get(
        "https://api.github.com/repos/kubernetes/kubernetes",
        headers={"Accept": "application/vnd.github+json"},
        timeout=(3.05, 10),  # connect, read
    )
    r.raise_for_status()
    print(r.json()["stargazers_count"])
except requests.exceptions.Timeout:
    print("Request timed out")
except requests.exceptions.HTTPError as e:
    print(f"HTTP error: {e.response.status_code} {e.response.text[:200]}")

Key trick → requests has no default timeout, so a call without one can hang forever. raise_for_status() turns 4xx/5xx into exceptions.

All Real-World Interview questions Roadmap: Interview readiness

More on Python for DevOps