Sometimes the problem is not your request but the server. A status in the 500s, like 500 Internal Server Error, means your request was fine but the server failed while answering it: a bug, a database that is down, too much traffic. It isn't your fault, and the same request may work a minute later.
Worse than a 500 is no answer at all. By default requests.get waits as long as the server takes. Pass timeout= a number of seconds to set a limit: when it runs out, requests raises requests.exceptions.Timeout. Catch it with try and except, so your script carries on instead of crashing:
try:
response = requests.get("https://api.example.com/weather", timeout=5)
print("Weather:", response.json()["sky"])
except requests.exceptions.Timeout:
print("No weather today")
The supplier has a route for each problem: /broken always fails, and /slow takes 2 seconds to answer.
GET /broken → 500 {"error": "The supplier is down"}
GET /slow (timeout=1) → no answer after 1 second: Timeout
Your script must print:
/broken: 500 The supplier failed: The supplier is down /slow: no answer after 1 second
Your task: get /broken and print its status, and for any status of 500 or more, the error from its JSON body. Then get /slow with timeout=1 inside a try block: print its status if it answers in time, and a message if it times out.
Assignment
Follow the Coding Tutorial to handle a server error and a timeout without crashing.
Hintresponse.status_code >= 500 catches every server error at once. Inside the try block, the lines after the request run only when an answer came in time.
Free plan: 30 tutor messages. PRO is unlimited.
