Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
FastAPI get user ID from API key

In fastAPI one can simply write a security dependency at the router level and secure an entire part of the URLs.

router.include_router(
    my_router,
    prefix="/mypath",
    dependencies=[Depends(auth.oauth2_scheme)]
)

This avoids repeating a lot of code.

The only problem is that I would like to protect a part of URLs with a router level dependency that checks the validity of the user token and retrieve the user id for that token.

The only way I found, is to add another dependency to all the functions, but this leads to repeating the code that I just saved.

Long story short, is there a way to add the dependency at the router level, retrieve and return the user id, and pass the returned value to the handling function? Something like

router.py

router.include_router(
        my_router,
        prefix="/mypath",
        dependencies=[user_id = Depends(auth.oauth2_scheme)]
    )

my_router.py

my_router = APIRouter()

@my_router.get("/my_path")
async def get_my_path(**kwargs):
    user_id = kwargs["user_id"]
    # Do stuff with the user_id
    return {}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Once the user is authenticated in the dependency function add the user_id to request.state, then on your route you can access it from the request object.

async def oauth2_scheme(request: Request):
    request.state.user_id = "foo"

my_router  = APIRouter()

@my_router .get("/")
async def hello(request: Request):
    print(request.state.user_id)

app.include_router(
    my_router,
    dependencies=[Depends(oauth2_scheme)]
)

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!