Skip to content

Instantly share code, notes, and snippets.

@b-b3rn4rd
Last active October 4, 2016 04:51
Show Gist options
  • Save b-b3rn4rd/b0da433f98d3b7975b6341dfae26340e to your computer and use it in GitHub Desktop.
Save b-b3rn4rd/b0da433f98d3b7975b6341dfae26340e to your computer and use it in GitHub Desktop.
API Gateway decorators for transforming request and response templates to lambda Proxy
def handler_pre_dispatch(handler):
"""
Request decorator to convert APIG Proxy params to the old style
Merge GET, POST, STAGE into new event dict
:param handler: resource handler
:return:
"""
def request_decorator(event, content):
event_decorated = {}
if event['queryStringParameters']:
event_decorated.update(event['queryStringParameters'])
if event['pathParameters']:
event_decorated.update(event['pathParameters'])
if event['stageVariables']:
event_decorated.update(event['stageVariables'])
return handler(event_decorated, content)
return request_decorator
def handler_callback(handler):
"""
Response decorator to convert old style exceptions
and responses to APIG Proxy response format
:param handler: resource handler
:return:
"""
def response_decorator(event, context):
try:
response = handler(event, context)
raise Exception(json.dumps(response))
except Exception as e:
exceptions = collections.OrderedDict((
(400, 'Bad Request:'),
(422, 'Unprocessable Entity:'),
(200, '')
))
for code, message in exceptions.items():
if str(e).startswith(message):
message = str(e).replace(message, '') if message else str(e)
break
return {
"statusCode": code,
"headers": {
"Content-Type": "application/json",
"Accept": "application/json"
},
"body": message
}
return response_decorator
@handler_pre_dispatch
@handler_callback
def hello_handler(event, context):
return services.say_hello(event, context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment