BeginnerLesson 2 of 126 min read

Reading JSON Responses Defensively: Types, Nulls, Dates and Big Numbers

Parse API responses safely: handle money as strings or integers, nulls and missing fields, ISO 8601 dates with time zones and numbers too large for JavaScript, and see a real precision bug by comparing Python and Node.js.

In this lesson you will

  • Validate the shape of a response
  • Handle null, missing and unknown fields
  • Parse dates with time zones
  • Avoid losing big integers

About 28 minutes

The API said it was a number

A response that has parsed without error is not necessarily correct. Noor’s code read an order from the courier’s API and showed a price of 12.5 euros for a plant that cost 12.50, then a delivery date one day early for a customer in New York, and later it showed a parcel with the wrong id. Each is a classic integration bug, and each comes from believing that JSON means what it appears to mean. JSON has only a few types: strings, numbers, booleans, null, arrays and objects. Everything else, money, dates, identifiers and enumerations, is a convention that the API documents and your code must honour.

Money should never be a floating point number. Good APIs send integer amounts in the smallest unit, such as cents, or a string like “12.50”, and your code should parse a string with the decimal type and keep amounts as integers. Dates arrive as strings in ISO 8601 format, which may carry a time zone offset, such as 2024-03-10T23:30:00-05:00, and must be converted to a single zone, usually UTC, before comparing or storing. Identifiers can be 64-bit integers, which JavaScript cannot represent exactly, because its numbers are 64-bit floating point with 53 bits of precision, so providers often send them as strings. Finally, fields can be null or missing, and new fields may appear without notice: ignore unknown ones, and handle the absence of optional ones.

Pitfall Safe habit
Price as float Integer cents or Decimal from a string
Date with offset Parse, convert to UTC
64-bit integer id Treat ids as strings
null or missing field Default or explicit error
Unknown new field Ignore it
Enum value you do not know Map to “unknown”, log it
import json, subprocess
from decimal import Decimal
from datetime import datetime, timezone

payload = """{
  "id": 9007199254740993,
  "ref": "A-1001",
  "total": "12.50",
  "float_total": 12.5,
  "currency": "EUR",
  "shipped_at": "2024-03-10T23:30:00-05:00",
  "delivered_at": null,
  "status": "partially_refunded",
  "items": [{"sku": "fern", "qty": 2, "unit_cents": 450}, {"sku": "cactus", "qty": 1}],
  "new_field_added_last_week": {"anything": true}
}"""
data = json.loads(payload)

def money(s): return int((Decimal(s) * 100).to_integral_value())
KNOWN = {"pending", "paid", "shipped", "refunded"}
def parse(d):
    out = {"id": str(d["id"]), "total_cents": money(d["total"]), "currency": d["currency"]}
    out["shipped_utc"] = datetime.fromisoformat(d["shipped_at"]).astimezone(timezone.utc).isoformat()
    out["delivered"] = d.get("delivered_at") is not None
    out["status"] = d["status"] if d["status"] in KNOWN else "unknown(" + d["status"] + ")"
    out["lines"] = [(i["sku"], i["qty"], i.get("unit_cents")) for i in d["items"]]
    out["known_total_cents"] = sum(q * c for _, q, c in out["lines"] if c is not None)
    return out
p = parse(data)
print("id kept exactly:", p["id"], "| total in cents:", p["total_cents"], "| float is exact here:", data["float_total"] == 12.5)
print("shipped at (UTC):", p["shipped_utc"], "| delivered yet:", p["delivered"], "| status:", p["status"])
print("lines:", p["lines"], "| known total:", p["known_total_cents"], "cents")
print("float sum 0.1 + 0.2 =", 0.1 + 0.2, "| Decimal sum =", Decimal("0.1") + Decimal("0.2"))
js = subprocess.run(["node", "-e", "const d = JSON.parse(process.argv[1]); console.log(String(d.id), Number.isSafeInteger(d.id))", payload], capture_output=True, text=True).stdout.strip()
print("the same id parsed by JavaScript:", js)
print("DATA " + json.dumps({"p": p, "js": js}))
id kept exactly: 9007199254740993 | total in cents: 1250 | float is exact here: True
shipped at (UTC): 2024-03-11T04:30:00+00:00 | delivered yet: False | status: unknown(partially_refunded)
lines: [('fern', 2, 450), ('cactus', 1, None)] | known total: 900 cents
float sum 0.1 + 0.2 = 0.30000000000000004 | Decimal sum = 0.3
the same id parsed by JavaScript: 9007199254740992 false

