http and apis — making the call6 / 9
status codes and error handling — what ai's api calls do when the wire blinks
Claude wrote a fetcher that calls .json() straight away without
checking the status. The fake response below is a 401 with a JSON
error body. The function returns data["name"], which doesn't exist
in the error body, so it crashes with a KeyError — pointing at the
wrong line.
Add an if response.status_code != 200: return None guard before
the .json() call so the function returns None cleanly when the
request failed.
Expected output:
None
The break is on line 2 — but read the whole snippet first.
⌘↵ runs the editor.
Booting Python…
Output
[promptdojo:~]$ _