Bird
0
0

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

easy📝 Syntax Q12 of 15
FastAPI - Middleware and Hooks
Which of the following is the correct way to add CORS middleware in FastAPI?
Aapp.middleware(CORSMiddleware, allow_origins=["*"])
Bapp.use(CORSMiddleware, allow_origins=["*"])
Capp.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET"])
Dapp.add_cors(allow_origins=["*"])
Step-by-Step Solution
Solution:
  1. Step 1: Recall FastAPI middleware syntax

    FastAPI uses app.add_middleware() to add middleware components like CORSMiddleware.
  2. Step 2: Check option syntax correctness

    app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET"]) uses app.add_middleware with CORSMiddleware and proper parameters, matching FastAPI docs.
  3. Final Answer:

    app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET"]) -> Option C
  4. Quick Check:

    Use add_middleware() to add CORS [OK]
Quick Trick: FastAPI middleware always uses add_middleware() method [OK]
Common Mistakes:
MISTAKES
  • Using app.use() which is not FastAPI syntax
  • Trying app.middleware() instead of add_middleware()
  • Calling a non-existent add_cors() method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes