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

Caching dependency result in APIRouter (avoid double validation on nested routers deps)#14324

AnsweredbyYuriiMotov
Arivadis 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

fromfastapiimportRequest,HTTPException,Depends,APIRouterfromjoseimportjwt,JWTErrorSECRET="..."ALGO="HS256"defverify_token(request:Request):ifhasattr(request.state,"user"):returnrequest.state.usertoken=request.cookies.get("access_token")ifnottoken:raiseHTTPException(status_code=401)try:payload=jwt.decode(token,SECRET,algorithms=[ALGO])exceptJWTError:raiseHTTPException(status_code=401)request.state.user=payloadreturnpayloaddefis_admin(request:Request=Depends(verify_token)):user=request.state.userifnotuser.get("is_admin"):raiseHTTPException(status_code=403)returnuserroot_router=APIRouter(prefix="",dependencies=[Depends(verify_token)])admin_router=APIRouter(prefix="/admin",dependencies=[Depends(is_admin)])root_router.include_router(admin_router)

Description

Hi!
Hope you’re doing well.

I’ve got a question regarding how dependencies are executed when using nested APIRouters.

If I attach a dependency like Depends(verify_token) to the root router, I don’t have to repeat token validation in every route — which is great.
However, if I include another router under it (for example /admin) that also defines its own dependency (Depends(is_admin)), both dependencies execute, and the token is validated twice.

This works correctly but feels redundant, since is_admin depends on verify_token anyway.
I’d like to cache the result of the top-level validation so that deeper routers can reuse it instead of triggering another validation pass.

The main step is in

if hasattr(request.state, "user"):          return request.state.user

The caching workaround with request.state may work fine, but I’m wondering if this approach is recommended at all — or if there’s (or planned) a more native way to reuse the dependency results across routers without re-executing them.

Operating System

Windows

Operating System Details

11

FastAPI Version

0.120.4

Pydantic Version

v2.11

Python Version

3.11

Additional Context

No response

You must be logged in to vote
...def is_admin(request: Request = Depends(verify_token)):    ...

This will not work. If you annotate parameter withRequest it's treated as special dependency and you can't useDepends with it.

Instead of storing user inrequest.state, you can just return it.
FastAPI hasinternal caching mechanism for dependencies:

fromfastapiimportFastAPI,Request,Depends,APIRouterdefverify_token(request:Request):print("verify_token called")return"payload"defis_admin(token:str=Depends(verify_token)):print("is_admin is called")return"user"root_router=APIRouter(prefix="",dependencies=[Depends(verify_token)])admin_router=APIRouter(prefix="/admin",dependen…

Replies: 1 comment 1 reply

Comment options

...def is_admin(request: Request = Depends(verify_token)):    ...

This will not work. If you annotate parameter withRequest it's treated as special dependency and you can't useDepends with it.

Instead of storing user inrequest.state, you can just return it.
FastAPI hasinternal caching mechanism for dependencies:

fromfastapiimportFastAPI,Request,Depends,APIRouterdefverify_token(request:Request):print("verify_token called")return"payload"defis_admin(token:str=Depends(verify_token)):print("is_admin is called")return"user"root_router=APIRouter(prefix="",dependencies=[Depends(verify_token)])admin_router=APIRouter(prefix="/admin",dependencies=[Depends(is_admin)])@admin_router.get("/me")defread_admin_me(user:str=Depends(is_admin)):return {"admin_user":user}root_router.include_router(admin_router)app=FastAPI()app.include_router(router=root_router)

Run this and you will see that despite havingverify_token included 3 times in dependency tree, it will only called once

You must be logged in to vote
1 reply
@Arivadis
Comment options

Many thanks.

Answer selected byYuriiMotov
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Labels
questionQuestion or problem
2 participants
@Arivadis@YuriiMotov

[8]ページ先頭

©2009-2025 Movatter.jp