http and apis — making the call9 / 9
status codes and error handling — what ai's api calls do when the wire blinks
Checkpoint
One last thing before we move on. Same surface as a write step — but the lesson doesn't complete until this passes.
Last drill. Write a function safe_fetch(response) that takes a
fake response dict (with status and body keys) and returns:
- The dict's
bodyif the status is 2xx (success). - The string
"not found"for status 404 specifically. - The string
"client error"for any other 4xx. - The string
"retry later"for any 5xx. - Raise
ValueError(f"unexpected status: {status}")for anything else (1xx, 3xx).
The starter has four responses to pass through. Use the bottom loop as-is.
Expected output:
{'id': 7}
not found
client error
retry later
⌘↵ runs the editor.
Booting Python…
Output
[promptdojo:~]$ _