Bird
0
0

You want to add middleware that logs request time but only for routes under /api. Why does FastAPI middleware still run on all routes, and how can you limit it?

hard🚀 Application Q15 of 15
FastAPI - Middleware and Hooks
You want to add middleware that logs request time but only for routes under /api. Why does FastAPI middleware still run on all routes, and how can you limit it?
AFastAPI does not support middleware; use dependencies instead
BMiddleware can be added only to specific routes by passing route list to add_middleware
CMiddleware runs globally but can be disabled per route with a decorator
DMiddleware runs globally by design; to limit, check path inside middleware and skip non-/api requests
Step-by-Step Solution
Solution:
  1. Step 1: Understand middleware scope

    FastAPI middleware always runs globally on every request to handle shared tasks.
  2. Step 2: Limit middleware effect by path check

    To restrict middleware to /api routes, check the request URL path inside middleware and skip processing for others.
  3. Final Answer:

    Middleware runs globally by design; to limit, check path inside middleware and skip non-/api requests -> Option D
  4. Quick Check:

    Middleware global; filter inside middleware [OK]
Quick Trick: Middleware always global; filter requests inside middleware [OK]
Common Mistakes:
MISTAKES
  • Expecting middleware to attach only to some routes automatically
  • Trying to pass routes to add_middleware (not supported)
  • Thinking middleware can be disabled per route with decorators

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes