Bird
0
0

What is wrong with this FastAPI OAuth2 password flow code snippet?

medium📝 Debug Q14 of 15
FastAPI - Authentication and Security
What is wrong with this FastAPI OAuth2 password flow code snippet?
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordRequestForm

app = FastAPI()

@app.post('/token')
async def login(form_data: OAuth2PasswordRequestForm):
    if form_data.username == 'bob' and form_data.password == 'pass':
        return {'access_token': 'abc', 'token_type': 'bearer'}
    return {'error': 'Invalid'}
AEndpoint should use GET method instead of POST
BIncorrect import of OAuth2PasswordRequestForm
CReturn type should be a string, not dict
DMissing Depends() in function parameter for form_data
Step-by-Step Solution
Solution:
  1. Step 1: Check function parameter for dependency injection

    OAuth2PasswordRequestForm must be wrapped with Depends() to extract form data properly.
  2. Step 2: Verify other parts

    Imports are correct, return type as dict is valid JSON response, POST method is correct for token requests.
  3. Final Answer:

    Missing Depends() in function parameter for form_data -> Option D
  4. Quick Check:

    Use Depends() to get form data [OK]
Quick Trick: Always wrap OAuth2PasswordRequestForm with Depends() [OK]
Common Mistakes:
MISTAKES
  • Forgetting Depends() causes runtime errors
  • Using GET instead of POST for token endpoint
  • Thinking return must be string, not dict

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes