Bird
0
0
FastAPIframework~30 mins

Bearer token handling in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Bearer Token Handling with FastAPI
📖 Scenario: You are building a simple API that requires users to provide a bearer token to access protected data. This is common in real-world apps where security matters, like accessing your bank info or private messages.
🎯 Goal: Create a FastAPI app that checks for a bearer token in the request header and allows access only if the token matches a preset secret token.
📋 What You'll Learn
Create a FastAPI app instance called app
Define a secret token string variable called SECRET_TOKEN with value "mysecrettoken123"
Create a dependency function called verify_token that extracts the bearer token from the Authorization header
Check if the token matches SECRET_TOKEN and raise HTTPException with status 401 if it does not
Create a GET endpoint /protected that uses verify_token as a dependency and returns a JSON message {"message": "Access granted"}
💡 Why This Matters
🌍 Real World
APIs often require secure access control using bearer tokens to protect user data and resources.
💼 Career
Understanding bearer token handling is essential for backend developers working on secure web services and APIs.
Progress0 / 4 steps
1
Create FastAPI app and secret token
Import FastAPI from fastapi. Create a FastAPI app instance called app. Create a string variable called SECRET_TOKEN and set it to "mysecrettoken123".
FastAPI
Hint

Remember to import FastAPI first, then create the app and the secret token variable exactly as named.

2
Create token verification dependency
Import Depends, HTTPException, and status from fastapi. Import Header from fastapi. Define a function called verify_token that takes authorization: str | None = Header(default=None). Inside, check if authorization is None or does not start with "Bearer ". If so, raise HTTPException with status code status.HTTP_401_UNAUTHORIZED and detail "Invalid or missing token". Extract the token string after "Bearer " and check if it equals SECRET_TOKEN. If not, raise the same HTTPException. Return True if token is valid.
FastAPI
Hint

Use the Header parameter to get the Authorization header. Check for the 'Bearer ' prefix and compare the token to SECRET_TOKEN.

3
Create protected GET endpoint
Create a GET endpoint /protected using @app.get("/protected"). Add a parameter token: bool = Depends(verify_token) to use the token verification dependency. Return a dictionary {"message": "Access granted"} from the endpoint function.
FastAPI
Hint

Use Depends to call verify_token in the endpoint parameters. Return the success message as a dictionary.

4
Add CORS middleware for cross-origin requests
Import CORSMiddleware from fastapi.middleware.cors. Add CORS middleware to app with allow_origins=["*"], allow_credentials=True, allow_methods=["*"], and allow_headers=["*"]. This enables the API to be accessed from any website during development.
FastAPI
Hint

Use app.add_middleware with CORSMiddleware and set all allow options to "*" or True as shown.