JSON and Data Exchange
Lesson opener
In one line: JSON is the text shape of the body. The field names are a business contract, not a private nickname.
Why it matters: Northline's warehouse sent "qty": "80" as text. The webshop added 10 and got "8010". The available-to-promise figure was nonsense, and a buyer was promised stock that was not there.
Before this lesson: HTTP fundamentals.
What you will be able to do
- Read a JSON object, an array, and one nested object.
- Design a payload with units, identifiers, and no ambiguous names.
- Reject a payload that fails a stated rule before it is stored.
- Tell a missing field from a field that is present and null.
Prerequisites
Lesson 2. The examples use Python's standard json module. You do not need FastAPI yet.
Objects, arrays, and validation
JSON is defined by RFC 8259 (https://www.rfc-editor.org/rfc/rfc8259). In this course:
- An object is a set of named fields:
{ "sku": "FX-100", "on_hand": 80 }. - An array is an ordered list:
[ { "bin": "A1", "qty": 40 }, { "bin": "B2", "qty": 40 } ]. - Nesting puts an object or an array inside a field.
Numbers are not strings. 80 and "80" are different JSON values. Booleans are true and false, not "yes".
Payload design rules for Northline, illustrative and signed by the integration owner:
- The identifier is stable (
sku,account_id). Display names may change. - Quantities are integers of the stock-keeping unit, and the field name says so (
on_hand). Do not send a number whose unit is undocumented. - Money is an integer of minor units plus a currency code, for example
150000and"INR"for an illustrative 1,500.00 rupees. Do not send a binary float for money in this course. - Omit a field only when the contract says omission means "leave it unchanged." Send
nullonly when the contract says null is a real value, such as "no bin assigned."
Validation checks the body after JSON parses and before the ERP is written. A failure is 422 with a list of field names, not a half-written item.
import json
payload = {
"sku": "FX-100",
"on_hand": 80,
"bins": [{"bin": "A1", "qty": 40}, {"bin": "B2", "qty": 40}],
}
raw = json.dumps(payload)
back = json.loads(raw)
assert back["bins"][0]["qty"] + back["bins"][1]["qty"] == back["on_hand"]
def reject_reasons(body):
reasons = []
if not isinstance(body.get("sku"), str) or not body["sku"].strip():
reasons.append("sku")
qty = body.get("on_hand")
if isinstance(qty, bool) or not isinstance(qty, int) or qty < 0:
reasons.append("on_hand")
bins = body.get("bins")
if not isinstance(bins, list) or not bins:
reasons.append("bins")
else:
total = 0
for row in bins:
q = row.get("qty") if isinstance(row, dict) else None
if isinstance(q, bool) or not isinstance(q, int) or q < 0:
reasons.append("bins.qty")
break
total += q
if "bins.qty" not in reasons and total != body.get("on_hand"):
reasons.append("bins_sum")
return reasons
assert reject_reasons(payload) == []
assert "on_hand" in reject_reasons({"sku": "FX-100", "on_hand": "80", "bins": [{"qty": 80}]})
assert "bins_sum" in reject_reasons(
{"sku": "FX-100", "on_hand": 80, "bins": [{"bin": "A1", "qty": 40}]}
)Teacher walkthrough: a customer payload
Illustrative contract for a customer read:
{
"account_id": "C-1044",
"name": "Harbour Tools",
"order_block": true,
"payment_terms_days": 30,
"ship_to": {"city": "Pune", "gate": "B"}
}payment_terms_days is an integer the ERP owns. The CRM note "they asked for 45" is not in this payload until the ERP owner changes the term. ship_to is nested so the city and the gate travel together. Validation: account_id is a non-empty string, order_block is a boolean, and payment_terms_days is an integer from 0 to 120. The 120 is Northline's illustrative ceiling, not a law.
A second workplace case
A supplier payload uses "bank_account": null to mean "not collected yet" and omits bank_account to mean "this caller is not allowed to see it." Those are different. The contract must say which one you are looking at. A client that treats both as "empty" will invite a payment to a blank account.
Failure example: a renamed field in one system
Symptom: The webshop shows on-hand as blank after a release. The warehouse still has 80.
Diagnosis: The warehouse renamed on_hand to qty_on_hand in the JSON and did not version the contract. The webshop still reads on_hand, gets a missing field, and stores nothing. The root cause is an unversioned rename.
Correction: Add qty_on_hand only in a new version, keep on_hand until every listed consumer has moved, and reject a body that contains neither. Write the consumer list down before the rename.
Validation: The old client still reads 80 from on_hand. The new client reads 80 from qty_on_hand. A body with neither field is 422.
Guided practice: design the receipt
Scenario: A goods receipt has receipt id R-19, SKU FX-100, quantity 10, and two bins that must sum to 10. Figures are illustrative.
Hints:
- Use an object for the receipt and an array for bins.
- Quantity is an integer.
- State one validation that fails closed.
Complete solution:
{
"receipt_id": "R-19",
"sku": "FX-100",
"qty": 10,
"bins": [{"bin": "A1", "qty": 6}, {"bin": "B2", "qty": 4}]
}Validation fails with 422 if qty is not an integer, if it is negative, or if the bin quantities do not add to qty. The ERP is not updated on 422. A second valid POST of the same receipt_id is a conflict (409), not a second receipt. That identity is what makes the create safe to recognise.
Independent practice
Design one JSON object your integration would send. Do not call a live vendor API.
Acceptance criteria:
- The example parses as JSON.
- It has one identifier, one integer quantity or money amount with a currency, and one nested object or array.
- You state what null means, or you forbid null.
- You list at least two validation rules and the status code on failure.
- You say which system of record owns each field.
Common mistakes
- Sending quantities as strings because a spreadsheet exported them that way.
- Using a JSON number with a fraction for money.
- Treating a missing field and null as the same business event.
- Renaming a field in production without a version and a consumer list.
Quick check
- Are
"80"and80the same JSON value? - What does an array hold in this lesson?
- Why does this course avoid binary floats for money?
- What status do we use when the JSON parses and the business rule fails?
- The bins sum to 40 and
on_handis 80. What is the validation result?
Answers:
- No. One is a string and one is a number.
- An ordered list of values, often objects.
- Fractional binary floats do not reliably represent decimal money.
- 422, with the field names, and no write to the system of record.
- Reject.
bins_sumfails. Do not store the item.
Lesson summary
JSON objects, arrays, and nested fields carry the contract. Types, units, null, and names are part of that contract. Validate them before any write.
Bridge to the next lesson
A valid body is still unacceptable from an unknown caller. The next lesson is how the caller proves identity and how the server decides what that identity may do.