Bearer token handling lets your FastAPI app check who is making a request. It helps keep your app safe by allowing only users with a valid token to access certain parts.
Bearer token handling in FastAPI
from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") @app.get("/items/") async def read_items(token: str = Depends(oauth2_scheme)): return {"token": token}
OAuth2PasswordBearer is a helper that extracts the bearer token from the request header.
The Depends function tells FastAPI to use the token from the request automatically.
from fastapi.security import OAuth2PasswordBearer oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
from fastapi import FastAPI, Depends app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") @app.get("/users/me") async def read_current_user(token: str = Depends(oauth2_scheme)): return {"token_received": token}
from fastapi import FastAPI, Depends, HTTPException, status app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") @app.get("/secure-data") async def secure_data(token: str = Depends(oauth2_scheme)): if token != "expected_token": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", headers={"WWW-Authenticate": "Bearer"}, ) return {"data": "This is protected"}
This FastAPI app has one protected route. It expects a bearer token in the request header. If the token is not exactly "mysecrettoken", it returns an error. Otherwise, it shows a success message with the token.
from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") @app.get("/protected") async def protected_route(token: str = Depends(oauth2_scheme)): if token != "mysecrettoken": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or missing token", headers={"WWW-Authenticate": "Bearer"}, ) return {"message": "Access granted with token: " + token}
Always use HTTPS to keep bearer tokens safe during transmission.
The tokenUrl parameter in OAuth2PasswordBearer is the URL where clients get tokens; it does not have to be implemented for token extraction to work.
Bearer tokens are usually sent in the header as: Authorization: Bearer <token>
Bearer token handling helps secure API routes by checking tokens sent by clients.
FastAPI's OAuth2PasswordBearer makes it easy to get the token from requests.
You can check the token value and reject requests without valid tokens.