0
0
FastAPIframework~10 mins

Protected routes in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the FastAPI class.

FastAPI
from fastapi import [1]
app = [1]()
Drag options to blanks, or click blank then click option'
AFastAPI
BRequest
CDepends
DHTTPException
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request instead of FastAPI
Using Depends in place of FastAPI
2fill in blank
medium

Complete the code to create a dependency that checks for a token.

FastAPI
from fastapi import Depends, HTTPException, Header

def get_token(token: str = [1]):
    if token != "secret":
        raise HTTPException(status_code=401, detail="Unauthorized")
    return token
Drag options to blanks, or click blank then click option'
AHeader(None)
BQuery(None)
CCookie(None)
DBody(None)
Attempts:
3 left
💡 Hint
Common Mistakes
Using Query instead of Header for token
Using Body which expects JSON payload
3fill in blank
hard

Fix the error in the route to use the dependency correctly.

FastAPI
@app.get("/protected")
async def protected_route(token: str = [1]):
    return {"token": token}
Drag options to blanks, or click blank then click option'
ADepends(get_token())
Bget_token()
CDepends(get_token)
Dget_token
Attempts:
3 left
💡 Hint
Common Mistakes
Calling get_token inside Depends with parentheses
Passing get_token without Depends
4fill in blank
hard

Fill both blanks to create a protected POST route that requires a token.

FastAPI
@app.post("/submit")
async def submit_data(data: dict, token: str = [1]):
    return {"data": data, "token": [2]
Drag options to blanks, or click blank then click option'
ADepends(get_token)
Btoken
CDepends(get_token())
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Using Depends(get_token()) with parentheses
Referencing data instead of token in the return
5fill in blank
hard

Fill all three blanks to create a protected route that raises an error if token is missing or invalid.

FastAPI
from fastapi import Header, HTTPException

async def get_token(token: str = [1]):
    if not token:
        raise HTTPException(status_code=401, detail=[2])
    if token != "secret":
        raise HTTPException(status_code=403, detail=[3])
    return token
Drag options to blanks, or click blank then click option'
AHeader(None)
B"Token missing"
C"Invalid token"
DQuery(None)
Attempts:
3 left
💡 Hint
Common Mistakes
Using Query instead of Header
Raising wrong status codes or messages