Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit2ff68e9

Browse files
committed
AWS API Gateway with Amazon Lambda integrations support
1 parent059dd73 commit2ff68e9

File tree

10 files changed

+512
-114
lines changed

10 files changed

+512
-114
lines changed

‎docs/integrations/aws.rst

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
Amazon API Gateway
2+
==================
3+
4+
This section describes integration with `Amazon API Gateway<https://aws.amazon.com/api-gateway/>`__.
5+
6+
It is useful for:
7+
8+
* `AWS Lambda integrations<https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html>`__ where Lambda functions handle events from API Gateway (Amazon API Gateway event format version 1.0 and 2.0).
9+
* `AWS Lambda function URLs<https://docs.aws.amazon.com/lambda/latest/dg/lambda-urls.html>`__ where Lambda functions handle events from dedicated HTTP(S) endpoint (Amazon API Gateway event format version 2.0).
10+
11+
ANY method
12+
----------
13+
14+
Amazon API Gateway defines special ``ANY`` method that catches all HTTP methods. It is specified as `x-amazon-apigateway-any-method<https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions-any-method.html>`__ OpenAPI extension. The extension is handled within custom path finder and can be used by setting ``path_finder_cls`` to be ``APIGatewayPathFinder``:
15+
16+
..code-block::python
17+
:emphasize-lines:1,4
18+
19+
from openapi_core.contrib.awsimport APIGatewayPathFinder
20+
21+
config= Config(
22+
path_finder_cls=APIGatewayPathFinder,
23+
)
24+
openapi= OpenAPI.from_file_path('openapi.json',config=config)
25+
26+
Low level
27+
---------
28+
29+
The integration defines classes useful for low level integration.
30+
31+
Request
32+
^^^^^^^
33+
34+
Use ``APIGatewayEventV2OpenAPIRequest`` to create OpenAPI request from an API Gateway event (format version 2.0):
35+
36+
..code-block::python
37+
38+
from openapi_core.contrib.awsimport APIGatewayEventV2OpenAPIRequest
39+
40+
defhandler(event,context):
41+
openapi_request= APIGatewayEventV2OpenAPIRequest(event)
42+
result= openapi.unmarshal_request(openapi_request)
43+
return {
44+
"statusCode":200,
45+
"body":"Hello world",
46+
}
47+
48+
If you use format version 1.0, then import and use ``APIGatewayEventOpenAPIRequest``.
49+
50+
Response
51+
^^^^^^^^
52+
53+
Use ``APIGatewayEventV2ResponseOpenAPIResponse`` to create OpenAPI response from API Gateway event (format version 2.0) response:
54+
55+
..code-block::python
56+
57+
from openapi_core.contrib.awsimport APIGatewayEventV2ResponseOpenAPIResponse
58+
59+
defhandler(event,context):
60+
openapi_request= APIGatewayEventV2OpenAPIRequest(event)
61+
response= {
62+
"statusCode":200,
63+
"body":"Hello world",
64+
}
65+
openapi_response= APIGatewayEventV2ResponseOpenAPIResponse(response)
66+
result= openapi.unmarshal_response(openapi_request, openapi_response)
67+
return response
68+
69+
If you use format version 1.0, then import and use ``APIGatewayEventResponseOpenAPIResponse``.

‎docs/integrations/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ Openapi-core integrates with your popular libraries and frameworks. Each integra
66
..toctree::
77
:maxdepth:1
88

9+
aws
910
aiohttp
1011
bottle
1112
django

‎openapi_core/contrib/aws/__init__.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
"""OpenAPI core contrib django module"""
2+
3+
fromopenapi_core.contrib.aws.findersimportAPIGatewayPathFinder
4+
fromopenapi_core.contrib.aws.requestsimportAPIGatewayEventOpenAPIRequest
5+
fromopenapi_core.contrib.aws.requestsimportAPIGatewayEventV2OpenAPIRequest
6+
fromopenapi_core.contrib.aws.responsesimportAPIGatewayEventResponseOpenAPIResponse
7+
fromopenapi_core.contrib.aws.responsesimportAPIGatewayEventV2ResponseOpenAPIResponse
8+
9+
__all__= [
10+
"APIGatewayPathFinder",
11+
"APIGatewayEventOpenAPIRequest",
12+
"APIGatewayEventV2OpenAPIRequest",
13+
"APIGatewayEventResponseOpenAPIResponse",
14+
"APIGatewayEventV2ResponseOpenAPIResponse",
15+
]

