Bird
Raised Fist0
FastAPIframework~10 mins

Protected routes in FastAPI - Step-by-Step Execution

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
Concept Flow - Protected routes
Client sends request
Check for auth token
Reject request
Validate token
Allow access
Return protected data
The server checks if the client request has a valid token before allowing access to protected data.
Execution Sample
FastAPI
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

async def get_current_user(token: str = Depends(oauth2_scheme)):
    if token != "validtoken":
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
    return {"user": "alice"}

@app.get("/protected")
async def protected_route(current_user: dict = Depends(get_current_user)):
    return {"message": f"Hello {current_user['user']}"}
This code protects the /protected route by requiring a valid token to access it.
Execution Table
StepActionToken Present?Token Valid?ResultResponse
1Client requests /protected without tokenNoN/AReject request401 Unauthorized
2Client requests /protected with token='invalidtoken'YesNoReject request401 Unauthorized
3Client requests /protected with token='validtoken'YesYesAllow access{"message": "Hello alice"}
💡 Requests without a valid token are rejected with 401 Unauthorized.
Variable Tracker
VariableStartRequest 1Request 2Request 3
tokenNoneNoneinvalidtokenvalidtoken
current_userNoneNoneNone{"user": "alice"}
Key Moments - 3 Insights
Why does the request without a token get rejected immediately?
Because the OAuth2PasswordBearer dependency expects a token. Without it, the route dependency fails and returns 401 as shown in execution_table step 1.
What happens if the token is present but invalid?
The get_current_user function raises HTTPException with status 401, rejecting the request as seen in execution_table step 2.
How does the route know the current user?
The token is validated in get_current_user, which returns user info. This is passed to the route via Depends, shown in execution_table step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the response when the token is missing?
A200 OK with message
B404 Not Found
C401 Unauthorized
D500 Internal Server Error
💡 Hint
Check execution_table row 1 under Response column.
At which step does the token get validated as correct?
AStep 3
BStep 2
CStep 1
DNone
💡 Hint
Look at execution_table Token Valid? column.
If the token was 'validtoken' but get_current_user returned None, what would happen?
ARoute raises 401 Unauthorized
BRoute returns 500 error
CAccess allowed with empty user
DRequest ignored silently
💡 Hint
get_current_user succeeds (no exception raised), passing None to the route. Route accesses current_user['user'] causing TypeError/KeyError, resulting in 500 Internal Server Error.
Concept Snapshot
Protected routes require a valid token to access.
Use OAuth2PasswordBearer to extract token.
Validate token in a dependency function.
Raise HTTPException(401) if invalid.
Pass user info to route via Depends.
Return protected data only if authorized.
Full Transcript
Protected routes in FastAPI work by checking if the client sends a valid token with their request. The OAuth2PasswordBearer dependency extracts the token from the request. Then, a function like get_current_user validates this token. If the token is missing or invalid, the function raises an HTTPException with status 401, which stops the request and returns an unauthorized error. If the token is valid, the function returns user information, which the route uses to allow access and return protected data. This process ensures only authorized users can access certain routes.

Practice

(1/5)
1. What is the main purpose of protected routes in FastAPI?
easy
A. To automatically generate API documentation
B. To speed up the API response time
C. To allow anyone to access all endpoints without restrictions
D. To restrict access to certain endpoints by verifying user credentials

Solution

  1. Step 1: Understand what protected routes do

    Protected routes limit access to certain parts of an app by checking if the user is allowed.
  2. Step 2: Identify the correct purpose

    Only To restrict access to certain endpoints by verifying user credentials describes restricting access by verifying user credentials, which matches protected routes.
  3. Final Answer:

    To restrict access to certain endpoints by verifying user credentials -> Option D
  4. Quick Check:

    Protected routes = restrict access [OK]
Hint: Protected routes check user access before allowing endpoint use [OK]
Common Mistakes:
  • Thinking protected routes improve speed
  • Confusing protected routes with documentation features
  • Assuming protected routes allow open access
