-
Notifications
You must be signed in to change notification settings - Fork 406
/
Copy pathapi_gateway.py
2724 lines (2325 loc) · 104 KB
/
api_gateway.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import base64
import json
import logging
import re
import traceback
import warnings
import zlib
from abc import ABC, abstractmethod
from enum import Enum
from functools import partial
from http import HTTPStatus
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Generic, Literal, Mapping, Match, Pattern, Sequence, TypeVar, cast
from typing_extensions import override
from aws_lambda_powertools.event_handler import content_types
from aws_lambda_powertools.event_handler.exceptions import NotFoundError, ServiceError
from aws_lambda_powertools.event_handler.openapi.constants import DEFAULT_API_VERSION, DEFAULT_OPENAPI_VERSION
from aws_lambda_powertools.event_handler.openapi.exceptions import RequestValidationError, SchemaValidationError
from aws_lambda_powertools.event_handler.openapi.types import (
COMPONENT_REF_PREFIX,
METHODS_WITH_BODY,
OpenAPIResponse,
OpenAPIResponseContentModel,
OpenAPIResponseContentSchema,
validation_error_definition,
validation_error_response_definition,
)
from aws_lambda_powertools.event_handler.util import (
_FrozenDict,
_FrozenListDict,
_validate_openapi_security_parameters,
extract_origin_header,
)
from aws_lambda_powertools.shared.cookies import Cookie
from aws_lambda_powertools.shared.functions import powertools_dev_is_set
from aws_lambda_powertools.shared.json_encoder import Encoder
from aws_lambda_powertools.utilities.data_classes import (
ALBEvent,
APIGatewayProxyEvent,
APIGatewayProxyEventV2,
BedrockAgentEvent,
LambdaFunctionUrlEvent,
VPCLatticeEvent,
VPCLatticeEventV2,
)
from aws_lambda_powertools.utilities.data_classes.common import BaseProxyEvent
logger = logging.getLogger(__name__)
_DYNAMIC_ROUTE_PATTERN = r"(<\w+>)"
_SAFE_URI = "-._~()'!*:@,;=+&$" # https://www.ietf.org/rfc/rfc3986.txt
# API GW/ALB decode non-safe URI chars; we must support them too
_UNSAFE_URI = r"%<> \[\]{}|^"
_NAMED_GROUP_BOUNDARY_PATTERN = rf"(?P\1[{_SAFE_URI}{_UNSAFE_URI}\\w]+)"
_DEFAULT_OPENAPI_RESPONSE_DESCRIPTION = "Successful Response"
_ROUTE_REGEX = "^{}$"
ResponseEventT = TypeVar("ResponseEventT", bound=BaseProxyEvent)
ResponseT = TypeVar("ResponseT")
if TYPE_CHECKING:
from aws_lambda_powertools.event_handler.openapi.compat import (
JsonSchemaValue,
ModelField,
)
from aws_lambda_powertools.event_handler.openapi.models import (
Contact,
License,
OpenAPI,
SecurityScheme,
Server,
Tag,
)
from aws_lambda_powertools.event_handler.openapi.params import Dependant
from aws_lambda_powertools.event_handler.openapi.swagger_ui.oauth2 import (
OAuth2Config,
)
from aws_lambda_powertools.event_handler.openapi.types import (
TypeModelOrEnum,
)
from aws_lambda_powertools.shared.cookies import Cookie
from aws_lambda_powertools.shared.types import AnyCallableT
from aws_lambda_powertools.utilities.typing import LambdaContext
class ProxyEventType(Enum):
"""An enumerations of the supported proxy event types."""
APIGatewayProxyEvent = "APIGatewayProxyEvent"
APIGatewayProxyEventV2 = "APIGatewayProxyEventV2"
ALBEvent = "ALBEvent"
BedrockAgentEvent = "BedrockAgentEvent"
VPCLatticeEvent = "VPCLatticeEvent"
VPCLatticeEventV2 = "VPCLatticeEventV2"
LambdaFunctionUrlEvent = "LambdaFunctionUrlEvent"
class CORSConfig:
"""CORS Config
Examples
--------
Simple CORS example using the default permissive CORS, note that this should only be used during early prototyping.
```python
from aws_lambda_powertools.event_handler.api_gateway import (
APIGatewayRestResolver, CORSConfig
)
app = APIGatewayRestResolver(cors=CORSConfig())
@app.get("/my/path")
def with_cors():
return {"message": "Foo"}
```
Using a custom CORSConfig where `with_cors` used the custom provided CORSConfig and `without_cors`
do not include any CORS headers.
```python
from aws_lambda_powertools.event_handler.api_gateway import (
APIGatewayRestResolver, CORSConfig
)
cors_config = CORSConfig(
allow_origin="https://wwww.example.com/",
extra_origins=["https://dev.example.com/"],
expose_headers=["x-exposed-response-header"],
allow_headers=["x-custom-request-header"],
max_age=100,
allow_credentials=True,
)
app = APIGatewayRestResolver(cors=cors_config)
@app.get("/my/path")
def with_cors():
return {"message": "Foo"}
@app.get("/another-one", cors=False)
def without_cors():
return {"message": "Foo"}
```
"""
_REQUIRED_HEADERS = ["Authorization", "Content-Type", "X-Amz-Date", "X-Api-Key", "X-Amz-Security-Token"]
def __init__(
self,
allow_origin: str = "*",
extra_origins: list[str] | None = None,
allow_headers: list[str] | None = None,
expose_headers: list[str] | None = None,
max_age: int | None = None,
allow_credentials: bool = False,
):
"""
Parameters
----------
allow_origin: str
The value of the `Access-Control-Allow-Origin` to send in the response. Defaults to "*", but should
only be used during development.
extra_origins: list[str] | None
The list of additional allowed origins.
allow_headers: list[str] | None
The list of additional allowed headers. This list is added to list of
built-in allowed headers: `Authorization`, `Content-Type`, `X-Amz-Date`,
`X-Api-Key`, `X-Amz-Security-Token`.
expose_headers: list[str] | None
A list of values to return for the Access-Control-Expose-Headers
max_age: int | None
The value for the `Access-Control-Max-Age`
allow_credentials: bool
A boolean value that sets the value of `Access-Control-Allow-Credentials`
"""
self._allowed_origins = [allow_origin]
if extra_origins:
self._allowed_origins.extend(extra_origins)
self.allow_headers = set(self._REQUIRED_HEADERS + (allow_headers or []))
self.expose_headers = expose_headers or []
self.max_age = max_age
self.allow_credentials = allow_credentials
def to_dict(self, origin: str | None) -> dict[str, str]:
"""Builds the configured Access-Control http headers"""
# If there's no Origin, don't add any CORS headers
if not origin:
return {}
# If the origin doesn't match any of the allowed origins, and we don't allow all origins ("*"),
# don't add any CORS headers
if origin not in self._allowed_origins and "*" not in self._allowed_origins:
return {}
# The origin matched an allowed origin, so return the CORS headers
headers = {
"Access-Control-Allow-Origin": origin,
"Access-Control-Allow-Headers": CORSConfig.build_allow_methods(self.allow_headers),
}
if self.expose_headers:
headers["Access-Control-Expose-Headers"] = ",".join(self.expose_headers)
if self.max_age is not None:
headers["Access-Control-Max-Age"] = str(self.max_age)
if origin != "*" and self.allow_credentials is True:
headers["Access-Control-Allow-Credentials"] = "true"
return headers
def allowed_origin(self, extracted_origin: str) -> str | None:
if extracted_origin in self._allowed_origins:
return extracted_origin
if extracted_origin is not None and "*" in self._allowed_origins:
return "*"
return None
@staticmethod
def build_allow_methods(methods: set[str]) -> str:
"""Build sorted comma delimited methods for Access-Control-Allow-Methods header
Parameters
----------
methods : set[str]
Set of HTTP Methods
Returns
-------
set[str]
Formatted string with all HTTP Methods allowed for CORS e.g., `GET, OPTIONS`
"""
return ",".join(sorted(methods))
class Response(Generic[ResponseT]):
"""Response data class that provides greater control over what is returned from the proxy event"""
def __init__(
self,
status_code: int,
content_type: str | None = None,
body: ResponseT | None = None,
headers: Mapping[str, str | list[str]] | None = None,
cookies: list[Cookie] | None = None,
compress: bool | None = None,
):
"""
Parameters
----------
status_code: int
Http status code, example 200
content_type: str
Optionally set the Content-Type header, example "application/json". Note this will be merged into any
provided http headers
body: str | bytes | None
Optionally set the response body. Note: bytes body will be automatically base64 encoded
headers: Mapping[str, str | list[str]]
Optionally set specific http headers. Setting "Content-Type" here would override the `content_type` value.
cookies: list[Cookie]
Optionally set cookies.
"""
self.status_code = status_code
self.body = body
self.base64_encoded = False
self.headers: dict[str, str | list[str]] = dict(headers) if headers else {}
self.cookies = cookies or []
self.compress = compress
self.content_type = content_type
if content_type:
self.headers.setdefault("Content-Type", content_type)
def is_json(self) -> bool:
"""
Returns True if the response is JSON, based on the Content-Type.
"""
content_type = self.headers.get("Content-Type", "")
if isinstance(content_type, list):
content_type = content_type[0]
return content_type.startswith("application/json")
class Route:
"""Internally used Route Configuration"""
def __init__(
self,
method: str,
path: str,
rule: Pattern,
func: Callable,
cors: bool,
compress: bool,
cache_control: str | None = None,
summary: str | None = None,
description: str | None = None,
responses: dict[int, OpenAPIResponse] | None = None,
response_description: str | None = None,
tags: list[str] | None = None,
operation_id: str | None = None,
include_in_schema: bool = True,
security: list[dict[str, list[str]]] | None = None,
openapi_extensions: dict[str, Any] | None = None,
deprecated: bool = False,
middlewares: list[Callable[..., Response]] | None = None,
):
"""
Parameters
----------
method: str
The HTTP method, example "GET"
path: str
The path of the route
rule: Pattern
The route rule, example "/my/path"
func: Callable
The route handler function
cors: bool
Whether or not to enable CORS for this route
compress: bool
Whether or not to enable gzip compression for this route
cache_control: str | None
The cache control header value, example "max-age=3600"
summary: str | None
The OpenAPI summary for this route
description: str | None
The OpenAPI description for this route
responses: dict[int, OpenAPIResponse] | None
The OpenAPI responses for this route
response_description: str | None
The OpenAPI response description for this route
tags: list[str] | None
The list of OpenAPI tags to be used for this route
operation_id: str | None
The OpenAPI operationId for this route
include_in_schema: bool
Whether or not to include this route in the OpenAPI schema
security: list[dict[str, list[str]]], optional
The OpenAPI security for this route
openapi_extensions: dict[str, Any], optional
Additional OpenAPI extensions as a dictionary.
deprecated: bool
Whether or not to mark this route as deprecated in the OpenAPI schema
middlewares: list[Callable[..., Response]] | None
The list of route middlewares to be called in order.
"""
self.method = method.upper()
self.path = "/" if path.strip() == "" else path
# OpenAPI spec only understands paths with { }. So we'll have to convert Powertools' < >.
# https://swagger.io/specification/#path-templating
self.openapi_path = re.sub(r"<(.*?)>", lambda m: f"{{{''.join(m.group(1))}}}", self.path)
self.rule = rule
self.func = func
self._middleware_stack = func
self.cors = cors
self.compress = compress
self.cache_control = cache_control
self.summary = summary
self.description = description
self.responses = responses
self.response_description = response_description
self.tags = tags or []
self.include_in_schema = include_in_schema
self.security = security
self.openapi_extensions = openapi_extensions
self.middlewares = middlewares or []
self.operation_id = operation_id or self._generate_operation_id()
self.deprecated = deprecated
# _middleware_stack_built is used to ensure the middleware stack is only built once.
self._middleware_stack_built = False
# _dependant is used to cache the dependant model for the handler function
self._dependant: Dependant | None = None
# _body_field is used to cache the dependant model for the body field
self._body_field: ModelField | None = None
def __call__(
self,
router_middlewares: list[Callable],
app: ApiGatewayResolver,
route_arguments: dict[str, str],
) -> dict | tuple | Response:
"""Calling the Router class instance will trigger the following actions:
1. If Route Middleware stack has not been built, build it
2. Call the Route Middleware stack wrapping the original function
handler with the app and route arguments.
Parameters
----------
router_middlewares: list[Callable]
The list of Router Middlewares (assigned to ALL routes)
app: "ApiGatewayResolver"
The ApiGatewayResolver instance to pass into the middleware stack
route_arguments: dict[str, str]
The route arguments to pass to the app function (extracted from the Api Gateway
Lambda Message structure from AWS)
Returns
-------
dict | tuple | Response
API Response object in ALL cases, except when the original API route
handler is called which may also return a dict, tuple, or Response.
"""
# Save CPU cycles by building middleware stack once
if not self._middleware_stack_built:
self._build_middleware_stack(router_middlewares=router_middlewares)
# If debug is turned on then output the middleware stack to the console
if app._debug:
print(f"\nProcessing Route:::{self.func.__name__} ({app.context['_path']})")
# Collect ALL middleware for debug printing - include internal _registered_api_adapter
all_middlewares = router_middlewares + self.middlewares + [_registered_api_adapter]
print("\nMiddleware Stack:")
print("=================")
print("\n".join(getattr(item, "__name__", "Unknown") for item in all_middlewares))
print("=================")
# Add Route Arguments to app context
app.append_context(_route_args=route_arguments)
# Call the Middleware Wrapped _call_stack function handler with the app
return self._middleware_stack(app)
def _build_middleware_stack(self, router_middlewares: list[Callable[..., Any]]) -> None:
"""
Builds the middleware stack for the handler by wrapping each
handler in an instance of MiddlewareWrapper which is used to contain the state
of each middleware step.
Middleware is represented by a standard Python Callable construct. Any Middleware
handler wanting to short-circuit the middlware call chain can raise an exception
to force the Python call stack created by the handler call-chain to naturally un-wind.
This becomes a simple concept for developers to understand and reason with - no additional
gymanstics other than plain old try ... except.
Notes
-----
The Route Middleware stack is processed in reverse order. This is so the stack of
middleware handlers is applied in the order of being added to the handler.
"""
all_middlewares = router_middlewares + self.middlewares
logger.debug(f"Building middleware stack: {all_middlewares}")
# IMPORTANT:
# this must be the last middleware in the stack (tech debt for backward
# compatibility purposes)
#
# This adapter will:
# 1. Call the registered API passing only the expected route arguments extracted from the path
# and not the middleware.
# 2. Adapt the response type of the route handler (dict | tuple | Response)
# and normalise into a Response object so middleware will always have a constant signature
all_middlewares.append(_registered_api_adapter)
# Wrap the original route handler function in the middleware handlers
# using the MiddlewareWrapper class callable construct in reverse order to
# ensure middleware is applied in the order the user defined.
#
# Start with the route function and wrap from last to the first Middleware handler.
for handler in reversed(all_middlewares):
self._middleware_stack = MiddlewareFrame(current_middleware=handler, next_middleware=self._middleware_stack)
self._middleware_stack_built = True
@property
def dependant(self) -> Dependant:
if self._dependant is None:
from aws_lambda_powertools.event_handler.openapi.dependant import get_dependant
self._dependant = get_dependant(path=self.openapi_path, call=self.func, responses=self.responses)
return self._dependant
@property
def body_field(self) -> ModelField | None:
if self._body_field is None:
from aws_lambda_powertools.event_handler.openapi.dependant import get_body_field
self._body_field = get_body_field(dependant=self.dependant, name=self.operation_id)
return self._body_field
def _get_openapi_path(
self,
*,
dependant: Dependant,
operation_ids: set[str],
model_name_map: dict[TypeModelOrEnum, str],
field_mapping: dict[tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue],
) -> tuple[dict[str, Any], dict[str, Any]]:
"""
Returns the OpenAPI path and definitions for the route.
"""
from aws_lambda_powertools.event_handler.openapi.dependant import get_flat_params
path = {}
definitions: dict[str, Any] = {}
# Gather all the route parameters
operation = self._openapi_operation_metadata(operation_ids=operation_ids)
parameters: list[dict[str, Any]] = []
all_route_params = get_flat_params(dependant)
operation_params = self._openapi_operation_parameters(
all_route_params=all_route_params,
model_name_map=model_name_map,
field_mapping=field_mapping,
)
parameters.extend(operation_params)
# Add security if present
if self.security:
operation["security"] = self.security
# Add OpenAPI extensions if present
if self.openapi_extensions:
operation.update(self.openapi_extensions)
# Add the parameters to the OpenAPI operation
if parameters:
all_parameters = {(param["in"], param["name"]): param for param in parameters}
required_parameters = {(param["in"], param["name"]): param for param in parameters if param.get("required")}
all_parameters.update(required_parameters)
operation["parameters"] = list(all_parameters.values())
# Add the request body to the OpenAPI operation, if applicable
if self.method.upper() in METHODS_WITH_BODY:
request_body_oai = self._openapi_operation_request_body(
body_field=self.body_field,
model_name_map=model_name_map,
field_mapping=field_mapping,
)
if request_body_oai:
operation["requestBody"] = request_body_oai
# Validation failure response (422) will always be part of the schema
operation_responses: dict[int, OpenAPIResponse] = {
422: {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {"$ref": COMPONENT_REF_PREFIX + "HTTPValidationError"},
},
},
},
}
# Add the response to the OpenAPI operation
if self.responses:
for status_code in list(self.responses):
response = self.responses[status_code]
# Case 1: there is not 'content' key
if "content" not in response:
response["content"] = {
"application/json": self._openapi_operation_return(
param=dependant.return_param,
model_name_map=model_name_map,
field_mapping=field_mapping,
),
}
# Case 2: there is a 'content' key
else:
# Need to iterate to transform any 'model' into a 'schema'
for content_type, payload in response["content"].items():
new_payload: OpenAPIResponseContentSchema
# Case 2.1: the 'content' has a model
if "model" in payload:
# Find the model in the dependant's extra models
return_field = next(
filter(
lambda model: model.type_ is cast(OpenAPIResponseContentModel, payload)["model"],
self.dependant.response_extra_models,
),
)
if not return_field:
raise AssertionError("Model declared in custom responses was not found")
new_payload = self._openapi_operation_return(
param=return_field,
model_name_map=model_name_map,
field_mapping=field_mapping,
)
# Case 2.2: the 'content' has a schema
else:
# Do nothing! We already have what we need!
new_payload = payload
response["content"][content_type] = new_payload
# Merge the user provided response with the default responses
operation_responses[status_code] = response
else:
# Set the default 200 response
response_schema = self._openapi_operation_return(
param=dependant.return_param,
model_name_map=model_name_map,
field_mapping=field_mapping,
)
# Add the response schema to the OpenAPI 200 response
operation_responses[200] = {
"description": self.response_description or _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION,
"content": {"application/json": response_schema},
}
operation["responses"] = operation_responses
path[self.method.lower()] = operation
# Add the validation error schema to the definitions, but only if it hasn't been added yet
if "ValidationError" not in definitions:
definitions.update(
{
"ValidationError": validation_error_definition,
"HTTPValidationError": validation_error_response_definition,
},
)
# Generate the response schema
return path, definitions
def _openapi_operation_summary(self) -> str:
"""
Returns the OpenAPI operation summary. If the user has not provided a summary, we
generate one based on the route path and method.
"""
return self.summary or f"{self.method.upper()} {self.openapi_path}"
def _openapi_operation_metadata(self, operation_ids: set[str]) -> dict[str, Any]:
"""
Returns the OpenAPI operation metadata. If the user has not provided a description, we
generate one based on the route path and method.
"""
operation: dict[str, Any] = {}
# Ensure tags is added to the operation
if self.tags:
operation["tags"] = self.tags
# Ensure summary is added to the operation
operation["summary"] = self._openapi_operation_summary()
# Ensure description is added to the operation
if self.description:
operation["description"] = self.description
# Ensure operationId is unique
if self.operation_id in operation_ids:
message = f"Duplicate Operation ID {self.operation_id} for function {self.func.__name__}"
file_name = getattr(self.func, "__globals__", {}).get("__file__")
if file_name:
message += f" in {file_name}"
warnings.warn(message, stacklevel=1)
# Adds the operation
operation_ids.add(self.operation_id)
operation["operationId"] = self.operation_id
# Mark as deprecated if necessary
operation["deprecated"] = self.deprecated or None
return operation
@staticmethod
def _openapi_operation_request_body(
*,
body_field: ModelField | None,
model_name_map: dict[TypeModelOrEnum, str],
field_mapping: dict[tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue],
) -> dict[str, Any] | None:
"""
Returns the OpenAPI operation request body.
"""
from aws_lambda_powertools.event_handler.openapi.compat import ModelField, get_schema_from_model_field
from aws_lambda_powertools.event_handler.openapi.params import Body
# Check that there is a body field and it's a Pydantic's model field
if not body_field:
return None
if not isinstance(body_field, ModelField):
raise AssertionError(f"Expected ModelField, got {body_field}")
# Generate the request body schema
body_schema = get_schema_from_model_field(
field=body_field,
model_name_map=model_name_map,
field_mapping=field_mapping,
)
field_info = cast(Body, body_field.field_info)
request_media_type = field_info.media_type
required = body_field.required
request_body_oai: dict[str, Any] = {}
if required:
request_body_oai["required"] = required
if field_info.description:
request_body_oai["description"] = field_info.description
# Generate the request body media type
request_media_content: dict[str, Any] = {"schema": body_schema}
request_body_oai["content"] = {request_media_type: request_media_content}
return request_body_oai
@staticmethod
def _openapi_operation_parameters(
*,
all_route_params: Sequence[ModelField],
model_name_map: dict[TypeModelOrEnum, str],
field_mapping: dict[tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue],
) -> list[dict[str, Any]]:
"""
Returns the OpenAPI operation parameters.
"""
from aws_lambda_powertools.event_handler.openapi.compat import (
get_schema_from_model_field,
)
from aws_lambda_powertools.event_handler.openapi.params import Param
parameters = []
parameter: dict[str, Any] = {}
for param in all_route_params:
field_info = param.field_info
field_info = cast(Param, field_info)
if not field_info.include_in_schema:
continue
param_schema = get_schema_from_model_field(
field=param,
model_name_map=model_name_map,
field_mapping=field_mapping,
)
parameter = {
"name": param.alias,
"in": field_info.in_.value,
"required": param.required,
"schema": param_schema,
}
if field_info.description:
parameter["description"] = field_info.description
if field_info.deprecated:
parameter["deprecated"] = field_info.deprecated
parameters.append(parameter)
return parameters
@staticmethod
def _openapi_operation_return(
*,
param: ModelField | None,
model_name_map: dict[TypeModelOrEnum, str],
field_mapping: dict[tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue],
) -> OpenAPIResponseContentSchema:
"""
Returns the OpenAPI operation return.
"""
if param is None:
return {}
from aws_lambda_powertools.event_handler.openapi.compat import (
get_schema_from_model_field,
)
return_schema = get_schema_from_model_field(
field=param,
model_name_map=model_name_map,
field_mapping=field_mapping,
)
return {"schema": return_schema}
def _generate_operation_id(self) -> str:
operation_id = self.func.__name__ + self.openapi_path
operation_id = re.sub(r"\W", "_", operation_id)
operation_id = operation_id + "_" + self.method.lower()
return operation_id
class ResponseBuilder(Generic[ResponseEventT]):
"""Internally used Response builder"""
def __init__(
self,
response: Response,
serializer: Callable[[Any], str] = partial(json.dumps, separators=(",", ":"), cls=Encoder),
route: Route | None = None,
):
self.response = response
self.serializer = serializer
self.route = route
def _add_cors(self, event: ResponseEventT, cors: CORSConfig):
"""Update headers to include the configured Access-Control headers"""
extracted_origin_header = extract_origin_header(event.resolved_headers_field)
origin = cors.allowed_origin(extracted_origin_header)
if origin is not None:
self.response.headers.update(cors.to_dict(origin))
def _add_cache_control(self, cache_control: str):
"""Set the specified cache control headers for 200 http responses. For non-200 `no-cache` is used."""
cache_control = cache_control if self.response.status_code == 200 else "no-cache"
self.response.headers["Cache-Control"] = cache_control
@staticmethod
def _has_compression_enabled(
route_compression: bool,
response_compression: bool | None,
event: ResponseEventT,
) -> bool:
"""
Checks if compression is enabled.
NOTE: Response compression takes precedence.
Parameters
----------
route_compression: bool, optional
A boolean indicating whether compression is enabled or not in the route setting.
response_compression: bool, optional
A boolean indicating whether compression is enabled or not in the response setting.
event: ResponseEventT
The event object containing the request details.
Returns
-------
bool
True if compression is enabled and the "gzip" encoding is accepted, False otherwise.
"""
encoding = event.headers.get("accept-encoding", "")
if "gzip" in encoding:
if response_compression is not None:
return response_compression # e.g., Response(compress=False/True))
if route_compression:
return True # e.g., @app.get(compress=True)
return False
def _compress(self):
"""Compress the response body, but only if `Accept-Encoding` headers includes gzip."""
self.response.headers["Content-Encoding"] = "gzip"
if isinstance(self.response.body, str):
logger.debug("Converting string response to bytes before compressing it")
self.response.body = bytes(self.response.body, "utf-8")
gzip = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)
self.response.body = gzip.compress(self.response.body) + gzip.flush()
def _route(self, event: ResponseEventT, cors: CORSConfig | None):
"""Optionally handle any of the route's configure response handling"""
if self.route is None:
return
if self.route.cors:
self._add_cors(event, cors or CORSConfig())
if self.route.cache_control:
self._add_cache_control(self.route.cache_control)
if self._has_compression_enabled(
route_compression=self.route.compress,
response_compression=self.response.compress,
event=event,
):
self._compress()
def build(self, event: ResponseEventT, cors: CORSConfig | None = None) -> dict[str, Any]:
"""Build the full response dict to be returned by the lambda"""
# We only apply the serializer when the content type is JSON and the
# body is not a str, to avoid double encoding
if self.response.is_json() and not isinstance(self.response.body, str):
self.response.body = self.serializer(self.response.body)
self._route(event, cors)
if isinstance(self.response.body, bytes):
logger.debug("Encoding bytes response with base64")
self.response.base64_encoded = True
self.response.body = base64.b64encode(self.response.body).decode()
return {
"statusCode": self.response.status_code,
"body": self.response.body,
"isBase64Encoded": self.response.base64_encoded,
**event.header_serializer().serialize(headers=self.response.headers, cookies=self.response.cookies),
}
class BaseRouter(ABC):
current_event: BaseProxyEvent
lambda_context: LambdaContext
context: dict
_router_middlewares: list[Callable] = []
processed_stack_frames: list[str] = []
@abstractmethod
def route(
self,
rule: str,
method: Any,
cors: bool | None = None,
compress: bool = False,
cache_control: str | None = None,
summary: str | None = None,
description: str | None = None,
responses: dict[int, OpenAPIResponse] | None = None,
response_description: str = _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION,
tags: list[str] | None = None,
operation_id: str | None = None,
include_in_schema: bool = True,
security: list[dict[str, list[str]]] | None = None,
openapi_extensions: dict[str, Any] | None = None,
deprecated: bool = False,
middlewares: list[Callable[..., Any]] | None = None,
) -> Callable[[AnyCallableT], AnyCallableT]:
raise NotImplementedError()
def use(self, middlewares: list[Callable[..., Response]]) -> None:
"""
Add one or more global middlewares that run before/after route specific middleware.
NOTE: Middlewares are called in insertion order.
Parameters
----------
middlewares: list[Callable[..., Response]]
List of global middlewares to be used
Examples
--------
Add middlewares to be used for every request processed by the Router.
```python
from aws_lambda_powertools import Logger
from aws_lambda_powertools.event_handler import APIGatewayRestResolver, Response
from aws_lambda_powertools.event_handler.middlewares import NextMiddleware
logger = Logger()
app = APIGatewayRestResolver()
def log_request_response(app: APIGatewayRestResolver, next_middleware: NextMiddleware) -> Response:
logger.info("Incoming request", path=app.current_event.path, request=app.current_event.raw_event)
result = next_middleware(app)
logger.info("Response received", response=result.__dict__)
return result
app.use(middlewares=[log_request_response])
def lambda_handler(event, context):
return app.resolve(event, context)
```
"""
self._router_middlewares = self._router_middlewares + middlewares
def get(
self,
rule: str,
cors: bool | None = None,
compress: bool = False,
cache_control: str | None = None,
summary: str | None = None,
description: str | None = None,
responses: dict[int, OpenAPIResponse] | None = None,
response_description: str = _DEFAULT_OPENAPI_RESPONSE_DESCRIPTION,
tags: list[str] | None = None,
operation_id: str | None = None,
include_in_schema: bool = True,
security: list[dict[str, list[str]]] | None = None,
openapi_extensions: dict[str, Any] | None = None,
deprecated: bool = False,
middlewares: list[Callable[..., Any]] | None = None,
) -> Callable[[AnyCallableT], AnyCallableT]:
"""Get route decorator with GET `method`
Examples