Recipe 13.3 · Python
JSON APIs End to End
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
Calling a JSON API is more than one line. The request body must be serialized with the right
options, errors come back as application/problem+json with useful detail that
EnsureSuccessStatusCode throws away, and large result sets arrive as one big array that you would
rather process as it streams in.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
When this fails, the log says "Response status code does not indicate success: 400 (Bad Request)". The server said which field was wrong, but the code threw that message away.
Requirements: Python 3.12+. Install: pip install httpx
"""POST JSON and lose the server's error detail
Source: ImproveCode, Chapter 13, Recipe 13.3 "JSON APIs End to End"
Section: The way it's often written
Book page: 285 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
JsonConvert -> json.dumps/json.loads; StringContent + PostAsync -> httpx.AsyncClient.post;
EnsureSuccessStatusCode -> raise_for_status (which also discards the body's detail).
"""
from __future__ import annotations
import json
from typing import Any
import httpx
from p285_r13_3_order_dtos_api_exception import OrderDto
# Not to copy: loses the server's error detail, buffers everything
async def create_order(client: httpx.AsyncClient, request: Any) -> OrderDto:
json_text = json.dumps(request, default=vars)
content = json_text.encode("utf-8")
response = await client.post(
"orders", content=content,
headers={"Content-Type": "application/json; charset=utf-8"})
response.raise_for_status() # "Client error '400 Bad Request'"
body = response.text
return OrderDto.model_validate(json.loads(body))
The improved recipe
Use the System.Net.Http.Json extensions for the happy path, and read the problem details on the
unhappy path.
Usage from a job that exports orders:
Requirements: Python 3.12+. Install: pip install pydantic
"""Order DTOs, problem details and an API exception carrying them
Source: ImproveCode, Chapter 13, Recipe 13.3 "JSON APIs End to End"
Section: The improved recipe
Book page: 285-286 -- original C# listing
Converted from C# to Python.
Records -> frozen pydantic models with camelCase aliases (JsonSerializerDefaults.Web);
decimal -> Decimal; HttpStatusCode -> http.HTTPStatus.
"""
from __future__ import annotations
from decimal import Decimal
from http import HTTPStatus
from pydantic import BaseModel, ConfigDict
from pydantic.alias_generators import to_camel
class _WebModel(BaseModel):
model_config = ConfigDict(
alias_generator=to_camel, populate_by_name=True, frozen=True)
class OrderLineDto(_WebModel):
sku: str
quantity: int
class CreateOrderRequest(_WebModel):
customer_id: int
lines: tuple[OrderLineDto, ...]
class OrderDto(_WebModel):
id: int
customer_id: int
status: str
total: Decimal
class ApiProblem(_WebModel):
type: str | None = None
title: str | None = None
status: int | None = None
detail: str | None = None
class ApiException(Exception):
def __init__(self, status_code: HTTPStatus, problem: ApiProblem | None) -> None:
title = problem.title if problem and problem.title is not None else status_code.phrase
detail = "" if problem is None or problem.detail is None else f" ({problem.detail})"
super().__init__(f"API returned {int(status_code)}: {title}{detail}")
self.status_code = status_code
self.problem = problem
Requirements: Python 3.12+. Install: pip install httpx ijson pydantic
"""Order API client with problem-details errors and a streamed export
Source: ImproveCode, Chapter 13, Recipe 13.3 "JSON APIs End to End"
Section: The improved recipe
Book page: 286-287 -- original C# listing
Converted from C# to Python.
HttpClient + System.Net.Http.Json -> httpx.AsyncClient + pydantic; GetFromJsonAsAsyncEnumerable
-> httpx streaming fed to ijson so the array is parsed item by item; JsonException ->
pydantic.ValidationError; CancellationToken -> asyncio task cancellation.
"""
from __future__ import annotations
from collections.abc import AsyncIterator
from http import HTTPStatus
import httpx
import ijson
from pydantic import TypeAdapter, ValidationError
from p285_r13_3_order_dtos_api_exception import (
ApiException,
ApiProblem,
CreateOrderRequest,
OrderDto,
)
_order = TypeAdapter(OrderDto | None)
class _AsyncByteReader:
"""Adapts an async byte iterator to the async read() that ijson expects."""
def __init__(self, chunks: AsyncIterator[bytes]) -> None:
self._chunks = chunks
async def read(self, size: int = -1) -> bytes:
try:
return await anext(self._chunks)
except StopAsyncIteration:
return b""
class OrderApiClient:
def __init__(self, http: httpx.AsyncClient) -> None:
self._http = http
async def get_order(self, id: int) -> OrderDto | None:
response = await self._http.get(f"orders/{id}")
if response.status_code == httpx.codes.NOT_FOUND:
return None
await self._ensure_success(response)
return _order.validate_json(response.content)
async def create_order(self, request: CreateOrderRequest) -> OrderDto:
response = await self._http.post(
"orders",
content=request.model_dump_json(by_alias=True),
headers={"Content-Type": "application/json; charset=utf-8"})
await self._ensure_success(response)
order = _order.validate_json(response.content)
if order is None:
raise ApiException(HTTPStatus(response.status_code), None)
return order
async def stream_orders(self) -> AsyncIterator[OrderDto | None]:
async with self._http.stream("GET", "orders/export") as response:
await self._ensure_success(response)
reader = _AsyncByteReader(response.aiter_bytes())
async for item in ijson.items(reader, "item"):
yield None if item is None else OrderDto.model_validate(item)
@staticmethod
async def _ensure_success(response: httpx.Response) -> None:
if response.is_success:
return
problem: ApiProblem | None = None
content_type = response.headers.get("content-type", "")
media_type = content_type.split(";")[0].strip().lower()
if media_type in ("application/problem+json", "application/json"):
try:
problem = ApiProblem.model_validate_json(await response.aread())
except ValidationError:
# Body was not problem details; keep the status code.
pass
raise ApiException(HTTPStatus(response.status_code), problem)
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Consume the streamed order export one item at a time
Source: ImproveCode, Chapter 13, Recipe 13.3 "JSON APIs End to End"
Section: The improved recipe
Book page: 287 -- original C# listing
Converted from C# to Python.
await foreach -> async for; the usage fragment is wrapped in a function, and the
writer is described by a small Protocol.
"""
from __future__ import annotations
from typing import Protocol
from p285_r13_3_order_dtos_api_exception import OrderDto
from p286_r13_3_order_api_client_problem_details import OrderApiClient
class OrderWriter(Protocol):
async def write(self, order: OrderDto) -> None: ...
async def export_orders(client: OrderApiClient, writer: OrderWriter) -> None:
async for order in client.stream_orders():
if order is not None:
await writer.write(order)
How it works
PostAsJsonAsync serializes straight into the request stream with the options you pass, sets
Content-Type: application/json; charset=utf-8, and avoids building an intermediate string.
ReadFromJsonAsync does the reverse from the response stream. Passing one static
JsonSerializerOptions keeps the metadata cache warm, as Chapter 12 explains.
EnsureSuccessAsync replaces EnsureSuccessStatusCode. ASP.NET Core and most modern APIs return
RFC 9457 problem details on errors: a small JSON object with title, status and detail. The
method reads it when the content type says it is JSON and throws an ApiException that carries
both the status code and the server's explanation. Your log now says
API returned 400: Validation failed (Quantity must be at least 1). Callers can also catch
ApiException and branch on StatusCode, for example to show a validation message for 400 and
an apology for 503.
GetFromJsonAsAsyncEnumerable streams a JSON array. Each item is yielded as soon as it has been
read, so an export of 500,000 orders uses the memory of a few orders, not all of them. The
response is read with HttpCompletionOption.ResponseHeadersRead under the covers, which is what
makes the streaming real.
Every method takes a CancellationToken. In ASP.NET Core, pass HttpContext.RequestAborted, and
when the user closes the browser the outgoing call is cancelled too.
Variations and pitfalls
- Always dispose the response.
using HttpResponseMessagereturns the connection to the pool promptly. Forgetting it on error paths is a classic slow leak. - Don't log whole bodies. Problem details are safe to log. Raw response bodies can contain
personal data, and Chapter 4 explains what never to log. If you need the body for diagnosis, log
the first 500 characters at
Debuglevel. - Validation errors. ASP.NET Core adds an
errorsdictionary to validation problems. AddIDictionary<string, string[]>? ErrorstoApiProblemif you want to show them per field. - Expected failures. If a failure is part of the normal flow, such as an insufficient balance,
return Chapter 5's
Resulttype from the client instead of throwing. - Generated clients. For a large API with an OpenAPI document, a generated client (NSwag or
Kiota) saves typing. Register it with
AddHttpClientso it still gets the factory and resilience.