Skip to content

Commit cc364b0

Browse files
author
Michael Brewer
committed
docs: add missing docs
1 parent 223e36c commit cc364b0

File tree

3 files changed

+134
-93
lines changed

3 files changed

+134
-93
lines changed

aws_lambda_powertools/utilities/data_classes/api_gateway_authorizer_event.py

+87-86
Original file line numberDiff line numberDiff line change
@@ -61,63 +61,78 @@ def parse_api_gateway_arn(arn: str) -> APIGatewayRouteArn:
6161
)
6262

6363

64-
class APIGatewayAuthorizerV2Event(DictWrapper):
65-
"""API Gateway Authorizer Event Format 2.0
64+
class APIGatewayAuthorizerTokenEvent(DictWrapper):
65+
"""API Gateway Authorizer Token Event Format 1.0
66+
67+
Documentation:
68+
-------------
69+
- https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html
70+
"""
71+
72+
@property
73+
def get_type(self) -> str:
74+
return self["type"]
75+
76+
@property
77+
def authorization_token(self) -> str:
78+
return self["authorizationToken"]
79+
80+
@property
81+
def method_arn(self) -> str:
82+
"""ARN of the incoming method request and is populated by API Gateway in accordance with the Lambda authorizer
83+
configuration"""
84+
return self["methodArn"]
85+
86+
@property
87+
def parsed_arn(self) -> APIGatewayRouteArn:
88+
"""Convenient property to return a parsed api gateway method arn"""
89+
return parse_api_gateway_arn(self.method_arn)
90+
91+
92+
class APIGatewayAuthorizerRequestEvent(DictWrapper):
93+
"""API Gateway Authorizer Request Event Format 1.0
6694
6795
Documentation:
6896
-------------
97+
- https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html
6998
- https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-lambda-authorizer.html
7099
"""
71100

72101
@property
73102
def version(self) -> str:
74-
"""Event payload version should always be 2.0"""
75103
return self["version"]
76104

77105
@property
78106
def get_type(self) -> str:
79-
"""Event type should always be request"""
80107
return self["type"]
81108

82109
@property
83-
def route_arn(self) -> str:
84-
"""ARN of the route being called
85-
86-
eg: arn:aws:execute-api:us-east-1:123456789012:abcdef123/test/GET/request"""
87-
return self["routeArn"]
110+
def method_arn(self) -> str:
111+
return self["methodArn"]
88112

89113
@property
90114
def parsed_arn(self) -> APIGatewayRouteArn:
91-
"""Convenient property to return a parsed api gateway route arn"""
92-
return parse_api_gateway_arn(self.route_arn)
115+
return parse_api_gateway_arn(self.method_arn)
93116

94117
@property
95-
def identity_source(self) -> Optional[List[str]]:
96-
"""The identity source for which authorization is requested.
97-
98-
For a REQUEST authorizer, this is optional. The value is a set of one or more mapping expressions of the
99-
specified request parameters. The identity source can be headers, query string parameters, stage variables,
100-
and context parameters.
101-
"""
102-
return self.get("identitySource")
118+
def identity_source(self) -> str:
119+
return self["identitySource"]
103120

104121
@property
105-
def route_key(self) -> str:
106-
"""The route key for the route. For HTTP APIs, the route key can be either $default,
107-
or a combination of an HTTP method and resource path, for example, GET /pets."""
108-
return self["routeKey"]
122+
def authorization_token(self) -> str:
123+
return self["authorizationToken"]
109124

110125
@property
111-
def raw_path(self) -> str:
112-
return self["rawPath"]
126+
def resource(self) -> str:
127+
return self["resource"]
113128

114129
@property
115-
def raw_query_string(self) -> str:
116-
return self["rawQueryString"]
130+
def path(self) -> str:
131+
return self["path"]
117132

118133
@property
119-
def cookies(self) -> List[str]:
120-
return self["cookies"]
134+
def http_method(self) -> str:
135+
return self["httpMethod"]
121136

122137
@property
123138
def headers(self) -> Dict[str, str]:
@@ -128,16 +143,16 @@ def query_string_parameters(self) -> Dict[str, str]:
128143
return self["queryStringParameters"]
129144

130145
@property
131-
def request_context(self) -> BaseRequestContextV2:
132-
return BaseRequestContextV2(self._data)
146+
def path_parameters(self) -> Dict[str, str]:
147+
return self["pathParameters"]
133148

134149
@property
135-
def path_parameters(self) -> Optional[Dict[str, str]]:
136-
return self.get("pathParameters")
150+
def stage_variables(self) -> Dict[str, str]:
151+
return self["stageVariables"]
137152

138153
@property
139-
def stage_variables(self) -> Optional[Dict[str, str]]:
140-
return self.get("stageVariables")
154+
def request_context(self) -> BaseRequestContext:
155+
return BaseRequestContext(self._data)
141156

142157
def get_header_value(
143158
self, name: str, default_value: Optional[str] = None, case_sensitive: Optional[bool] = False
@@ -160,78 +175,64 @@ def get_header_value(
160175
return get_header_value(self.headers, name, default_value, case_sensitive)
161176

162177

163-
class APIGatewayAuthorizerTokenEvent(DictWrapper):
164-
"""API Gateway Authorizer Token Event Format 1.0
165-
166-
Documentation:
167-
-------------
168-
- https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html
169-
"""
170-
171-
@property
172-
def get_type(self) -> str:
173-
return self["type"]
174-
175-
@property
176-
def authorization_token(self) -> str:
177-
return self["authorizationToken"]
178-
179-
@property
180-
def method_arn(self) -> str:
181-
"""ARN of the incoming method request and is populated by API Gateway in accordance with the Lambda authorizer
182-
configuration"""
183-
return self["methodArn"]
184-
185-
@property
186-
def parsed_arn(self) -> APIGatewayRouteArn:
187-
"""Convenient property to return a parsed api gateway method arn"""
188-
return parse_api_gateway_arn(self.method_arn)
189-
190-
191-
class APIGatewayAuthorizerRequestEvent(DictWrapper):
192-
"""API Gateway Authorizer Request Event Format 1.0
178+
class APIGatewayAuthorizerEventV2(DictWrapper):
179+
"""API Gateway Authorizer Event Format 2.0
193180
194181
Documentation:
195182
-------------
196-
- https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html
197183
- https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-lambda-authorizer.html
184+
- https://aws.amazon.com/blogs/compute/introducing-iam-and-lambda-authorizers-for-amazon-api-gateway-http-apis/
198185
"""
199186

