link
fastapi/custom-route

Custom Route Class

Create advanced routes

advanced
routing

Command

Examples

Custom route handler

from fastapi.routing import APIRoute
  
  class CustomRoute(APIRoute):
      def get_route_handler(self):
          original_route_handler = super().get_route_handler()
          
          async def custom_route_handler(request):
              # Pre-processing
              response = await original_route_handler(request)
              # Post-processing
              return response
              
          return custom_route_handler
  
  app = FastAPI()
  app.router.route_class = CustomRoute