Middleware is a request-processing layer between a client and an API endpoint. It can inspect headers, validate access information, apply business rules, and return an error before the endpoint handles the request. section 4.10 section 8.7
A practical use is protecting a ticket checkout flow from scalping bots. Middleware checks for an allowed browser user agent, obtains the user identity from access-token claims, and rejects a purchase when that user bought a ticket within the previous 24 hours. section 4.10
The example applies these decisions:
- Return 401 Unauthorized when the request does not contain an allowed browser user agent. section 4.10
- Return 409 Conflict when the authenticated user has a recent transaction. section 4.10
- Keep the rule aligned with the application’s business requirements rather than treating middleware as a universal defense. section 4.10
Listing 4.14 Custom middleware to prevent scalping
# file: ch04/vulnerable_business_flows.py
class UserClaims(BaseModel):
sub: str
def validate_access(): #1
return UserClaims(
sub="deb6f47e-fd9d-4b4c-ae4f-c85726ed502c"
)
@server.middleware("http.request") #2
async def prevent_scalping(request: Request, call_next):
if not any( #3
agent in request.headers["user-agent"] for agent in allowed_agents
):
return JSONResponse( #4
status_code=401, content={"error": "Unauthorized"}
)
user_claims = validate_access() #5
if request.url.path == "/checkout": #6
for transaction in recent_transactions:
if ( #7
transaction.sub == user_claims.sub
and transaction.within_24h
):
return JSONResponse( #8
status_code=409, content={"error": "Conflict"}
)
return await call_next(request) #9
Inspect the focused middleware example to see request-header inspection, access validation, path matching, transaction lookup, and JSON error responses. section 4.10









