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

350
Vistas
FastAPI - can't access path parameters from middleware

My typical path is something like

/user/{user_id}/resource/{resource_id}

I have a validation method, already written in async python, like this:

async def is_allowed(user_id: int, resource_id: int) -> bool

That returns a boolean: true if the user can access the resource, false otherwise.

I want to write a middleware that calls is_allowed extracting the variables from the path.

I fiddled around but I can't find how to get them: I was expecting to get this information from request.path_params.

A somehow more complete example (edited following @Marcelo Trylesinski answer):

import logging

from fastapi import FastAPI
from starlette.requests import Request
from starlette.responses import Response

app = FastAPI()

_logger = logging.getLogger()
_logger.setLevel(logging.DEBUG)


async def is_allowed(user_id, resource_id):
    _logger.error(user_id)
    _logger.error(resource_id)
    return True


@app.middleware('http')
async def acl(request: Request, call_next):
    user_id = request.path_params.get("user_id", None)
    resource_id = request.path_params.get("resource_id", None)
    allowed = await is_allowed(user_id, resource_id)
    if not allowed:
        return Response(status_code=403)
    else:
        return await call_next(request)


@app.get('/user/{user_id}/resource/{resource_id}')
async def my_handler(user_id: int, resource_id: int):
    return {"what": f"Doing stuff with {user_id} on {resource_id}"}

The logged values are None.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You will not be able to achieve your goal with a Middleware, because Middlewares are executed before the routing.

Therefore FastAPI/Starlette doesn't know which path it will match to and cannot populate path_params.

You will have to use a different solution, such as passing these params on a cookie, header or query arg, or using a decorator/Dependency.

Reference:

https://github.com/encode/starlette/issues/230

https://fastapi.tiangolo.com/tutorial/middleware/#middleware

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