‎openapi_core/contrib/aws/datatypes.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
fromtypingimportDict
2+
fromtypingimportList
3+
fromtypingimportOptional
4+
5+
frompydanticimportField
6+
frompydantic.dataclassesimportdataclass
7+
8+
API_GATEWAY_EVENT_CONFIG=dict(extra="allow")
9+
10+
11+
@dataclass(frozen=True)
12+
classAPIGatewayEvent:
13+
"""AWS API Gateway event"""
14+
model_config=API_GATEWAY_EVENT_CONFIG
15+
16+
headers:Dict[str,str]
17+
18+
path:str
19+
httpMethod:str
20+
resource:str
21+
22+
queryStringParameters:Optional[Dict[str,str]]=None
23+
isBase64Encoded:Optional[bool]=None
24+
body:Optional[str]=None
25+
pathParameters:Optional[Dict[str,str]]=None
26+
stageVariables:Optional[Dict[str,str]]=None
27+
28+
multiValueHeaders:Optional[Dict[str,List[str]]]=None
29+
version:Optional[str]="1.0"
30+
multiValueQueryStringParameters:Optional[Dict[str,List[str]]]=None
31+
32+
33+
@dataclass(frozen=True)
34+
classAPIGatewayEventV2Http:
35+
"""AWS API Gateway event v2 HTTP"""
36+
model_config=API_GATEWAY_EVENT_CONFIG
37+
38+
method:str
39+
path:str
40+
41+
42+
@dataclass(frozen=True)
43+
classAPIGatewayEventV2:
44+
"""AWS API Gateway event v2"""
45+
model_config=API_GATEWAY_EVENT_CONFIG
46+
47+
headers:Dict[str,str]
48+
49+
version:str
50+
routeKey:str
51+
rawPath:str
52+
rawQueryString:str
53+
http:APIGatewayEventV2Http
54+
55+
queryStringParameters:Optional[Dict[str,str]]=None
56+
isBase64Encoded:Optional[bool]=None
57+
body:Optional[str]=None
58+
pathParameters:Optional[Dict[str,str]]=None
59+
stageVariables:Optional[Dict[str,str]]=None
60+
61+
cookies:Optional[List[str]]=None
62+
63+
64+
@dataclass(frozen=True)
65+
classAPIGatewayEventResponse:
66+
"""AWS API Gateway event response"""
67+
model_config=API_GATEWAY_EVENT_CONFIG
68+
69+
body:str
70+
isBase64Encoded:bool
71+
statusCode:int
72+
headers:Dict[str,str]
73+
multiValueHeaders:Dict[str,List[str]]
74+
75+
76+
@dataclass(frozen=True)
77+
classAPIGatewayEventV2Response:
78+
"""AWS API Gateway event v2 response"""
79+
model_config=API_GATEWAY_EVENT_CONFIG
80+
81+
body:str
82+
isBase64Encoded:bool=False
83+
statusCode:int=200
84+
headers:Dict[str,str]=Field(
85+
default_factory=lambda: {"content-type":"application/json"}
86+
)

‎openapi_core/contrib/aws/finders.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
fromopenapi_core.templating.paths.findersimportAPICallPathFinder
2+
fromopenapi_core.templating.paths.iteratorsimport (
3+
CatchAllMethodOperationsIterator,
4+
)
5+
6+
7+
classAPIGatewayPathFinder(APICallPathFinder):
8+
operations_iterator=CatchAllMethodOperationsIterator(
9+
"any",
10+
"x-amazon-apigateway-any-method",
11+
)