The program parsed one response with six traps in it. The order id 9007199254740993 was kept exactly, as the string 9007199254740993, because Python integers have no size limit. The total arrived as the string “12.50” and was converted with the decimal type to 1250 cents, not to a float. The shipping time 23:30 with an offset of minus five hours is 04:30 the next day in UTC, 2024-03-11T04:30:00+00:00: a system that compared the local time of a New York warehouse with a European customer’s date without converting would be a day out. The field delivered_at was null, so the order is not delivered yet, and a missing unit price on the cactus line was handled with get, so the known total of 900 cents counts only the fern lines, 2 x 450, and the code can report that one price is unknown, which is better than guessing zero.

The status “partially_refunded” is not in the list of values that the code knows, so it was mapped to unknown(partially_refunded) instead of crashing, and an unknown field that appeared “last week” was ignored. These two habits, tolerating additions and handling unexpected enumeration values, are what keep an integration working when the provider changes the API in a compatible way, and a log line for the unknown value lets you notice it. The line about 0.1 + 0.2 repeats the lesson of floating point: it gives 0.30000000000000004, while the decimal type gives exactly 0.3.

The real bug shows when the same JSON is parsed by JavaScript. Node.js printed “9007199254740992 false”: the id 9007199254740993 became 9007199254740992, because a JavaScript number cannot hold it, and Number.isSafeInteger says false. Two different parcels could end up with the same id in a JavaScript system, with no error. That is why providers send large ids as strings, and why your code should treat identifiers as opaque strings and never do arithmetic on them. Independent check: Node.js itself was the second parser, and it also confirmed the date conversion, 2024-03-11T04:30:00.000Z, agreeing with Python’s UTC result.

Check by hand: 23:30 with an offset of minus 5 hours means that UTC is 5 hours ahead, 23:30 plus 5 hours is 04:30 on the next day. 12.50 euros is 1,250 cents. The largest integer that a double holds exactly is 2 to the power 53, 9,007,199,254,740,992, so 9,007,199,254,740,993 is the first integer that it cannot hold.

Do not use floats for money

Amounts in floating point accumulate rounding errors. Use integer cents or a decimal type, and round only at the end, with a rule that your accountant accepts.

Convert at the edge

Parse and validate every response in one place, converting strings to the right types and dates to UTC, and let the rest of your program work with clean internal types.

About this course

Every program in this lesson was run while the course was written, with Python 3.13 (standard library only) against small mock APIs that the lesson itself starts on a local port, and cross-checked with curl, OpenSSL, Node.js or a second calculation. The services are invented stand-ins, not real vendors: always read the current documentation of the real API you use.

Practice

Write a function that validates a response against a list of required fields and types, and returns the list of problems. Parse a date with a Z suffix and one with an offset, and compare them. Find the largest id that JavaScript represents exactly.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

How should money from an API be handled?

  1. As a float
  2. As text only
  3. As integer cents or a decimal, never a float
  4. As a date

Avoid rounding errors.

What is 2024-03-10T23:30:00-05:00 in UTC?

  1. 2024-03-10T18:30:00Z
  2. 2024-03-11T04:30:00Z
  3. 2024-03-10T23:30:00Z
  4. 2024-03-11T23:30:00Z

Add 5 hours.

Why do some APIs send ids as strings?

  1. Strings are shorter
  2. JavaScript cannot hold large integers exactly
  3. It is required by JSON
  4. Integers are slow

Above 2^53.

What should you do with an unknown field?

  1. Ignore it
  2. Crash
  3. Delete the response
  4. Retry

Tolerate additions.

What should you do with an unknown enum value?

  1. Map it to unknown and log it
  2. Crash
  3. Treat it as paid
  4. Ignore the whole response

So that you notice it.

Summary

  • JSON has few types; money, dates and ids are conventions.
  • Use integer cents or decimals, UTC dates, and string ids.
  • Handle null, missing, unknown fields and unknown enum values.
  • Parse and validate at the edge.

Next lesson

Lesson 3 covers authentication: keys, Basic, Bearer and OAuth.

Questions

Should I trust the API documentation?

Mostly, and verify. Real APIs sometimes differ from their documentation, so keep sample responses and tests, and handle surprises gracefully.

What is a schema?

A formal description of the shape of the data, which a validator can check. JSON Schema and OpenAPI are common. Check the documentation of the provider.

Why convert dates to UTC?

So that times from different zones can be compared and sorted correctly. Convert to local time only for display.

Progress is saved in this browser.