Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

117
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda