smartyfy.mrindigi.com

Python Master Course V2 — 095. Working with JSON APIs

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 09 — WEB AND API ENGINEERING · LESSON 095 / 200

Working with JSON APIs

Estimated study: 80–110 minutes · Prerequisite: preceding lesson, functions, exceptions and structured data.

Course hub

Video lesson

Video not yet available; this area is reserved for a verified video link or player.

Learning outcomes

Decode JSON and validate response shapes. Explain the technical mechanism, interpret outputs, diagnose failures, test edge cases and apply the skill in a realistic system.

Detailed explanation and architecture

JSON decoding checks syntax, not business schema. Validate required keys, types and missing/null fields before using response data.

Implementation sequence: define a contract; model inputs and outputs; apply explicit validation; use standard-library tools where possible; handle expected failures; write tests; document assumptions. Keep persistence or networking separate from business decisions and output formatting.

Professional concerns: predictable error handling, security boundaries, data integrity, performance under realistic load, logging without secrets, and reproducible environments. An example that works once is not automatically a production-ready service.

Understand and apply: Working with JSON APIs

Decode first, validate second, normalize third

A JSON decoder checks whether text follows JSON syntax and translates it into Python values. It does not know that an inventory response must be an object containing an items list, or that each product needs a nonblank SKU and nonnegative integer quantity. Treat parsing and validation as separate boundaries so errors point to the right problem.

A useful validator returns a small normalized representation that downstream code can trust. This example accepts a top-level items list, ignores extra fields, trims SKU whitespace, rejects duplicate normalized SKUs and returns tuples. Those are explicit policy choices. A different API might reject unknown fields or preserve SKU whitespace; clients should follow the documented contract rather than silently choosing.

Python example

import json

def products_from_json(text):
    payload = json.loads(text)
    if not isinstance(payload, dict) or not isinstance(payload.get("items"), list):
        raise ValueError("items must be a list in an object")
    result, seen = [], set()
    for index, item in enumerate(payload["items"]):
        if not isinstance(item, dict):
            raise ValueError(f"items[{index}] must be an object")
        sku, qty = item.get("sku"), item.get("qty")
        if not isinstance(sku, str) or not sku.strip():
            raise ValueError(f"items[{index}].sku must be nonblank text")
        if type(qty) is not int or qty < 0:
            raise ValueError(f"items[{index}].qty must be a nonnegative integer")
        sku = sku.strip()
        if sku in seen:
            raise ValueError(f"items[{index}].sku is duplicated")
        seen.add(sku)
        result.append((sku, qty))
    return result

print(products_from_json('{"items":[{"sku":" PEN ","qty":3},{"sku":"BOOK","qty":0}]}'))
print(products_from_json('{"items":[]}'))
try:
    products_from_json('{"items":[{"sku":"PEN","qty":true}]}')
except ValueError as error:
    print(error)

assert products_from_json('{"items":[]}') == []
invalid_payloads = [
    [], {}, {"items": None}, {"items": [3]},
    {"items": [{"sku": " ", "qty": 1}]},
    {"items": [{"sku": "PEN", "qty": -1}]},
    {"items": [{"sku": "PEN", "qty": "3"}]},
    {"items": [{"sku": "PEN", "qty": None}]},
    {"items": [{"sku": "PEN", "qty": 1}, {"sku": " PEN ", "qty": 2}]},
]
for payload in invalid_payloads:
    try:
        products_from_json(json.dumps(payload))
    except ValueError:
        pass
    else:
        raise AssertionError("invalid schema accepted")
try:
    products_from_json("{")
except json.JSONDecodeError:
    pass
else:
    raise AssertionError("malformed JSON accepted")

Expected output

[('PEN', 3), ('BOOK', 0)]
[]
items[0].qty must be a nonnegative integer

Walk from the outermost structure inward. A list check must happen before iterating items; an object check must happen before reading product fields; type checks precede trimming and comparisons. The error path identifies which element and field failed. Exact integer checking excludes bool, even though Python normally treats bool as an int subclass.

