Rana Maninder Singh
Lesson 3 of 12API & Integration Development

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

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:

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:

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:

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:

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

  1. Are "80" and 80 the same JSON value?
  2. What does an array hold in this lesson?
  3. Why does this course avoid binary floats for money?
  4. What status do we use when the JSON parses and the business rule fails?
  5. The bins sum to 40 and on_hand is 80. What is the validation result?

Answers:

  1. No. One is a string and one is a number.
  2. An ordered list of values, often objects.
  3. Fractional binary floats do not reliably represent decimal money.
  4. 422, with the field names, and no write to the system of record.
  5. Reject. bins_sum fails. 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.