diff --git a/aws_lambda_powertools/event_handler/api_gateway.py b/aws_lambda_powertools/event_handler/api_gateway.py index ec9b6b0011c..6cf8aad6449 100644 --- a/aws_lambda_powertools/event_handler/api_gateway.py +++ b/aws_lambda_powertools/event_handler/api_gateway.py @@ -3202,7 +3202,12 @@ def include_router(self, router: Router, prefix: str | None = None) -> None: if prefix: rule = route[0] - rule = prefix if rule == "/" else f"{prefix}{rule}" + if rule == "/": + rule = prefix + elif rule.startswith("/"): + rule = f"{prefix.rstrip('/')}{rule}" + else: + rule = f"{prefix}{rule}" new_route = (rule, *route[1:]) # Middlewares are stored by route separately - must grab them to include diff --git a/tests/functional/event_handler/required_dependencies/test_api_gateway.py b/tests/functional/event_handler/required_dependencies/test_api_gateway.py index 8c72ed839ae..86f7bb9c50e 100644 --- a/tests/functional/event_handler/required_dependencies/test_api_gateway.py +++ b/tests/functional/event_handler/required_dependencies/test_api_gateway.py @@ -1766,6 +1766,24 @@ def foo(): assert result["multiValueHeaders"]["Content-Type"] == [content_types.APPLICATION_JSON] +def test_api_gateway_app_router_with_prefix_trailing_slash(): + # GIVEN a Router with a route starting with "/" + # AND a prefix ending with "/" + app = ApiGatewayResolver() + router = Router() + + @router.get(rule="/path") + def foo(): + return {} + + app.include_router(router, prefix="/my/") + # WHEN calling the event handler for "/my/path" + result = app(LOAD_GW_EVENT, {}) + + # THEN the route matches instead of being registered as "/my//path" + assert result["statusCode"] == 200 + + def test_api_gateway_app_router_with_prefix_equals_path(): # GIVEN a Router with registered routes # AND a prefix is defined during the registration