Complete the code to define a middleware function in FastAPI.
from fastapi import FastAPI app = FastAPI() @app.middleware("[1]") async def log_requests(request, call_next): response = await call_next(request) return response
The middleware decorator in FastAPI uses the string "http" to indicate it processes HTTP requests globally.
Complete the code to call the next middleware or route handler inside the middleware.
async def log_requests(request, call_next): response = await [1](request) return response
Inside middleware, you call the next handler using the 'call_next' function with the request.
Fix the error in the middleware function to ensure it processes all requests globally.
from fastapi import FastAPI app = FastAPI() @app.middleware("http") async def [1](request, call_next): response = await call_next(request) return response
The middleware function name can be anything, but 'log_requests' is the conventional name used here to indicate its purpose.
Fill both blanks to create a middleware that adds a custom header to every response.
from fastapi import FastAPI app = FastAPI() @app.middleware("http") async def add_header(request, call_next): response = await call_next(request) response.headers[[1]] = [2] return response
The middleware adds a custom header named "X-Custom-Header" with the value "Hello" to every response.
Fill both blanks to create a middleware that logs the request method and path before processing.
from fastapi import FastAPI app = FastAPI() @app.middleware("http") async def log_request_info(request, call_next): print(f"Request: [1] [2]") response = await call_next(request) return response
The middleware prints the HTTP method and URL path of the incoming request before calling the next handler.