Complete the code to import the OAuth2PasswordBearer class from FastAPI.
from fastapi.security import [1]
The OAuth2PasswordBearer class is used to define the OAuth2 password flow token URL in FastAPI.
Complete the code to create an OAuth2PasswordBearer instance with the token URL '/token'.
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=[1])The tokenUrl parameter should point to the URL where the client sends username and password to get the token. Commonly, this is '/token'.
Fix the error in the dependency injection to get the token from the OAuth2 scheme.
async def read_items(token: str = [1]):
When using FastAPI dependencies, you pass the callable without parentheses to Depends. So it should be Depends(oauth2_scheme).
Fill both blanks to define a token endpoint that uses OAuth2PasswordRequestForm and returns a token.
from fastapi import FastAPI, Depends from fastapi.security import OAuth2PasswordRequestForm app = FastAPI() @app.post("/token") async def login(form_data: [1] = Depends()): return {"access_token": form_data.[2], "token_type": "bearer"}
The OAuth2PasswordRequestForm dependency extracts form data including the username and password. The token response usually includes the username as the access token for demonstration.
Fill all three blanks to create a protected route that extracts the token and returns a welcome message.
from fastapi import FastAPI, Depends, HTTPException from fastapi.security import OAuth2PasswordBearer app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token") @app.get("/users/me") async def read_users_me(token: str = Depends([1])): if not token: raise HTTPException(status_code=401, detail="Invalid authentication") return {"message": f"Welcome, [2]! Your token is [3]."}
Depends(oauth2_scheme()) instead of Depends(oauth2_scheme).tokenUrl instead of oauth2_scheme.The dependency oauth2_scheme extracts the token. The welcome message uses a placeholder user (which could be replaced by username in real apps) and the token variable.