I'm using FastAPI where the main app is using include_router
to add extra routes to the fastAPI app.
I would like to add a generic validation on all the routes. I found in the documentation that you can achieve this by using the dependencies when including a router.
https://fastapi.tiangolo.com/tutorial/bigger-applications/#the-main-fastapi
This works and is getting executed by all the http requests. Thus far everything great!
Now, I want to know inside this generic validation function (being injected using the Depends() in all the routes) what route is invoking the function.
I found a way to get access to the actual request (using fastapi.routing.Request as input parameter for the function) but I would like to get access to the function or the name of the APIRoute itself.
from fastapi import FastAPI, Depends
from fastapi.routing import Request, APIRoute
async def check_permission(req: Request, route: APIRoute):
print("test me")
app = FastAPI()
app.include_router(admin.service_api, dependencies=[Depends(check_permission)])
RuntimeError: no validator found for <class 'fastapi.routing.APIRoute'>
Perhaps this is a bad idea all together and should I do it in a different way? All suggestions are very much appreciated. Thank you.
Actually using the Request object is the best practice, since it holds the entire data of the Request, I can not see a reason to not to use it.
Even if you create a workaround for this error, you can not get this work in a proper way. Because the APIRoute is not a valid Pydantic Field type, so our FastAPI should be raising FastAPIError for this.
So the answer is: You should use Request object.