A typed API client keeps request and response shapes explicit, uses timeouts, parses JSON carefully, and validates fields before returning typed data.
What It Does and Why It Matters
A typed API client keeps request and response shapes explicit, uses timeouts, parses JSON carefully, and validates fields before returning typed data. Standard-library urllib is sufficient for simple calls, though authentication and retries require more work.
For a remote call, include explicit URL allowlists, request timeouts, and server-side validation.
Step-by-Step Example
Start with the complete example below. Read the inputs and predict what the final print statement will show before you run it.
import json
from typing import TypedDict
class ProductResponse(TypedDict):
identifier: int
label: str
def parse_product(response_body: str) -> ProductResponse:
decoded = json.loads(response_body)
if not isinstance(decoded, dict) or not isinstance(decoded.get('identifier'), int) or not isinstance(decoded.get('label'), str):
raise ValueError('Invalid product response')
return {'identifier': decoded['identifier'], 'label': decoded['label']}
print(parse_product('{"identifier": 7, "label": "Keyboard"}'))
How the Code Works
- The imports make these standard-library tools available: json, typing.
- The definition of ProductResponse, parse_product creates reusable behavior; its body runs only when called or instantiated as appropriate.
- The print calls display the results. Compare these results with the method’s documented return type and the input used.
- The annotations describe intended types for editors and checkers. They are not a replacement for validating input values when the function runs.
Expected output:
{'identifier': 7, 'label': 'Keyboard'}
For the demonstrated inputs, Python displays "{'identifier': 7, 'label': 'Keyboard'}". This result follows from the operation described above; change one input at a time to understand which rule matters.
What to Notice
Pay attention to the accepted input types, the returned value and the boundary behavior. Predict what changes if you replace the example input with an empty, zero, negative or missing value, where that value is meaningful for this operation.
If the task uses a library function, inspect its documented exceptions and return type before reusing it inside a larger function.
Where You Would Use This
This helps maintain larger projects where functions and data shapes cross module boundaries. Check the code with a static analyzer, and still validate data received from files, users or remote APIs. Annotation constructs do not normally enforce types automatically at runtime.
Practice Exercise
Adapt a typed JSON response parser to accept product records in a local test.
Before running your edited example, write down the result you expect. Then test at least one valid boundary or deliberately invalid value, using appropriate exception handling where necessary.
Reference: official Python documentation for the complete API contract and version notes.
Common Beginner Mistakes
- Treating any successful HTTP status or JSON object as proof that expected fields exist and are valid.
- Assuming a type checker has checked values received dynamically from an untrusted source.
Key Takeaways
- A typed API client keeps request and response shapes explicit, uses timeouts, parses JSON carefully, and validates fields before returning typed data.
- Adapt a typed JSON response parser to accept product records in a local test.