Complete worked example
python
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
def inspect_example(role_id):
app = FastAPI()
@app.get("/roles/{role_id}")
def read(role_id: int):
if role_id != 1:
raise HTTPException(status_code=404, detail="Role not found")
return {"id": 1, "title": "QA"}
with TestClient(app) as client:
response = client.get(f"/roles/{role_id}")
body = response.json()
if response.status_code == 422:
body = sorted({e["type"] for e in body["detail"]})
return {"status": response.status_code, "body": body}- Reasoning
- HTTPException interrupts normal endpoint execution and produces its declared status with a detail body. Request validation creates a different response before the route function runs. The inspection helper reduces validation errors to their types, avoiding brittle comparison of framework prose. The missing-role branch is intentionally short and contains no side effect. That makes the control flow visible: after the exception, there is no normal success return for the missing object. Real services should likewise avoid performing protected writes before checking required preconditions.