Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork8.3k
-
First Check
Commit to Help
Example Code#here is my router.py filefromfastapiimportAPIRouter,Dependsfromsrc.auth.dependenciesimportverify_userrouter=APIRouter(prefix="/auth",tags=["auth"],dependencies=[Depends(verify_user)],responses={404: {"description":"Not found"}},)@router.get("/",tags=["auth"])asyncdefroot():return {"message":"Hello auth"}# dependency.pyasyncdefverify_user(x_token:Annotated[str,Header()])->User:try:ifx_token=="uza":# todo: set the default user to a fake userreturnUser(first_name="fake",username="faker",email="example@example.com",age=21)else:payload=jwt.decode(x_token,JWT_SECRET_KEY,algorithms=["HS256"])print(payload)returnUser(**payload)exceptJWTErrorase:raiseHTTPException(status_code=401,detail="Invalid token provided") DescriptionI have added the dependencies in the APIRouter. I want to auth the token at the highest level so won't want to define it in every API. So my question is how would I get the current user. i also have added my dependency.py file. Operating SystemWindows Operating System DetailsNo response FastAPI Version0.109.2 Pydantic Version2.6.1 Python Version3.10.5 Additional ContextNo response |
BetaWas this translation helpful?Give feedback.
All reactions
The result of router based dependencies is discarded after the dependency is run as it says in the docshere.
FastAPI is designed around dependency injection for the path operations so the idea is to give every request that needs a user the user dependency.
Replies: 1 comment 4 replies
-
The result of router based dependencies is discarded after the dependency is run as it says in the docshere. FastAPI is designed around dependency injection for the path operations so the idea is to give every request that needs a user the user dependency. |
BetaWas this translation helpful?Give feedback.
All reactions
-
If I have the same dependency in router as well as in the path operation (for getting current user), will the dependency be called twice or will it be cached? |
BetaWas this translation helpful?Give feedback.
All reactions
-
It will be cached. |
BetaWas this translation helpful?Give feedback.
All reactions
👍 1
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
-
Sorry I have another question on the caching: it works very fine for simple function-based dependencies, but what about parameterized class dependencies? When fromtypingimportAnnotatedimportuvicornfromfastapiimportDepends,FastAPI,HTTPException,statusapp=FastAPI()classRoleChecker:def__init__(self,allowed_role:str):self.allowed_role=allowed_roledef__call__(self,role:str="guest"):print(f"called with{role} <=>{self.allowed_role}")ifrolenotinself.allowed_role:raiseHTTPException(status_code=status.HTTP_403_FORBIDDEN,detail=f"User with role '{role}' is not allowed to access this endpoint.", )returnrole# --- Using the Parameterized Dependencies in Routes ---@app.get("/admin",dependencies=[Depends(RoleChecker("admin"))])asyncdefadmin_dashboard(current_user_role:Annotated[str,Depends(RoleChecker("admin"))],current_user_role2:Annotated[str,Depends(RoleChecker("admin"))],):return {"message":"Welcome to the admin dashboard!","role":current_user_role}@app.get("/")asyncdefindex():""" A public endpoint that doesn't require any specific role. """return {"message":"Welcome to the API. Try accessing /admin or /profile with a role parameter." }if__name__=="__main__":uvicorn.run("poc:app",host="0.0.0.0",port=8001,reload=True) |
BetaWas this translation helpful?Give feedback.
All reactions
-
Hi It must be ran at least twice for your use case. The dependency on the And for the two parameters, e.g. From this context, the route dependency is a little redundant hence at the start I mentioned it as 'at least twice'. |
BetaWas this translation helpful?Give feedback.