Bird
0
0

Which of the following is the correct way to add middleware globally in FastAPI?

easy📝 Syntax Q12 of 15
FastAPI - Middleware and Hooks
Which of the following is the correct way to add middleware globally in FastAPI?
Aapp.add_middleware(SomeMiddleware)
Bapp.middleware(SomeMiddleware)
Capp.route.middleware(SomeMiddleware)
DSomeMiddleware(app)
Step-by-Step Solution
Solution:
  1. Step 1: Recall FastAPI middleware syntax

    FastAPI uses the method add_middleware() on the app instance to add middleware globally.
  2. Step 2: Eliminate incorrect options

    Options A, B and C are invalid: A instantiates middleware without adding it to the app, B and C are invalid method calls.
  3. Final Answer:

    app.add_middleware(SomeMiddleware) -> Option A
  4. Quick Check:

    Use add_middleware() to add middleware globally [OK]
Quick Trick: Use app.add_middleware() to add middleware globally [OK]
Common Mistakes:
MISTAKES
  • Using app.middleware() which does not exist
  • Trying to add middleware on route instead of app
  • Instantiating middleware without adding it to app

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes