Complete the code to import the base class for middleware in FastAPI.
from starlette.middleware.base import [1]
The BaseHTTPMiddleware class is the base class used to create custom middleware in FastAPI.
Complete the code to define the async method that processes each request in custom middleware.
class CustomMiddleware(BaseHTTPMiddleware): async def [1](self, request, call_next): response = await call_next(request) return response
The dispatch method is the required async method to process requests in FastAPI custom middleware.
Fix the error in the middleware code by completing the missing import for the Request class.
from fastapi import FastAPI from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import [1] app = FastAPI()
The Request class from starlette.requests is needed to type hint or use the request object in middleware.
Fill both blanks to add the custom middleware to the FastAPI app.
app = FastAPI() app.add_middleware([1], app=[2])
BaseHTTPMiddleware directly instead of the custom class.You add your custom middleware class CustomMiddleware to the app using add_middleware, passing the app instance as a parameter.
Fill all three blanks to modify the response headers inside the custom middleware.
class CustomMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): response = await call_next(request) response.headers[[1]] = [2] response.headers[[3]] = "CustomValue" return response
To add custom headers, you assign header names and values to response.headers. Here, "X-Custom-Header" and "X-Another-Header" are header names, and "Processed" is a header value.