@jasen
To use middleware with routing in FastAPI, you need to create a custom middleware class that inherits from Middleware
class provided by FastAPI. Then, you can define the logic for the middleware in the __call__
method of the class. Here is an example of how to use middleware with routing in FastAPI:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse from fastapi.middleware import Middleware class CustomMiddleware: def __init__(self, app: FastAPI): self.app = app async def __call__(self, request: Request, call_next): # Add your middleware logic here print("Middleware executed before request handling") response = await call_next(request) # Add your middleware logic here print("Middleware executed after request handling") return response app = FastAPI() # Add custom middleware to the app app.add_middleware(Middleware, dispatch=CustomMiddleware) @app.get('/') async def root(): return {"message": "Hello World"} |
In this example, we create a custom middleware class CustomMiddleware
and define the middleware logic in the __call__
method. We then add the middleware to the FastAPI app using the add_middleware
method, passing in the custom middleware class as an argument.
When a request is made to the /
endpoint, the middleware logic will be executed before and after the request handling, as specified in the __call__
method of the custom middleware class.