Bird
Raised Fist0
FastAPIframework~20 mins

Protected routes in FastAPI - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
FastAPI Protected Routes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output when accessing a protected route without credentials?

Consider a FastAPI app with a route protected by HTTP Basic authentication. What happens if a client tries to access the route without providing any credentials?

FastAPI
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials

app = FastAPI()
security = HTTPBasic()

@app.get('/protected')
def protected_route(credentials: HTTPBasicCredentials = Depends(security)):
    if credentials.username == 'user' and credentials.password == 'pass':
        return {'message': 'Access granted'}
    raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Invalid credentials')
AThe server responds with status 403 Forbidden and message 'Invalid credentials'
BThe server responds with status 401 Unauthorized and a detail message 'Not authenticated'
CThe server responds with status 200 OK and message 'Access granted'
DThe server crashes with a runtime error due to missing credentials
Attempts:
2 left
💡 Hint

Think about what FastAPI's HTTPBasic security does when no credentials are sent.

state_output
intermediate
2:00remaining
What is the response when correct credentials are provided?

Given the same FastAPI app as before, what is the response when the client sends username 'user' and password 'pass'?

FastAPI
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials

app = FastAPI()
security = HTTPBasic()

@app.get('/protected')
def protected_route(credentials: HTTPBasicCredentials = Depends(security)):
    if credentials.username == 'user' and credentials.password == 'pass':
        return {'message': 'Access granted'}
    raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Invalid credentials')
A{'detail': 'Invalid credentials'} with status 401 Unauthorized
BEmpty response with status 204 No Content
C{'detail': 'Not authenticated'} with status 401 Unauthorized
D{'message': 'Access granted'} with status 200 OK
Attempts:
2 left
💡 Hint

Check the condition inside the route function for valid credentials.

📝 Syntax
advanced
2:00remaining
Which option correctly protects a route using OAuth2PasswordBearer?

Which code snippet correctly uses OAuth2PasswordBearer to protect a FastAPI route?

A
oauth2_scheme = OAuth2PasswordBearer(tokenUrl='token')

@app.get('/items')
async def read_items(token: str = Depends(oauth2_scheme)):
    return {'token': token}
B
oauth2_scheme = OAuth2PasswordBearer(tokenUrl='token')

@app.get('/items')
async def read_items(token: OAuth2PasswordBearer = Depends()):
    return {'token': token}
C
oauth2_scheme = OAuth2PasswordBearer(tokenUrl='token')

@app.get('/items')
async def read_items(token: str):
    return {'token': token}
D
oauth2_scheme = OAuth2PasswordBearer(tokenUrl='token')

@app.get('/items')
async def read_items(token: str = oauth2_scheme):
    return {'token': token}
Attempts:
2 left
💡 Hint

Remember how Depends is used to inject dependencies in FastAPI.

🔧 Debug
advanced
2:00remaining
Why does this protected route always return 401 Unauthorized?

Examine the code below. The route always returns 401 Unauthorized even with correct credentials. What is the cause?

FastAPI
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials

app = FastAPI()
security = HTTPBasic()

@app.get('/secure')
def secure_route(credentials: HTTPBasicCredentials = Depends(security)):
    if credentials.username == 'user' and credentials.password == 'pass':
        return {'message': 'Welcome!'}
    raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Invalid credentials')

# Client sends username 'user' and password 'pass' but gets 401 Unauthorized
AThe client is not sending credentials in the correct HTTP Basic Authorization header format
BThe security dependency is not called because Depends is missing
CThe route function is missing async keyword causing authentication failure
DThe HTTPException status code should be 403 Forbidden instead of 401 Unauthorized
Attempts:
2 left
💡 Hint

Check how HTTP Basic authentication expects credentials from the client.

🧠 Conceptual
expert
2:00remaining
What is the main benefit of using dependency injection for protected routes in FastAPI?

Why does FastAPI use dependency injection (Depends) to handle authentication in protected routes?

AIt automatically encrypts all route responses for security
BIt forces all routes to require authentication even if not needed
CIt allows reusing authentication logic across multiple routes without repeating code
DIt disables access to routes during server startup
Attempts:
2 left
💡 Hint

Think about how dependencies help organize code in FastAPI.

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