200187
@property
201188
def version(self) -> str:
189+
"""Event payload version should always be 2.0"""
202190
return self["version"]
203191

204192
@property
205193
def get_type(self) -> str:
194+
"""Event type should always be request"""
206195
return self["type"]
207196

208197
@property
209-
def method_arn(self) -> str:
210-
return self["methodArn"]
198+
def route_arn(self) -> str:
199+
"""ARN of the route being called
200+
201+
eg: arn:aws:execute-api:us-east-1:123456789012:abcdef123/test/GET/request"""
202+
return self["routeArn"]
211203

212204
@property
213205
def parsed_arn(self) -> APIGatewayRouteArn:
214-
return parse_api_gateway_arn(self.method_arn)
206+
"""Convenient property to return a parsed api gateway route arn"""
207+
return parse_api_gateway_arn(self.route_arn)
215208

216209
@property
217-
def identity_source(self) -> str:
218-
return self["identitySource"]
210+
def identity_source(self) -> Optional[List[str]]:
211+
"""The identity source for which authorization is requested.
212+
213+
For a REQUEST authorizer, this is optional. The value is a set of one or more mapping expressions of the
214+
specified request parameters. The identity source can be headers, query string parameters, stage variables,
215+
and context parameters.
216+
"""
217+
return self.get("identitySource")
219218

