Sobes.tech
Junior — Middle

What is the role of Middleware in FastAPI and why is it used in applications?

sobes.tech AI

Answer from AI

Middleware in FastAPI is a component that intercepts HTTP requests and responses, allowing for additional processing before and after calling endpoints. It is used for tasks such as logging, authentication, session management, CORS handling, modifying requests or responses, and other cross-cutting concerns.

Example of using middleware in FastAPI:

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

app = FastAPI()

class SimpleMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        print(f"Received request: {request.method} {request.url}")
        response = await call_next(request)
        print(f"Response sent with status: {response.status_code}")
        return response

app.add_middleware(SimpleMiddleware)

@app.get("/")
async def root():
    return {"message": "Hello World"}

Thus, middleware helps to centrally handle common tasks without cluttering individual handlers' code.