Sobes.tech
Junior — Middle

Have you used middleware layers in FastAPI for request processing?

sobes.tech AI

Answer from AI

In FastAPI, middleware layers are used for processing requests and responses at the application level, for example, for logging, authentication, error handling, or modifying requests.

Middleware are functions that accept a request, can modify it or perform additional actions, and then pass control further.

An example of simple middleware in FastAPI:

from fastapi import FastAPI, Request

app = FastAPI()

@app.middleware("http")
async def simple_middleware(request: Request, call_next):
    print(f"Received request: {request.method} {request.url}")
    response = await call_next(request)
    response.headers["X-Custom-Header"] = "Value"
    return response

This middleware logs each incoming request and adds a custom header to the response.