How to Get Current User in FastAPI: Simple Guide
In FastAPI, you get the current user by creating a dependency that extracts user info from the request, usually via OAuth2 or JWT tokens. Use
Depends with a security function like get_current_user to access the user inside your path operation functions.Syntax
To get the current user in FastAPI, define a dependency function that verifies the user's identity and returns user data. Then, use Depends in your route handler to call this function automatically.
Key parts:
Depends: tells FastAPI to run the dependency function.get_current_user: your custom function that checks authentication and returns user info.- Security schemes like
OAuth2PasswordBearerhelp extract tokens from requests.
python
from fastapi import Depends, FastAPI from fastapi.security import OAuth2PasswordBearer app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") def verify_token(token: str): # Dummy verification function return {"username": "user"} def get_current_user(token: str = Depends(oauth2_scheme)): # Verify token and return user info user = verify_token(token) return user @app.get("/users/me") async def read_users_me(current_user: dict = Depends(get_current_user)): return current_user
Example
This example shows a simple FastAPI app that uses OAuth2 password flow to get the current user from a token. The get_current_user function decodes the token and returns user data. The /users/me endpoint returns the current user's info.
python
from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer from pydantic import BaseModel app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") class User(BaseModel): username: str email: str # Dummy function to simulate token verification def verify_token(token: str) -> User: if token == "secrettoken": return User(username="alice", email="alice@example.com") raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", headers={"WWW-Authenticate": "Bearer"}, ) def get_current_user(token: str = Depends(oauth2_scheme)) -> User: return verify_token(token) @app.get("/users/me") async def read_users_me(current_user: User = Depends(get_current_user)): return current_user
Output
{"username":"alice","email":"alice@example.com"}
Common Pitfalls
- Not using
Dependsin the route function will prevent FastAPI from injecting the current user. - Forgetting to handle invalid or missing tokens causes server errors instead of proper 401 responses.
- Not setting
tokenUrlinOAuth2PasswordBearercan confuse clients about where to get tokens. - Returning raw tokens instead of user objects makes it hard to use user info in routes.
python
from fastapi import Depends, FastAPI from fastapi.security import OAuth2PasswordBearer from pydantic import BaseModel app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") class User(BaseModel): username: str email: str def verify_token(token: str) -> User: # Dummy verification return User(username="user", email="user@example.com") def get_current_user(token: str = Depends(oauth2_scheme)) -> User: return verify_token(token) # Wrong: missing Depends, user not injected @app.get("/wrong") async def wrong_route(current_user): return current_user # Right: use Depends to inject current user @app.get("/right") async def right_route(current_user: User = Depends(get_current_user)): return current_user
Quick Reference
Summary tips for getting current user in FastAPI:
- Use
OAuth2PasswordBeareror other security schemes to extract tokens. - Create a
get_current_userdependency to verify tokens and return user info. - Use
Depends(get_current_user)in your route parameters to access the user. - Handle authentication errors with proper HTTP exceptions.
Key Takeaways
Use FastAPI's dependency injection with Depends to get the current user.
Create a function that verifies the token and returns user data.
Use OAuth2PasswordBearer to extract tokens from requests.
Always handle invalid tokens with HTTP 401 errors.
Inject the current user in route handlers to access user info easily.