‎openapi_core/contrib/aws/requests.py

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
fromtypingimportDict
2+
fromtypingimportOptional
3+
4+
fromwerkzeug.datastructuresimportHeaders
5+
fromwerkzeug.datastructuresimportImmutableMultiDict
6+
7+
fromopenapi_core.contrib.aws.datatypesimportAPIGatewayEvent
8+
fromopenapi_core.contrib.aws.datatypesimportAPIGatewayEventV2
9+
fromopenapi_core.contrib.aws.typesimportAPIGatewayEventPayload
10+
fromopenapi_core.datatypesimportRequestParameters
11+
12+
13+
classAPIGatewayEventOpenAPIRequest:
14+
"""
15+
Converts an API Gateway event payload to an OpenAPI request.
16+
17+
Designed to be used with API Gateway REST API specification exports for
18+
integrations that use event v1 payload. Uses API Gateway event v1 httpMethod
19+
and path data. Requires APIGatewayPathFinder to resolve ANY methods.
20+
"""
21+
22+
def__init__(self,payload:APIGatewayEventPayload):
23+
self.event=APIGatewayEvent(**payload)
24+
25+
self.parameters=RequestParameters(
26+
path=self.path_params,
27+
query=ImmutableMultiDict(self.query_params),
28+
header=Headers(self.event.headers),
29+
cookie=ImmutableMultiDict(),
30+
)
31+
32+
@property
33+
defpath_params(self)->Dict[str,str]:
34+
params=self.event.pathParameters
35+
ifparamsisNone:
36+
return {}
37+
returnparams
38+
39+
@property
40+
defquery_params(self)->Dict[str,str]:
41+
params=self.event.queryStringParameters
42+
ifparamsisNone:
43+
return {}
44+
returnparams
45+
46+
@property
47+
defproto(self)->str:
48+
returnself.event.headers.get("X-Forwarded-Proto","https")
49+
50+
@property
51+
defhost(self)->str:
52+
returnself.event.headers["Host"]
53+
54+
@property
55+
defhost_url(self)->str:
56+
return"://".join([self.proto,self.host])
57+
58+
@property
59+
defpath(self)->str:
60+
returnself.event.path
61+
62+
@property
63+
defmethod(self)->str:
64+
returnself.event.httpMethod.lower()
65+
66+
@property
67+
defbody(self)->Optional[str]:
68+
returnself.event.body
69+
70+
@property
71+
defmimetype(self)->str:
72+
returnself.event.headers.get("Content-Type","")
73+
74+
75+
classAPIGatewayEventV2OpenAPIRequest:
76+
"""
77+
Converts an API Gateway event v2 payload to an OpenAPI request.
78+
79+
Designed to be used with API Gateway HTTP API specification exports for
80+
integrations that use event v2 payload. Uses API Gateway event v2 routeKey
81+
and rawPath data. Requires APIGatewayPathFinder to resolve ANY methods.
82+
83+
.. note::
84+
API Gateway HTTP APIs don't support request validation
85+
"""
86+
87+
def__init__(self,payload:APIGatewayEventPayload):
88+
self.event=APIGatewayEventV2(**payload)
89+
90+
self.parameters=RequestParameters(
91+
path=self.path_params,
92+
query=ImmutableMultiDict(self.query_params),
93+
header=Headers(self.event.headers),
94+
cookie=ImmutableMultiDict(),
95+
)
96+
97+
@property
98+
defpath_params(self)->Dict[str,str]:
99+
ifself.event.pathParametersisNone:
100+
return {}
101+
returnself.event.pathParameters
102+
103+
@property
104+
defquery_params(self)->Dict[str,str]:
105+
ifself.event.queryStringParametersisNone:
106+
return {}
107+
returnself.event.queryStringParameters
108+
109+
@property
110+
defproto(self)->str:
111+
returnself.event.headers.get("x-forwarded-proto","https")
112+
113+
@property
114+
defhost(self)->str:
115+
returnself.event.headers["host"]
116+
117+
@property
118+
defhost_url(self)->str:
119+
return"://".join([self.proto,self.host])
120+
121+
@property
122+
defpath(self)->str:
123+
returnself.event.rawPath
124+
125+
@property
126+
defmethod(self)->str:
127+
returnself.event.routeKey.split(" ")[0].lower()
128+
129+
@property
130+
defbody(self)->Optional[str]:
131+
returnself.event.body
132+
133+
@property
134+
defmimetype(self)->str:
135+
returnself.event.headers.get("content-type","")
136+
137+
138+
classAPIGatewayEventV2HTTPOpenAPIRequest(APIGatewayEventV2OpenAPIRequest):
139+
"""
140+
Converts an API Gateway event v2 payload to an OpenAPI request.
141+
142+
Uses http integration path and method data.
143+
"""
144+
145+
@property
146+
defpath(self)->str:
147+
returnself.event.http.path
148+
149+
@property
150+
defmethod(self)->str:
151+
returnself.event.http.method.lower()

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp