Parsing nested API responses — without crashing on a missing key — step 7 of 9
AI wrote a parser that uses chained .get without defaults. When a
field is missing, the chain returns None and the function quietly
returns None. The caller has no idea anything went wrong, so the
bug surfaces somewhere unrelated.
Fix the function to raise ValueError(f"missing field: {field}")
whenever the field can't be found. Specifically:
- If
choicesis missing or the list is empty, raise with field"choices". - If
messageis missing on the first choice, raise with field"message". - If
contentis missing, raise with field"content".
The starter has a response missing content. Wrap the call in
try/except ValueError as err: print(err).
Expected output:
missing field: content
AI wrote a parser that uses chained .get without defaults. When a
field is missing, the chain returns None and the function quietly
returns None. The caller has no idea anything went wrong, so the
bug surfaces somewhere unrelated.
Fix the function to raise ValueError(f"missing field: {field}")
whenever the field can't be found. Specifically:
- If
choicesis missing or the list is empty, raise with field"choices". - If
messageis missing on the first choice, raise with field"message". - If
contentis missing, raise with field"content".
The starter has a response missing content. Wrap the call in
try/except ValueError as err: print(err).
Expected output:
missing field: content
this step needs the editor
on desktop today; in the app (coming soon). save your spot and we'll bring you back here when you're ready.