0
0
FastAPIframework~20 mins

Protected routes in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
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.