Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

116
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda