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.
More on Python for DevOps
Write a Python script using boto3 that lists all running EC2 instances with their Name tag.BeginnerWrite a script that finds unattached EBS volumes and deletes them (with a dry-run flag).IntermediateAdd retry with exponential backoff to HTTP calls without writing the loop yourself.IntermediateWrite your own retry decorator with exponential backoff and jitter.AdvancedParse a YAML file and print every container image in a multi-document Kubernetes manifest.IntermediateRun a shell command from Python, capture output, and fail properly on error.Intermediate