220219
@property
221-
def authorization_token(self) -> str:
222-
return self["authorizationToken"]
220+
def route_key(self) -> str:
221+
"""The route key for the route. For HTTP APIs, the route key can be either $default,
222+
or a combination of an HTTP method and resource path, for example, GET /pets."""
223+
return self["routeKey"]
223224

224225
@property
225-
def resource(self) -> str:
226-
return self["resource"]
226+
def raw_path(self) -> str:
227+
return self["rawPath"]
227228

228229
@property
229-
def path(self) -> str:
230-
return self["path"]
230+
def raw_query_string(self) -> str:
231+
return self["rawQueryString"]
231232

232233
@property
233-
def http_method(self) -> str:
234-
return self["httpMethod"]
234+
def cookies(self) -> List[str]:
235+
return self["cookies"]
235236

236237
@property
237238
def headers(self) -> Dict[str, str]:
@@ -242,16 +243,16 @@ def query_string_parameters(self) -> Dict[str, str]:
242243
return self["queryStringParameters"]
243244

244245
@property
245-
def path_parameters(self) -> Dict[str, str]:
246-
return self["pathParameters"]
246+
def request_context(self) -> BaseRequestContextV2:
247+
return BaseRequestContextV2(self._data)
247248

248249
@property
249-
def stage_variables(self) -> Dict[str, str]:
250-
return self["stageVariables"]
250+
def path_parameters(self) -> Optional[Dict[str, str]]:
251+
return self.get("pathParameters")
251252

252253
@property
253-
def request_context(self) -> BaseRequestContext:
254-
return BaseRequestContext(self._data)
254+
def stage_variables(self) -> Optional[Dict[str, str]]:
255+
return self.get("stageVariables")
255256

256257
def get_header_value(
257258
self, name: str, default_value: Optional[str] = None, case_sensitive: Optional[bool] = False
@@ -274,7 +275,7 @@ def get_header_value(
274275
return get_header_value(self.headers, name, default_value, case_sensitive)
275276

276277

277-
class APIGatewayAuthorizerV2Response:
278+
class APIGatewayAuthorizerResponseV2:
278279
"""Api Gateway HTTP API V2 payload authorizer simple response helper
279280
280281
Parameters

docs/utilities/data_classes.md

+41-1
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,12 @@ Same example as above, but using the `event_source` decorator
5959

6060
Event Source | Data_class
6161
------------------------------------------------- | ---------------------------------------------------------------------------------
62+
[API Gateway Authorizer V2](#api-gateway-authorizer-v2) | `APIGatewayAuthorizerEventV2`
6263
[API Gateway Proxy](#api-gateway-proxy) | `APIGatewayProxyEvent`
6364
[API Gateway Proxy V2](#api-gateway-proxy-v2) | `APIGatewayProxyEventV2`
6465
[Application Load Balancer](#application-load-balancer) | `ALBEvent`
65-
[AppSync Resolver](#appsync-resolver) | `AppSyncResolverEvent`
6666
[AppSync Authorizer](#appsync-authorizer) | `AppSyncAuthorizerEvent`
67+
[AppSync Resolver](#appsync-resolver) | `AppSyncResolverEvent`
6768
[CloudWatch Logs](#cloudwatch-logs) | `CloudWatchLogsEvent`
6869
[CodePipeline Job Event](#codepipeline-job) | `CodePipelineJobEvent`
6970
[Cognito User Pool](#cognito-user-pool) | Multiple available under `cognito_user_pool_event`
@@ -81,6 +82,45 @@ Event Source | Data_class
8182
The examples provided below are far from exhaustive - the data classes themselves are designed to provide a form of
8283
documentation inherently (via autocompletion, types and docstrings).
8384

85+
### API Gateway Authorizer V2
86+
87+
> New in 1.20.0
88+
89+
It is used for API Gateway HTTP API lambda authorizer payload version 2. See blog post
90+
[Introducing IAM and Lambda authorizers for Amazon API Gateway HTTP APIs](https://aws.amazon.com/blogs/compute/introducing-iam-and-lambda-authorizers-for-amazon-api-gateway-http-apis/){target="_blank"}
91+
or [Working with AWS Lambda authorizers for HTTP APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-lambda-authorizer.html){target="_blank"}
92+
for more details
93+
94+
Below is a simple example of an HTTP API lambda authorizer looking up user details by `x-token` header and using
95+
`APIGatewayAuthorizerResponseV2` to return the declined response when user is not found or authorized and include
96+
the user details in the request context.
97+
98+
=== "app.py"
99+
100+
```python
101+
from aws_lambda_powertools.utilities.data_classes import event_source
102+
from aws_lambda_powertools.utilities.data_classes.api_gateway_authorizer_event import (
103+
APIGatewayAuthorizerEventV2,
104+
APIGatewayAuthorizerResponseV2,
105+
)
106+
107+
108+
def get_user_by_token(token):
109+
...
110+
111+
112+
@event_source(data_class=APIGatewayAuthorizerEventV2)
113+
def handler(event: APIGatewayAuthorizerEventV2, context):
114+
user = get_user_by_token(event.get_header_value("x-token"))
115+
116+
if user is None:
117+
# No user was found, so we return not authorized
118+
return APIGatewayAuthorizerResponseV2().asdict()
119+
120+
# Found the user and setting the details in the context
121+
return APIGatewayAuthorizerResponseV2(authorize=True, context=user).asdict()
122+
```
123+
84124
### API Gateway Proxy
85125

86126
It is used for either API Gateway REST API or HTTP API using v1 proxy event.

tests/functional/test_data_classes.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,10 @@
2323
SQSEvent,
2424
)
2525
from aws_lambda_powertools.utilities.data_classes.api_gateway_authorizer_event import (
26+
APIGatewayAuthorizerEventV2,
2627
APIGatewayAuthorizerRequestEvent,
28+
APIGatewayAuthorizerResponseV2,
2729
APIGatewayAuthorizerTokenEvent,
28-
APIGatewayAuthorizerV2Event,
29-
APIGatewayAuthorizerV2Response,
3030
parse_api_gateway_arn,
3131
)
3232
from aws_lambda_powertools.utilities.data_classes.appsync.scalar_types_utils import (
@@ -1469,7 +1469,7 @@ def test_appsync_authorizer_response():
14691469

14701470
def test_api_gateway_authorizer_v2():
14711471
"""Check api gateway authorize event format v2.0"""
1472-
event = APIGatewayAuthorizerV2Event(load_event("apiGatewayAuthorizerV2Event.json"))
1472+
event = APIGatewayAuthorizerEventV2(load_event("apiGatewayAuthorizerV2Event.json"))
14731473

14741474
assert event["version"] == event.version
14751475
assert event["version"] == "2.0"
@@ -1513,7 +1513,7 @@ def test_api_gateway_authorizer_v2():
15131513
assert event.get_header_value("missing") is None
15141514

15151515
# Check for optionals
1516-
event_optionals = APIGatewayAuthorizerV2Event({"requestContext": {}})
1516+
event_optionals = APIGatewayAuthorizerEventV2({"requestContext": {}})
15171517
assert event_optionals.identity_source is None
15181518
assert event_optionals.request_context.authentication is None
15191519
assert event_optionals.path_parameters is None
@@ -1588,9 +1588,9 @@ def test_api_gateway_authorizer_request_event():
15881588

15891589
def test_api_gateway_authorizer_simple_response():
15901590
"""Check building API Gateway authorizer simple resource"""
1591-
assert {"isAuthorized": False} == APIGatewayAuthorizerV2Response().asdict()
1591+
assert {"isAuthorized": False} == APIGatewayAuthorizerResponseV2().asdict()
15921592
expected_context = {"foo": "value"}
1593-
assert {"isAuthorized": True, "context": expected_context} == APIGatewayAuthorizerV2Response(
1593+
assert {"isAuthorized": True, "context": expected_context} == APIGatewayAuthorizerResponseV2(
15941594
authorize=True,
15951595
context=expected_context,
15961596
).asdict()

0 commit comments

Comments
 (0)