0
0
FastAPIframework~10 mins

Why API security is critical in FastAPI - Test Your Understanding

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

Complete the code to import FastAPI and create an app instance.

FastAPI
from fastapi import [1]

app = [1]()
Drag options to blanks, or click blank then click option'
ADepends
BRequest
CResponse
DFastAPI
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request or Response instead of FastAPI.
Not creating the app instance with FastAPI().
2fill in blank
medium

Complete the code to define a GET endpoint that returns a welcome message.

FastAPI
@app.[1]("/")
async def root():
    return {"message": "Welcome to the API"}
Drag options to blanks, or click blank then click option'
Apost
Bput
Cget
Ddelete
Attempts:
3 left
💡 Hint
Common Mistakes
Using POST or PUT instead of GET for a simple data retrieval.
Forgetting the @app decorator.
3fill in blank
hard

Fix the error in the code to add a security dependency for API key verification.

FastAPI
from fastapi.security import APIKeyHeader
from fastapi import Depends

api_key_header = APIKeyHeader(name="X-API-Key")

@app.get("/secure")
async def secure_endpoint(api_key: str = [1]):
    if api_key != "secret-key":
        return {"error": "Unauthorized"}
    return {"message": "Secure data"}
Drag options to blanks, or click blank then click option'
ADepends(api_key_header)
Bapi_key_header
CDepends()
Dapi_key
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the APIKeyHeader instance directly without Depends.
Using Depends() without arguments.
4fill in blank
hard

Fill both blanks to create a middleware that logs each request's method and URL.

FastAPI
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware

class LoggingMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: [1], call_next):
        print(f"Request: {request.method} {request.[2]")
        response = await call_next(request)
        return response

app.add_middleware(LoggingMiddleware)
Drag options to blanks, or click blank then click option'
ARequest
BResponse
Curl
Dpath
Attempts:
3 left
💡 Hint
Common Mistakes
Using Response instead of Request in dispatch.
Accessing request.url instead of request.path for the path string.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that filters headers starting with 'X-' and converts keys to lowercase.

FastAPI
filtered_headers = { [1].lower(): [2] for [1], [3] in request.headers.items() if [1].startswith("X-") }
Drag options to blanks, or click blank then click option'
Akey
Bvalue
Dheader
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up key and value variable names.
Not converting keys to lowercase.