This issue was moved to a discussion.
You can continue the conversation there. Go to discussion →
How to use middleware for a specific route only in a single APIRouter #4437
Labels
You can continue the conversation there. Go to discussion →
First Check
Commit to Help
Example Code
Description
FastAPI has a feature to have sub-apps. But it's not applicable in all cases, especially in my case where I have an
APIRouter
instance with 3 path operations/routes:login_user
,create_user
,get_logged_in_user
. And I have an authentication middlware.I spent a lot of time trying to find a way to only use that middleware in the
get_logged_in_user
operation, and not the other ones. But I found nothing regarding this. All I found online was using sub-apps, but I was trying to find a way to be able to use middlewares for a few specific routes in the sameAPIRouter
instance.So is there some kind of way where I can attach a middleware to a select few routes/operations in a single APIRouter instance? Because at the moment, the middleware is being triggered on all routes, including my user create and login path operations; which isn't practical.
This is how I'm adding my middleware, since it's in a separate file.
Operating System
Linux
Operating System Details
Linux Mint. Kernel version: 5.4.0-74-generic
DE: Not using one, just DWM
FastAPI Version
0.72.0
Python Version
Python 3.8.10
Additional Context
I have just taken a look at the source code, and it seems that the FastAPI middleware system is actually handled by Starlette. So
does that mean per-route/per-APIRouter middleware is something unrelated to FastAPI but related to Starlette itself?
The text was updated successfully, but these errors were encountered: