Bird
0
0

Examine the following FastAPI code snippet for Bearer token handling:

medium📝 Debug Q6 of 15
FastAPI - Authentication and Security
Examine the following FastAPI code snippet for Bearer token handling:
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/profile")
async def profile(token: str = oauth2_scheme):
    return {"token": token}
What is the main issue with this code?
AThe dependency should be wrapped with Depends() to work correctly
BOAuth2PasswordBearer requires a different tokenUrl parameter
CThe endpoint should be async def with no parameters
DThe token variable should be an integer, not a string
Step-by-Step Solution
Solution:
  1. Step 1: Review dependency injection syntax

    FastAPI requires dependencies to be declared with Depends() to be properly injected.
  2. Step 2: Identify the error

    The code uses 'token: str = oauth2_scheme' instead of 'token: str = Depends(oauth2_scheme)'. This prevents FastAPI from calling the dependency.
  3. Final Answer:

    The dependency should be wrapped with Depends() -> Option A
  4. Quick Check:

    Always use Depends() to declare dependencies in FastAPI. [OK]
Quick Trick: Wrap dependencies with Depends() to enable injection [OK]
Common Mistakes:
MISTAKES
  • Omitting Depends() when declaring dependencies
  • Misunderstanding the tokenUrl parameter purpose
  • Incorrectly typing the token variable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes