Junior — Middle
Can you explain what middleware means in the context of FastAPI and how it is used?
sobes.tech AI
Answer from AI
In FastAPI, middleware is a component that intercepts HTTP requests and/or responses, allowing for additional processing before and after the request is handled by the endpoint function.
Middleware is used for tasks such as:
- Logging requests and responses
- Authentication and authorization
- Handling CORS
- Modifying or adding headers
- Error handling
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
Here, the middleware logs request information and adds a custom header to the response. Middleware in FastAPI allows centralized management of application behavior at the request and response level.