Complete the code to import FastAPI and create an app instance.
from fastapi import [1] app = [1]()
The FastAPI class is imported and used to create the app instance.
Complete the code to define a GET endpoint that returns a welcome message.
@app.[1]("/") async def root(): return {"message": "Welcome to the API"}
The GET method is used to define an endpoint that responds to HTTP GET requests.
Fix the error in the code to add a security dependency for API key verification.
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"}
The Depends function is used to declare a dependency on the APIKeyHeader instance for security.
Fill both blanks to create a middleware that logs each request's method and URL.
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)
The dispatch method receives a Request object. The request path is accessed via request.path.
Fill all three blanks to create a dictionary comprehension that filters headers starting with 'X-' and converts keys to lowercase.
filtered_headers = { [1].lower(): [2] for [1], [3] in request.headers.items() if [1].startswith("X-") }The comprehension iterates over key, value pairs. Keys are converted to lowercase and filtered by prefix.