Protected routes keep parts of your app safe. Only allowed users can see or use them.
0
0
Protected routes in FastAPI
Introduction
When you want only logged-in users to access their profile page.
When you need to hide admin controls from regular users.
When you want to protect sensitive data like payment info.
When you want to check user permissions before showing certain pages.
Syntax
FastAPI
from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") def get_current_user(token: str = Depends(oauth2_scheme)): if token != "fake-super-secret-token": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", headers={"WWW-Authenticate": "Bearer"}, ) return {"username": "user1"} @app.get("/protected") async def protected_route(current_user: dict = Depends(get_current_user)): return {"message": f"Hello {current_user['username']}! This is a protected route."}
Depends tells FastAPI to run a function before the route to check something.
OAuth2PasswordBearer helps get the token from the request header.
Examples
This example shows a simple dependency that always allows access. The secure route uses it to check before responding.
FastAPI
from fastapi import Depends, FastAPI app = FastAPI() def verify_user(): # Simple check return True @app.get("/open") async def open_route(): return {"message": "Anyone can see this."} @app.get("/secure") async def secure_route(verified: bool = Depends(verify_user)): if not verified: return {"error": "Not allowed"} return {"message": "Only verified users."}
This example uses OAuth2 token checking to protect the dashboard route.
FastAPI
from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") def get_current_user(token: str = Depends(oauth2_scheme)): if token != "valid-token": raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") return {"username": "user123"} @app.get("/dashboard") async def dashboard(user: dict = Depends(get_current_user)): return {"message": f"Welcome {user['username']} to your dashboard."}
Sample Program
This FastAPI app has one protected route at /protected. It checks the token sent by the user. If the token is correct, it shows a welcome message. If not, it sends an error.
FastAPI
from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") def get_current_user(token: str = Depends(oauth2_scheme)): if token != "fake-super-secret-token": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", headers={"WWW-Authenticate": "Bearer"}, ) return {"username": "user1"} @app.get("/protected") async def protected_route(current_user: dict = Depends(get_current_user)): return {"message": f"Hello {current_user['username']}! This is a protected route."}
OutputSuccess
Important Notes
Always send the token in the Authorization header as Bearer <token>.
Use HTTPS to keep tokens safe during transfer.
You can customize get_current_user to check real users from a database.
Summary
Protected routes keep parts of your app safe by checking user tokens.
Use Depends with a function that verifies the user before allowing access.
FastAPI's OAuth2PasswordBearer helps get tokens from requests easily.