Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(event-handler): new resolvers to fix current_event typing #978

Merged
merged 21 commits into from
Feb 3, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
227a913
fix(event-handler): API Gateway current_event doesn't show all proper…
michaelbrewer Jan 26, 2022
17e894f
Merge branch 'awslabs:develop' into fix-event-handler
michaelbrewer Jan 26, 2022
e40e7a8
Merge branch 'awslabs:develop' into fix-event-handler
michaelbrewer Jan 29, 2022
0e741b1
Merge branch 'awslabs:develop' into fix-event-handler
michaelbrewer Jan 31, 2022
9994dd3
Merge branch 'awslabs:develop' into fix-event-handler
michaelbrewer Jan 31, 2022
fbd4fd2
chore: remove redundant docs
michaelbrewer Feb 1, 2022
4dcb441
chore: remove redundant docs
michaelbrewer Feb 1, 2022
0ee3903
chore: remove redundant docs
michaelbrewer Feb 1, 2022
6e2ceef
chore: remove redundant docs
michaelbrewer Feb 1, 2022
e9706ce
chore: remove redundant docs
michaelbrewer Feb 1, 2022
76e7e28
chore: remove redundant docs
michaelbrewer Feb 1, 2022
a633991
fix: correct tests
michaelbrewer Feb 1, 2022
ac8255f
docs: docstrings to signal v1/v2
heitorlessa Feb 2, 2022
cda0d7c
Merge branch 'awslabs:develop' into fix-event-handler
michaelbrewer Feb 2, 2022
543c1bb
docs(event_handler): Rename ApiGatewayResolver to APIGatewayRestResolver
michaelbrewer Feb 2, 2022
9688282
docs: remove duplicate tutorial file
heitorlessa Feb 3, 2022
962df46
Merge branch 'fix-event-handler' of https://github.com/gyft/aws-lambd…
heitorlessa Feb 3, 2022
b66b732
docs: improve intro on REST/HTTP
heitorlessa Feb 3, 2022
d1a8636
docs: fix key features typo
heitorlessa Feb 3, 2022
0265a18
docs: improv nav, wording, and add ApiGatewayResolver FAQ
heitorlessa Feb 3, 2022
d9b2869
docs: add wording on HTTP API v1/v2 payload
heitorlessa Feb 3, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 81 additions & 0 deletions aws_lambda_powertools/event_handler/api_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -731,3 +731,84 @@ def register_route(func: Callable):
self._routes[(rule, methods, cors, compress, cache_control)] = func

return register_route


class APIGatewayProxyEventResolver(ApiGatewayResolver):
michaelbrewer marked this conversation as resolved.
Show resolved Hide resolved
current_event: APIGatewayProxyEvent

def __init__(
self,
cors: Optional[CORSConfig] = None,
debug: Optional[bool] = None,
serializer: Optional[Callable[[Dict], str]] = None,
strip_prefixes: Optional[List[str]] = None,
):
"""
Parameters
----------
cors: CORSConfig
Optionally configure and enabled CORS. Not each route will need to have to cors=True
debug: Optional[bool]
Enables debug mode, by default False. Can be also be enabled by "POWERTOOLS_EVENT_HANDLER_DEBUG"
environment variable
serializer : Callable, optional
function to serialize `obj` to a JSON formatted `str`, by default json.dumps
strip_prefixes: List[str], optional
list of prefixes to be removed from the request path before doing the routing. This is often used
with api gateways with multiple custom mappings.
"""
michaelbrewer marked this conversation as resolved.
Show resolved Hide resolved
super().__init__(ProxyEventType.APIGatewayProxyEvent, cors, debug, serializer, strip_prefixes)


class APIGatewayProxyEventV2Resolver(ApiGatewayResolver):
michaelbrewer marked this conversation as resolved.
Show resolved Hide resolved
current_event: APIGatewayProxyEventV2

def __init__(
self,
cors: Optional[CORSConfig] = None,
debug: Optional[bool] = None,
serializer: Optional[Callable[[Dict], str]] = None,
strip_prefixes: Optional[List[str]] = None,
):
"""
Parameters
----------
cors: CORSConfig
Optionally configure and enabled CORS. Not each route will need to have to cors=True
debug: Optional[bool]
Enables debug mode, by default False. Can be also be enabled by "POWERTOOLS_EVENT_HANDLER_DEBUG"
environment variable
serializer : Callable, optional
function to serialize `obj` to a JSON formatted `str`, by default json.dumps
strip_prefixes: List[str], optional
list of prefixes to be removed from the request path before doing the routing. This is often used
with api gateways with multiple custom mappings.
"""
michaelbrewer marked this conversation as resolved.
Show resolved Hide resolved
super().__init__(ProxyEventType.APIGatewayProxyEventV2, cors, debug, serializer, strip_prefixes)


class ALBEventResolver(ApiGatewayResolver):
michaelbrewer marked this conversation as resolved.
Show resolved Hide resolved
current_event: ALBEvent

def __init__(
self,
cors: Optional[CORSConfig] = None,
debug: Optional[bool] = None,
serializer: Optional[Callable[[Dict], str]] = None,
strip_prefixes: Optional[List[str]] = None,
):
"""
Parameters
----------
cors: CORSConfig
Optionally configure and enabled CORS. Not each route will need to have to cors=True
debug: Optional[bool]
Enables debug mode, by default False. Can be also be enabled by "POWERTOOLS_EVENT_HANDLER_DEBUG"
environment variable
serializer : Callable, optional
function to serialize `obj` to a JSON formatted `str`, by default json.dumps
strip_prefixes: List[str], optional
list of prefixes to be removed from the request path before doing the routing. This is often used
with api gateways with multiple custom mappings.
"""
michaelbrewer marked this conversation as resolved.
Show resolved Hide resolved
super().__init__(ProxyEventType.ALBEvent, cors, debug, serializer, strip_prefixes)
14 changes: 10 additions & 4 deletions tests/functional/event_handler/test_api_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@

from aws_lambda_powertools.event_handler import content_types
from aws_lambda_powertools.event_handler.api_gateway import (
ALBEventResolver,
APIGatewayProxyEventResolver,
APIGatewayProxyEventV2Resolver,
ApiGatewayResolver,
CORSConfig,
ProxyEventType,
Expand Down Expand Up @@ -47,13 +50,14 @@ def read_media(file_name: str) -> bytes:


def test_alb_event():
# GIVEN a Application Load Balancer proxy type event
app = ApiGatewayResolver(proxy_type=ProxyEventType.ALBEvent)
# GIVEN an Application Load Balancer proxy type event
app = ALBEventResolver()

@app.get("/lambda")
def foo():
assert isinstance(app.current_event, ALBEvent)
assert app.lambda_context == {}
assert app.current_event.request_context.elb_target_group_arn is not None
return Response(200, content_types.TEXT_HTML, "foo")

# WHEN calling the event handler
Expand All @@ -68,12 +72,13 @@ def foo():

def test_api_gateway_v1():
# GIVEN a Http API V1 proxy type event
app = ApiGatewayResolver(proxy_type=ProxyEventType.APIGatewayProxyEvent)
app = APIGatewayProxyEventResolver()

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

# WHEN calling the event handler
Expand Down Expand Up @@ -106,12 +111,13 @@ def get_lambda() -> Response:

def test_api_gateway_v2():
# GIVEN a Http API V2 proxy type event
app = ApiGatewayResolver(proxy_type=ProxyEventType.APIGatewayProxyEventV2)
app = APIGatewayProxyEventV2Resolver()

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

# WHEN calling the event handler
Expand Down