In a general sense, the answer given by @lsabi is correct.
In the context of FastAPI though, there's no way of defining a middleware on a particular API router (as of Aug 2022).
All the middlewares are usually on global app level (though you can write your own logic to apply it on only a specific route by regex/filtering, not very clean solution imo), and if that's the only way you want to go, you have to create a separate application for each route (using mounts), and then you can write their own middlewares, as explained here:
https://github.com/tiangolo/fastapi/issues/1174#issuecomment-605508353
But for route dependencies, this statement isn't entirely true:
The middleware can be seen as a superset of a Dependency
Even though, dependencies by defination don't reject/forward stuff, In FastAPI, you can always raise an exception (might be HTTPException) from a dependency which will cause it to reject the request, before it reaches to the route handler.
so you can do something like:
async def auth_middleware(request: Request):
# your code to check if user is authenticated
# ...
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated bruh"
)
router = APIRouter(dependencies=[Depends(auth_middleware)])
now, before executing any route handler defined on the router, first it will run the auth_middleware function. Which is exactly how a middleware is supposed to work.
The only caveat here is that, because it's a dependency, it has to run before the route handler.
So if your use case requires you to handle something after, this wouldn't work.
I didn't come across any such requirement, selective gzipping might be one example, but you shouldn't be gzipping your http response in python anyway.
Hope that helps!