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
Start learning this pattern below
Jump into concepts and practice - no test required
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.
Practice
Solution
Step 1: Understand Bearer token role
Bearer tokens are used to prove the client has permission to access protected routes.Step 2: Identify purpose in FastAPI
FastAPI uses Bearer tokens to check authorization before allowing access to API endpoints.Final Answer:
To securely identify and authorize API requests -> Option DQuick Check:
Bearer token = Authorization [OK]
- Confusing token with response formatting
- Thinking token speeds up database
- Assuming token serves static files
Solution
Step 1: Recall FastAPI token extraction classes
OAuth2PasswordBearer is designed to read Bearer tokens from the Authorization header.Step 2: Match class to Bearer token usage
OAuth2PasswordRequestForm is for form data, HTTPBasicCredentials is for basic auth, APIKeyHeader is for API keys, so only OAuth2PasswordBearer fits Bearer tokens.Final Answer:
OAuth2PasswordBearer -> Option AQuick Check:
Bearer token extractor = OAuth2PasswordBearer [OK]
- Using OAuth2PasswordRequestForm for token extraction
- Confusing basic auth with Bearer token
- Choosing APIKeyHeader for Bearer tokens
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/users/me")
async def read_users_me(token: str = Depends(oauth2_scheme)):
return {"token": token}
What will be the output if the client sends a request with header Authorization: Bearer abc123?Solution
Step 1: Understand OAuth2PasswordBearer behavior
This class extracts only the token string after 'Bearer ' from the Authorization header.Step 2: Analyze the returned value
The function returns a JSON with the token string, so it will return {"token": "abc123"}.Final Answer:
{"token": "abc123"} -> Option CQuick Check:
Bearer token string extracted = "abc123" [OK]
- Expecting full 'Bearer abc123' string returned
- Assuming 401 error without token validation
- Thinking token is null if present
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/items/")
async def read_items(token: str = Depends(oauth2_scheme)):
if token == None:
raise HTTPException(status_code=401, detail="Invalid token")
return {"token": token}Solution
Step 1: Check token validation logic
OAuth2PasswordBearer returns a string or raises an error if missing; token is never None but can be empty or missing.Step 2: Correct token presence check
Using 'if not token' is safer to catch empty strings or missing tokens rather than 'token == None'.Final Answer:
The token check should use 'if not token' instead of 'if token == None' -> Option AQuick Check:
Token presence check = 'if not token' [OK]
- Using 'token == None' which misses empty strings
- Thinking OAuth2PasswordBearer doesn't extract tokens
- Confusing HTTP status codes for auth errors
Solution
Step 1: Use OAuth2PasswordBearer dependency
We must use Depends(oauth2_scheme) to extract the token from the Authorization header.Step 2: Check token value correctly
The token string is just the token without 'Bearer ' prefix, so compare directly to "secret123" and raise 401 if not matching.Final Answer:
async def protected_route(token: str = Depends(oauth2_scheme)): if token != "secret123": raise HTTPException(status_code=401, detail="Unauthorized") return {"message": "Access granted"} -> Option BQuick Check:
Compare token string directly to "secret123" [OK]
- Comparing token to 'Bearer secret123' including prefix
- Not using Depends(oauth2_scheme) to get token
- Returning access granted when token is None
