Bird
Raised Fist0
FastAPIframework~10 mins

Bearer token handling in FastAPI - Interactive Code Practice

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the correct FastAPI security class for bearer token handling.

FastAPI
from fastapi.security import [1]
Drag options to blanks, or click blank then click option'
AHTTPBasic
BAPIKeyHeader
COAuth2PasswordBearer
DHTTPBearer
Attempts:
3 left
💡 Hint
Common Mistakes
Choosing OAuth2PasswordBearer which is for OAuth2 flows, not simple bearer tokens.
Choosing HTTPBasic which is for basic auth, not bearer tokens.
2fill in blank
medium

Complete the code to create an instance of the HTTPBearer security scheme.

FastAPI
security = [1]()
Drag options to blanks, or click blank then click option'
AOAuth2PasswordBearer
BHTTPBearer
CHTTPBasic
DAPIKeyHeader
Attempts:
3 left
💡 Hint
Common Mistakes
Instantiating OAuth2PasswordBearer which requires a token URL.
Using HTTPBasic which is unrelated to bearer tokens.
3fill in blank
hard

Fix the error in the dependency function to correctly extract the bearer token string.

FastAPI
async def get_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
    return credentials.[1]
Drag options to blanks, or click blank then click option'
Atoken
Btoken_type
Ccredentials
Daccess_token
Attempts:
3 left
💡 Hint
Common Mistakes
Using token_type which is usually 'Bearer', not the token itself.
Using access_token which is not an attribute of HTTPAuthorizationCredentials.
4fill in blank
hard

Fill both blanks to define a FastAPI route that requires a bearer token and returns it.

FastAPI
from fastapi import FastAPI, Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

app = FastAPI()
security = HTTPBearer()

@app.get("/token")
async def read_token(credentials: [1] = Depends(security)):
    return {"token": credentials.[2]
Drag options to blanks, or click blank then click option'
AHTTPAuthorizationCredentials
BHTTPBearer
Ctoken
Dtoken_type
Attempts:
3 left
💡 Hint
Common Mistakes
Using HTTPBearer as the parameter type instead of HTTPAuthorizationCredentials.
Returning token_type instead of token.
5fill in blank
hard

Fill all three blanks to create a dependency that validates the bearer token prefix and returns the token string.

FastAPI
from fastapi import HTTPException, status

async def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
    if credentials.scheme != [1]:
        raise HTTPException(status_code=[2], detail="Invalid authentication scheme")
    return credentials.[3]
Drag options to blanks, or click blank then click option'
A"Bearer"
Bstatus.HTTP_401_UNAUTHORIZED
Ctoken
D"Basic"
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for "Basic" scheme instead of "Bearer".
Using wrong status code like 403 instead of 401.
Returning scheme or token_type instead of token.

Practice

(1/5)
1. What is the main purpose of using a Bearer token in FastAPI?
easy
A. To serve static files efficiently
B. To format JSON responses automatically
C. To speed up database queries
D. To securely identify and authorize API requests

Solution

  1. Step 1: Understand Bearer token role

    Bearer tokens are used to prove the client has permission to access protected routes.
  2. Step 2: Identify purpose in FastAPI

    FastAPI uses Bearer tokens to check authorization before allowing access to API endpoints.
  3. Final Answer:

    To securely identify and authorize API requests -> Option D
  4. Quick Check:

    Bearer token = Authorization [OK]
Hint: Bearer tokens are for security and access control [OK]
Common Mistakes:
  • Confusing token with response formatting
  • Thinking token speeds up database
  • Assuming token serves static files
2. Which FastAPI class is used to extract a Bearer token from the Authorization header?
easy
A. OAuth2PasswordBearer
B. HTTPBasicCredentials
C. OAuth2PasswordRequestForm
D. APIKeyHeader

Solution

  1. Step 1: Recall FastAPI token extraction classes

    OAuth2PasswordBearer is designed to read Bearer tokens from the Authorization header.
  2. 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.
  3. Final Answer:

    OAuth2PasswordBearer -> Option A
  4. Quick Check:

    Bearer token extractor = OAuth2PasswordBearer [OK]
Hint: Bearer token uses OAuth2PasswordBearer class [OK]
Common Mistakes:
  • Using OAuth2PasswordRequestForm for token extraction
  • Confusing basic auth with Bearer token
  • Choosing APIKeyHeader for Bearer tokens
3. Given this FastAPI dependency:
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?
medium
A. {"token": "Bearer abc123"}
B. HTTP 401 Unauthorized error
C. {"token": "abc123"}
D. {"token": null}

Solution

  1. Step 1: Understand OAuth2PasswordBearer behavior

    This class extracts only the token string after 'Bearer ' from the Authorization header.
  2. Step 2: Analyze the returned value

    The function returns a JSON with the token string, so it will return {"token": "abc123"}.
  3. Final Answer:

    {"token": "abc123"} -> Option C
  4. Quick Check:

    Bearer token string extracted = "abc123" [OK]
Hint: OAuth2PasswordBearer strips 'Bearer ' prefix automatically [OK]
Common Mistakes:
  • Expecting full 'Bearer abc123' string returned
  • Assuming 401 error without token validation
  • Thinking token is null if present
4. What is wrong with this FastAPI code snippet for Bearer token validation?
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}
medium
A. The token check should use 'if not token' instead of 'if token == None'
B. OAuth2PasswordBearer does not extract tokens from headers
C. The route path should not end with a slash
D. HTTPException requires a status_code of 403 for invalid tokens

Solution

  1. 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.
  2. Step 2: Correct token presence check

    Using 'if not token' is safer to catch empty strings or missing tokens rather than 'token == None'.
  3. Final Answer:

    The token check should use 'if not token' instead of 'if token == None' -> Option A
  4. Quick Check:

    Token presence check = 'if not token' [OK]
Hint: Check token presence with 'if not token' for safety [OK]
Common Mistakes:
  • Using 'token == None' which misses empty strings
  • Thinking OAuth2PasswordBearer doesn't extract tokens
  • Confusing HTTP status codes for auth errors
5. You want to protect a FastAPI route so only requests with the exact Bearer token "secret123" are allowed. Which code snippet correctly implements this?
hard
A. async def protected_route(token: str = Depends(oauth2_scheme)): if token == None: return {"message": "Access granted"} raise HTTPException(status_code=401, detail="Unauthorized")
B. async def protected_route(token: str = Depends(oauth2_scheme)): if token != "secret123": raise HTTPException(status_code=401, detail="Unauthorized") return {"message": "Access granted"}
C. async def protected_route(token: str): if token == "secret123": return {"message": "Access granted"} raise HTTPException(status_code=403, detail="Forbidden")
D. async def protected_route(token: str = Depends(oauth2_scheme)): if token == "Bearer secret123": return {"message": "Access granted"} raise HTTPException(status_code=401, detail="Unauthorized")

Solution

  1. Step 1: Use OAuth2PasswordBearer dependency

    We must use Depends(oauth2_scheme) to extract the token from the Authorization header.
  2. 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.
  3. 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 B
  4. Quick Check:

    Compare token string directly to "secret123" [OK]
Hint: Compare token string directly, no 'Bearer ' prefix included [OK]
Common Mistakes:
  • Comparing token to 'Bearer secret123' including prefix
  • Not using Depends(oauth2_scheme) to get token
  • Returning access granted when token is None