Missing, null and empty are different cases

A missing items key and items:null fail this contract. An empty items list succeeds and means no products were returned. For a product, missing qty and qty:null are both invalid because quantity is required; neither should silently become zero. If a field is truly optional, document its default and distinguish omission from an explicit null when the API assigns them different meanings.

The function rejects the whole response on the first invalid product. That atomic validation policy is useful when a client cannot safely act on a partial inventory. A batch-import application might instead return accepted and rejected records, but it must make partial success visible. Do not quietly skip bad products while presenting the result as a complete feed.

Tests should cover malformed JSON, a top-level list, missing items, null items, an empty list, a nonobject member, whitespace-only SKU, boolean quantity, negative quantity and duplicate SKUs after normalization. Numeric strings such as "3" are rejected instead of coerced. This prevents accidental acceptance of a provider’s breaking schema change. Add a maximum item count and an upstream body-size limit for bounded resource usage.

Trusted-fixture decoding warm-up

Requires Python 3.10+. Save as lesson95.py and run using python or python3. The example uses local or in-memory data and makes no external network request.

import json
payload='{"items":[{"id":1,"name":"Pen"}]}'
data=json.loads(payload)
print(data['items'][0]['name'])

Expected output:

Pen

This short warm-up assumes the fixed trusted fixture has a nonempty items list and a name field. It demonstrates decoding and indexing only. For response data that may be empty or malformed, use the schema validator above; an unchecked items[0] lookup is not a complete API validation strategy.

Reasoning walkthrough

Read the imports and setup, identify the data model, then follow each operation until the final result. Change one input and predict the effect before running it. Consider the behavior with empty data, invalid types and missing resources.

Guided real-world project

Normalize an API product feed into validated records using the explicit SKU and quantity contract above.

  1. Write a specification with data schema, required operations and failure conditions.
  2. Implement a minimal solution using small named functions.
  3. Add input validation and deliberate error responses.
  4. Test typical, boundary and invalid inputs.
  5. Verify the result against an independently calculated expectation.
  6. Document setup, limitations and recovery steps.

Acceptance: deterministic tests, correct handling of rejected data, no undocumented destructive behavior, and a clear explanation of architecture. This project is an assignment; its full implementation has not been independently executed.

Common mistakes and debugging

  • Concatenating untrusted input into SQL or URLs without proper encoding and parameterization.
  • Assuming remote services or databases always succeed.
  • Omitting transaction or timeout boundaries.
  • Confusing transport status with validated application data.
  • Testing only success paths and ignoring empty or malformed responses.

To debug, reproduce the failure, inspect the smallest failing input, check types and constraints, and add a regression test.

Practice with explained answers

Make a prediction before opening each answer. Then trace the example and explain the result in your own words.

Optional hint for question 1

JSON syntax can be valid while required fields have the wrong values or shape.

1. Why can json.loads succeed while products_from_json fails?

The text may be valid JSON with an invalid application shape, such as {"items": null}. Syntax and schema are separate contracts.

2. Should an empty items list be treated as an error?

No under this contract. It is a valid collection with zero products. Missing or null items has a different meaning and is rejected.

3. Why reject qty:true?

JSON true becomes Python True. Exact int checking excludes it so a boolean is not accidentally interpreted as one unit of stock.

4. Why reject duplicate SKUs after trimming?

Normalization can make "PEN" and " PEN " identify the same product. Checking afterward prevents two representations from producing ambiguous stock records.

5. Why not convert every quantity using int(qty)?

That would accept numeric strings and booleans, and could truncate floats. Strict validation makes unexpected provider schema changes visible rather than silently changing their meaning.

Mastery checkpoint

Reproduce the sample, explain the design, complete the guided project, document three test cases and identify a realistic failure mode. No video, certificate or account-synced completion is claimed.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.