Python / FastAPI Basics Interview Questions
How do you implement OAuth2 password flow with JWT tokens in FastAPI?
FastAPI provides OAuth2PasswordBearer and OAuth2PasswordRequestForm helpers for the standard username/password token flow. The pattern: client POSTs credentials → server returns a JWT → client sends JWT in Authorization: Bearer <token> header on subsequent requests.
from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from typing import Annotated from datetime import datetime, timedelta import jwt # pip install PyJWT app = FastAPI() SECRET_KEY = "your-secret-key" # use a strong random key in production! ALGORITHM = "HS256" # Tells FastAPI where clients obtain tokens â used in OpenAPI docs oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token") # 1. Login endpoint â returns a JWT @app.post("/token") def login(form: Annotated[OAuth2PasswordRequestForm, Depends()]): if form.username != "alice" or form.password != "secret": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", headers={"WWW-Authenticate": "Bearer"}, ) # Create JWT token payload = { "sub": form.username, "exp": datetime.utcnow() + timedelta(minutes=30), } token = jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM) return {"access_token": token, "token_type": "bearer"} # 2. Dependency that decodes and validates the token def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) username = payload.get("sub") if not username: raise ValueError except Exception: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) return username # 3. Protected endpoint @app.get("/me") def read_me(current_user: Annotated[str, Depends(get_current_user)]): return {"username": current_user}
More Related questions...