Access route path parameters in middleware #4028
-
Hey all! I've recently started using the new(ish) middleware that can be used both globally and on a route. So far its been fantastic! Really enjoy how yall have designed it. One thing that Im not sure is covered is being able to pull out path params in the middleware. In my use case we are trying to authorize a user to act on a resource specified via path, for example with the route: We want to pull out the document_id, and validate that the current user does in fact have delete permissions on it. Id love to build this as a middleware, rather than copying it onto every method that needs this functionality. If we pass it as a query string we can use Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
Hey @Sheemap! 🚀 Thanks a ton for the fantastic feedback on this feature! Middleware is proving to be a great feature, streamlining processes, and simplifying complexities for our customers. If you have a route defined as codefrom aws_lambda_powertools import Logger
from aws_lambda_powertools.event_handler import APIGatewayRestResolver, Response
from aws_lambda_powertools.event_handler.middlewares import NextMiddleware
app = APIGatewayRestResolver()
logger = Logger()
def inject_correlation_id(app: APIGatewayRestResolver, next_middleware: NextMiddleware) -> Response:
print(app.current_event.path_parameters)
@app.get("/v1/documents/<document_id>", middlewares=[inject_correlation_id])
def get_todos(document_id: int):
return document_id
@logger.inject_lambda_context(correlation_id_path='headers."x-correlation-id"')
def lambda_handler(event, context):
return app.resolve(event, context) outputSTART RequestId: 679e1f01-db51-4b3d-b405-64c805e1a146 Version: $LATEST
{'document_id': '1223434556'}
END RequestId: 679e1f01-db51-4b3d-b405-64c805e1a146
REPORT RequestId: 679e1f01-db51-4b3d-b405-64c805e1a146 Init Duration: 0.17 ms Duration: 304.89 ms Billed Duration: 305 ms Memory Size: 128 MB Max Memory Used: 128 MB
2024-03-27 19:17:58 127.0.0.1 - - [27/Mar/2024 19:17:58] "GET /v1/documents/1223434556 HTTP/1.1" 200 - Please let me know if I can assist you further in resolving the issue. |
Beta Was this translation helpful? Give feedback.
If you are using Proxy then your
path_parameters
will be the full path and it is difficult to extract information, I agree.If this is blocking you and is a critical requirement for your system, there is an alternative method to obtain this information more easily. However, it's worth noting that this approach is not considered best practice and may be subject to internal changes in the code with potential breaking changes.
We need to inject the route arguments in the context because we need to use it when invoking
next_middleware
or the next route, so, you can access the route path parameters by using_route_args
variable._route_args = {'_route': <aws_lambda_powertools.event_handler.api…