Reading a Response Safely

Parse, then check, then use. Skipping the middle step is where most crashes in data code come from.

A field present in the response you looked at is not necessarily present in all of them. Real data has missing keys, nulls where you expected an object, empty arrays, and occasionally a field that is a string in one record and a number in the next.

Reaching into a response

Python

# raises when absent
data["author"]["name"]

# survives
(data.get("author") or {}).get("name", "")

for tag in data.get("tags") or []:
    ...

JavaScript

// throws when absent
data.author.name

// survives
data?.author?.name ?? ""

for (const t of data.tags ?? []) {
}
Compare → The `or {}` and the `?? []` handle the case people forget: the key exists but its value is null, which is different from the key being missing and breaks the naive fix.

✦ An error can arrive with status 200

Some APIs return a perfectly successful HTTP response whose body says the request failed. Always check the body's own success or error field as well as the status code, or you will treat an error message as data and wonder why your counts are wrong.

◈ Graded Challenge

Write extract(record) pulling a clean summary out of one messy API record. Return an object with three keys. title is record's title, or "Untitled" when it is missing, null or an empty string. year is record's year as a number, or null when it is missing, null, or cannot be read as a whole number. tags is record's tags when it is a list, or an empty list otherwise, including when it is null or a string.

Name it exactly: extract(record)

3 visible + 5 hidden
loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back