Performance: Protected routes
This affects the server response time and user experience by adding authentication checks before serving protected content.
Jump into concepts and practice - no test required
from fastapi import FastAPI, Depends from fastapi.security import OAuth2PasswordBearer import asyncio app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") async def verify_token_async(token: str): await asyncio.sleep(0) # simulate async I/O return "user123" @app.get("/protected") async def protected_route(token: str = Depends(oauth2_scheme)): user = await verify_token_async(token) return {"message": f"Hello {user}"}
from fastapi import FastAPI, Depends from fastapi.security import OAuth2PasswordBearer app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") @app.get("/protected") async def protected_route(token: str = Depends(oauth2_scheme)): user = verify_token(token) # synchronous blocking call return {"message": f"Hello {user}"}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous token verification | N/A (server-side) | N/A | N/A | [X] Bad |
| Asynchronous token verification | N/A (server-side) | N/A | N/A | [✓] Good |
Depends to declare dependencies like authentication checks.Depends with a function that verifies tokens enforces protection on routes./users/me without a token?
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def get_current_user(token: str = Depends(oauth2_scheme)):
if token != "validtoken":
raise HTTPException(status_code=401, detail="Invalid token")
return {"username": "user1"}
@app.get("/users/me")
async def read_users_me(current_user: dict = Depends(get_current_user)):
return current_userget_current_user checks if the token equals "validtoken"; otherwise, it raises HTTP 401.oauth2_scheme will not provide a valid token, so the check fails and raises HTTP 401.from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def get_current_user(token: str):
if token != "secret":
raise HTTPException(status_code=401, detail="Unauthorized")
return {"user": "admin"}
@app.get("/dashboard")
async def dashboard(user: dict = Depends(get_current_user)):
return usertoken: str but does not use Depends(oauth2_scheme) to get the token automatically.Depends(oauth2_scheme), FastAPI won't provide the token, causing an error.