Complete worked example
python
from fastapi import APIRouter, FastAPI
from fastapi.testclient import TestClient
def inspect_example(path):
app = FastAPI()
router = APIRouter(prefix="/roles")
def stats():
return {"observed": 2}
def read(role_id: int):
return {"id": role_id}
router.add_api_route("/stats", stats, methods=["GET"])
router.add_api_route("/{role_id}", read, methods=["GET"])
app.include_router(router)
with TestClient(app) as client:
response = client.get(path)
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
- APIRouter supplies a common prefix, and include_router attaches its routes to the application. A static path is registered first so stats reaches its own endpoint. A numeric segment reaches the dynamic operation, where FastAPI applies the integer annotation. The helper sends exact local paths and reports status and body. This makes route selection observable. A nonnumeric unknown segment matches the dynamic shape and then fails integer parsing; it is not necessarily the same result as a completely unmatched URL.