Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to Get the Current User with dependencies added to APIRouter#11150

Answeredbyjgould22
Zaeem6100 asked this question inQuestions
Discussion options

First Check

  • I added a very descriptive title here.
  • I used the GitHub search to find a similar question and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but toPydantic.
  • I already checked if it is not related to FastAPI but toSwagger UI.
  • I already checked if it is not related to FastAPI but toReDoc.

Commit to Help

  • I commit to help with one of those options 👆

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")

Description

I 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 System

Windows

Operating System Details

No response

FastAPI Version

0.109.2

Pydantic Version

2.6.1

Python Version

3.10.5

Additional Context

No response

You must be logged in to vote

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

Comment options

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.

You must be logged in to vote
4 replies
@henrymcl
Comment options

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.

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?

@jymchng
Comment options

It will be cached.Depends function has ause_cache parameter which is by defaultTrue.

@henrymcl
Comment options

Sorry I have another question on the caching: it works very fine for simple function-based dependencies, but what about parameterized class dependencies? When/admin is visited RoleChecker is run for 3 times

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)
@jymchng
Comment options

Hi

It must be ran at least twice for your use case.

The dependency on the@app.get decorator is meant for the route even before the dependencies for the endpoint parameter is injected.

And for the two parameters, e.g.current_user_role and the other one, I suppose you would want to check the role for each 'User' which is then injected into the endpoint function as different 'User' arguments.

From this context, the route dependency is a little redundant hence at the start I mentioned it as 'at least twice'.

Answer selected byKludex
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Labels
questionQuestion or problem
4 participants
@Zaeem6100@jgould22@henrymcl@jymchng

[8]ページ先頭

©2009-2025 Movatter.jp