Skip to content

Commit 227a913

Browse files
committed
fix(event-handler): API Gateway current_event doesn't show all properties
Add new specialized resolvers APIGatewayProxyEventResolver, APIGatewayProxyEventV2Resolver and ALBEventResolver closes aws-powertools#761
1 parent 5c0a14d commit 227a913

File tree

2 files changed

+91
-4
lines changed

2 files changed

+91
-4
lines changed

aws_lambda_powertools/event_handler/api_gateway.py

+81
Original file line numberDiff line numberDiff line change
@@ -735,3 +735,84 @@ def register_route(func: Callable):
735735
self._routes[(rule, methods, cors, compress, cache_control)] = func
736736

737737
return register_route
738+
739+
740+
class APIGatewayProxyEventResolver(ApiGatewayResolver):
741+
current_event: APIGatewayProxyEvent
742+
743+
def __init__(
744+
self,
745+
cors: Optional[CORSConfig] = None,
746+
debug: Optional[bool] = None,
747+
serializer: Optional[Callable[[Dict], str]] = None,
748+
strip_prefixes: Optional[List[str]] = None,
749+
):
750+
"""
751+
Parameters
752+
----------
753+
cors: CORSConfig
754+
Optionally configure and enabled CORS. Not each route will need to have to cors=True
755+
debug: Optional[bool]
756+
Enables debug mode, by default False. Can be also be enabled by "POWERTOOLS_EVENT_HANDLER_DEBUG"
757+
environment variable
758+
serializer : Callable, optional
759+
function to serialize `obj` to a JSON formatted `str`, by default json.dumps
760+
strip_prefixes: List[str], optional
761+
list of prefixes to be removed from the request path before doing the routing. This is often used
762+
with api gateways with multiple custom mappings.
763+
"""
764+
super().__init__(ProxyEventType.APIGatewayProxyEvent, cors, debug, serializer, strip_prefixes)
765+
766+
767+
class APIGatewayProxyEventV2Resolver(ApiGatewayResolver):
768+
current_event: APIGatewayProxyEventV2
769+
770+
def __init__(
771+
self,
772+
cors: Optional[CORSConfig] = None,
773+
debug: Optional[bool] = None,
774+
serializer: Optional[Callable[[Dict], str]] = None,
775+
strip_prefixes: Optional[List[str]] = None,
776+
):
777+
"""
778+
Parameters
779+
----------
780+
cors: CORSConfig
781+
Optionally configure and enabled CORS. Not each route will need to have to cors=True
782+
debug: Optional[bool]
783+
Enables debug mode, by default False. Can be also be enabled by "POWERTOOLS_EVENT_HANDLER_DEBUG"
784+
environment variable
785+
serializer : Callable, optional
786+
function to serialize `obj` to a JSON formatted `str`, by default json.dumps
787+
strip_prefixes: List[str], optional
788+
list of prefixes to be removed from the request path before doing the routing. This is often used
789+
with api gateways with multiple custom mappings.
790+
"""
791+
super().__init__(ProxyEventType.APIGatewayProxyEventV2, cors, debug, serializer, strip_prefixes)
792+
793+
794+
class ALBEventResolver(ApiGatewayResolver):
795+
current_event: ALBEvent
796+
797+
def __init__(
798+
self,
799+
cors: Optional[CORSConfig] = None,
800+
debug: Optional[bool] = None,
801+
serializer: Optional[Callable[[Dict], str]] = None,
802+
strip_prefixes: Optional[List[str]] = None,
803+
):
804+
"""
805+
Parameters
806+
----------
807+
cors: CORSConfig
808+
Optionally configure and enabled CORS. Not each route will need to have to cors=True
809+
debug: Optional[bool]
810+
Enables debug mode, by default False. Can be also be enabled by "POWERTOOLS_EVENT_HANDLER_DEBUG"
811+
environment variable
812+
serializer : Callable, optional
813+
function to serialize `obj` to a JSON formatted `str`, by default json.dumps
814+
strip_prefixes: List[str], optional
815+
list of prefixes to be removed from the request path before doing the routing. This is often used
816+
with api gateways with multiple custom mappings.
817+
"""
818+
super().__init__(ProxyEventType.ALBEvent, cors, debug, serializer, strip_prefixes)

tests/functional/event_handler/test_api_gateway.py

+10-4
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212

1313
from aws_lambda_powertools.event_handler import content_types
1414
from aws_lambda_powertools.event_handler.api_gateway import (
15+
ALBEventResolver,
16+
APIGatewayProxyEventResolver,
17+
APIGatewayProxyEventV2Resolver,
1518
ApiGatewayResolver,
1619
CORSConfig,
1720
ProxyEventType,
@@ -41,13 +44,14 @@ def read_media(file_name: str) -> bytes:
4144

4245

4346
def test_alb_event():
44-
# GIVEN a Application Load Balancer proxy type event
45-
app = ApiGatewayResolver(proxy_type=ProxyEventType.ALBEvent)
47+
# GIVEN an Application Load Balancer proxy type event
48+
app = ALBEventResolver()
4649

4750
@app.get("/lambda")
4851
def foo():
4952
assert isinstance(app.current_event, ALBEvent)
5053
assert app.lambda_context == {}
54+
assert app.current_event.request_context.elb_target_group_arn is not None
5155
return Response(200, content_types.TEXT_HTML, "foo")
5256

5357
# WHEN calling the event handler
@@ -62,12 +66,13 @@ def foo():
6266

6367
def test_api_gateway_v1():
6468
# GIVEN a Http API V1 proxy type event
65-
app = ApiGatewayResolver(proxy_type=ProxyEventType.APIGatewayProxyEvent)
69+
app = APIGatewayProxyEventResolver()
6670

6771
@app.get("/my/path")
6872
def get_lambda() -> Response:
6973
assert isinstance(app.current_event, APIGatewayProxyEvent)
7074
assert app.lambda_context == {}
75+
assert app.current_event.request_context.domain_name == "id.execute-api.us-east-1.amazonaws.com"
7176
return Response(200, content_types.APPLICATION_JSON, json.dumps({"foo": "value"}))
7277

7378
# WHEN calling the event handler
@@ -100,12 +105,13 @@ def get_lambda() -> Response:
100105

101106
def test_api_gateway_v2():
102107
# GIVEN a Http API V2 proxy type event
103-
app = ApiGatewayResolver(proxy_type=ProxyEventType.APIGatewayProxyEventV2)
108+
app = APIGatewayProxyEventV2Resolver()
104109

105110
@app.post("/my/path")
106111
def my_path() -> Response:
107112
assert isinstance(app.current_event, APIGatewayProxyEventV2)
108113
post_data = app.current_event.json_body
114+
assert app.current_event.cookies[0] == "cookie1"
109115
return Response(200, content_types.TEXT_PLAIN, post_data["username"])
110116

111117
# WHEN calling the event handler

0 commit comments

Comments
 (0)