Bird
0
0

Identify the error in this FastAPI security code snippet:

medium📝 Debug Q14 of 15
FastAPI - Authentication and Security
Identify the error in this FastAPI security code snippet:
from fastapi import FastAPI, Security
from fastapi.security import APIKeyHeader

app = FastAPI()
api_key_header = APIKeyHeader(name="Authorization")

@app.get("/secure")
async def secure_route(api_key: str = Depends(api_key_header)):
    return {"key": api_key}
AFunction should not be async
BMissing import of Depends
CAPIKeyHeader name should be "X-API-Key"
DUsing Depends instead of Security for APIKeyHeader dependency
Step-by-Step Solution
Solution:
  1. Step 1: Check for import errors

    The code uses 'Depends(api_key_header)' but 'Depends' is not imported. Only FastAPI and Security are imported from fastapi.
  2. Step 2: Confirm dependency usage is otherwise correct

    Using Depends with APIKeyHeader is valid; adding 'from fastapi import Depends' would fix it. Header name and async are fine.
  3. Final Answer:

    Missing import of Depends -> Option B
  4. Quick Check:

    Missing Depends import causes NameError [OK]
Quick Trick: Always import Depends for FastAPI dependencies [OK]
Common Mistakes:
MISTAKES
  • Confusing Depends and Security usage
  • Thinking header name must be fixed
  • Believing async is not allowed

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes