Complete the code to import the FastAPI class.
from fastapi import [1] app = [1]()
The FastAPI class is imported to create the app instance.
Complete the code to create a dependency that checks for a token.
from fastapi import Depends, HTTPException, Header def get_token(token: str = [1]): if token != "secret": raise HTTPException(status_code=401, detail="Unauthorized") return token
Header(None) extracts the token from HTTP headers for authentication.
Fix the error in the route to use the dependency correctly.
@app.get("/protected") async def protected_route(token: str = [1]): return {"token": token}
Depends expects the function itself, not a call, so use Depends(get_token).
Fill both blanks to create a protected POST route that requires a token.
@app.post("/submit") async def submit_data(data: dict, token: str = [1]): return {"data": data, "token": [2]
The token parameter uses Depends(get_token) and the returned token is referenced by its name.
Fill all three blanks to create a protected route that raises an error if token is missing or invalid.
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
Use Header(None) to get the token, and raise HTTPException with appropriate messages for missing or invalid tokens.