2. Which FastAPI feature is commonly used to enforce protected routes by requiring token verification?
easy
A. BackgroundTasks
B. Depends
C. Query
D. Path

Solution

  1. Step 1: Recall FastAPI dependency injection

    FastAPI uses Depends to declare dependencies like authentication checks.
  2. Step 2: Match feature to protected routes

    Using Depends with a function that verifies tokens enforces protection on routes.
  3. Final Answer:

    Depends -> Option B
  4. Quick Check:

    Token check uses Depends [OK]
Hint: Use Depends to add token checks on routes [OK]
Common Mistakes:
  • Confusing Depends with query or path parameters
  • Using BackgroundTasks for authentication
  • Not using any dependency for protection
3. Given this FastAPI code snippet, what will happen when accessing /users/me without a token?
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

def get_current_user(token: str = Depends(oauth2_scheme)):
    if token != "validtoken":
        raise HTTPException(status_code=401, detail="Invalid token")
    return {"username": "user1"}

@app.get("/users/me")
async def read_users_me(current_user: dict = Depends(get_current_user)):
    return current_user
medium
A. Raises HTTP 401 Unauthorized error
B. Returns {"username": "user1"} regardless of token
C. Returns an empty response
D. Raises HTTP 404 Not Found error

Solution

  1. Step 1: Analyze token dependency behavior

    The function get_current_user checks if the token equals "validtoken"; otherwise, it raises HTTP 401.
  2. Step 2: Consider no token case

    Without a token, oauth2_scheme will not provide a valid token, so the check fails and raises HTTP 401.
  3. Final Answer:

    Raises HTTP 401 Unauthorized error -> Option A
  4. Quick Check:

    No token = HTTP 401 error [OK]
Hint: No valid token triggers HTTP 401 error [OK]
Common Mistakes:
  • Assuming it returns user data without token
  • Confusing 401 with 404 error
  • Expecting empty response instead of error
4. Identify the error in this FastAPI protected route code:
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

def get_current_user(token: str):
    if token != "secret":
        raise HTTPException(status_code=401, detail="Unauthorized")
    return {"user": "admin"}

@app.get("/dashboard")
async def dashboard(user: dict = Depends(get_current_user)):
    return user
medium
A. OAuth2PasswordBearer is not imported
B. HTTPException is not imported
C. Missing Depends in get_current_user parameter
D. Route path is invalid

Solution

  1. Step 1: Check get_current_user parameter

    The function expects token: str but does not use Depends(oauth2_scheme) to get the token automatically.
  2. Step 2: Identify missing dependency injection

    Without Depends(oauth2_scheme), FastAPI won't provide the token, causing an error.
  3. Final Answer:

    Missing Depends in get_current_user parameter -> Option C
  4. Quick Check:

    Token param needs Depends(oauth2_scheme) [OK]
Hint: Use Depends(oauth2_scheme) to get token in dependencies [OK]
Common Mistakes:
  • Forgetting to import HTTPException
  • Not using Depends for token parameter
  • Incorrect route path syntax
5. How can you combine FastAPI's OAuth2PasswordBearer with a custom user verification function to protect multiple routes efficiently?
hard
A. Create a reusable dependency function that uses OAuth2PasswordBearer to get the token and verifies the user, then use Depends on routes
B. Add token verification code inside each route handler separately
C. Use OAuth2PasswordBearer only in the main app instance without dependencies
D. Skip token verification and rely on client-side checks

Solution

  1. Step 1: Understand reusable dependency pattern

    Creating a function that uses OAuth2PasswordBearer to get the token and verifies the user allows reuse across routes.
  2. Step 2: Apply Depends to routes

    Using Depends with this function on multiple routes enforces protection without repeating code.
  3. Final Answer:

    Create a reusable dependency function that uses OAuth2PasswordBearer to get the token and verifies the user, then use Depends on routes -> Option A
  4. Quick Check:

    Reusable dependency + Depends = efficient protection [OK]
Hint: Make one verify function and reuse with Depends on routes [OK]
Common Mistakes:
  • Duplicating token checks in every route
  • Not using Depends for token verification
  • Ignoring server-side token checks