Skip to content
This repository has been archived by the owner on May 19, 2024. It is now read-only.

Commit

Permalink
feat: simply with the new ApiGatewayResolver
Browse files Browse the repository at this point in the history
Signed-off-by: heitorlessa <[email protected]>
  • Loading branch information
heitorlessa committed May 7, 2021
1 parent 05cb1e1 commit 87f1f89
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 98 deletions.
2 changes: 1 addition & 1 deletion {{ cookiecutter.project_name }}/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ run: ##=> Run SAM Local API GW and can optionally run new containers connected t
|| sam local start-api --docker-network ${NETWORK}

test: ##=> Run pytest
@POWERTOOLS_TRACE_DISABLED=1 POWERTOOLS_METRICS_NAMESPACE="MyServerlessApplication" $(PIPENV) run python -m pytest --cov . --cov-report term-missing --cov-fail-under $(CODE_COVERAGE) tests/ -v
@POWERTOOLS_TRACE_DISABLED=1 POWERTOOLS_METRICS_NAMESPACE="MyServerlessApplication" $(PIPENV) run python -m pytest --cov . --cov-report term-missing --cov-fail-under $(CODE_COVERAGE) tests/ -vv

ci: ##=> Run full workflow - Install deps, build deps, and deploy
$(MAKE) dev
Expand Down
92 changes: 19 additions & 73 deletions {{ cookiecutter.project_name }}/hello_world/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,91 +3,37 @@

import boto3
from aws_lambda_powertools import Logger, Metrics, Tracer
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.utilities.typing import LambdaContext
from aws_lambda_powertools.event_handler.api_gateway import ApiGatewayResolver

# https://awslabs.github.io/aws-lambda-powertools-python/#features
tracer = Tracer()
logger = Logger()
metrics = Metrics()
app = ApiGatewayResolver()

# Global variables are reused across execution contexts (if available)
session = boto3.Session()
# session = boto3.Session()

@metrics.log_metrics(capture_cold_start_metric=True)
@logger.inject_lambda_context
@tracer.capture_lambda_handler
def lambda_handler(event, context):
"""
AWS Lambda handler
Parameters
----------
context: object, required
Lambda Context runtime methods and attributes
Attributes
----------
context.aws_request_id: str
Lambda request ID
context.client_context: object
Additional context when invoked through AWS Mobile SDK
context.function_name: str
Lambda function name
context.function_version: str
Function version identifier
context.get_remaining_time_in_millis: function
Time in milliseconds before function times out
context.identity:
Cognito identity provider context when invoked through AWS Mobile SDK
context.invoked_function_arn: str
Function ARN
context.log_group_name: str
Cloudwatch Log group name
context.log_stream_name: str
Cloudwatch Log stream name
context.memory_limit_in_mb: int
Function memory
https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html
@app.get("/hello")
def hello():
query_string_name = app.current_event.get_query_string_value(name="name", default_value="universe")
return {"message": f"hello {query_string_name}"}

event: dict, required
API Gateway Lambda Proxy Input Format

{
"resource": "Resource path",
"path": "Path parameter",
"httpMethod": "Incoming request's method name"
"headers": {Incoming request headers}
"queryStringParameters": {query string parameters }
"pathParameters": {path parameters}
"stageVariables": {Applicable stage variables}
"requestContext": {Request context, including authorizer-returned key-value pairs}
"body": "A JSON string of the request payload."
"isBase64Encoded": "A boolean flag to indicate if the applicable request payload is Base64-encode"
}
@app.get("/hello/<name>")
def hello_you(name):
# query_strings_as_dict = app.current_event.query_string_parameters
# json_payload = app.current_event.json_body
return {"message": f"hello {name}"}

https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format
Returns
------
API Gateway Lambda Proxy Output Format: dict
'statusCode' and 'body' are required
{
"isBase64Encoded": true | false,
"statusCode": httpStatusCode,
"headers": {"headerName": "headerValue", ...},
"body": "..."
}
# api-gateway-simple-proxy-for-lambda-output-format
https: // docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
"""
@metrics.log_metrics(capture_cold_start_metric=True)
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
@tracer.capture_lambda_handler
def lambda_handler(event, context: LambdaContext):
try:
message = {"hello": "world"}
return {
"statusCode": 200,
"body": json.dumps(message)
}
return app.resolve(event, context)
except Exception as e:
logger.exception(e)
raise
58 changes: 36 additions & 22 deletions {{ cookiecutter.project_name }}/template.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,24 @@ Transform: AWS::Serverless-2016-10-31
Description: >
{{ cookiecutter.project_name }}
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Globals: # https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-specification-template-anatomy-globals.html
Api:
EndpointConfiguration: REGIONAL
TracingEnabled: true
Cors: # https://awslabs.github.io/aws-lambda-powertools-python/latest/core/event_handler/api_gateway/#cors
# AllowOrigin: "'https://example.com'"
AllowOrigin: "'*'" # Dev only
AllowHeaders: "'Content-Type,Authorization,X-Amz-Date'"
MaxAge: "'300'"
BinaryMediaTypes: # https://awslabs.github.io/aws-lambda-powertools-python/latest/core/event_handler/api_gateway/#binary-responses
- '*~1*' # converts to */* for any binary type
Function:
Timeout: 5
MemorySize: 256
Runtime: python3.8
Tracing: Active # https://docs.aws.amazon.com/lambda/latest/dg/lambda-x-ray.html
{%- if cookiecutter.include_safe_deployment == "y" %}
AutoPublishAlias: live # More info about Safe Deployments: https://github.com/awslabs/serverless-application-model/blob/master/docs/safe_lambda_deployments.rst
AutoPublishAlias: live # More info about Safe Deployments: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-function-deploymentpreference.html
DeploymentPreference:
Type: Linear10PercentEvery1Minute {% endif %}
Environment:
Expand All @@ -24,17 +34,22 @@ Globals:

Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Type: AWS::Serverless::Function # More info about Function Resource: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html
Properties:
Handler: app.lambda_handler
CodeUri: hello_world
Description: Hello World function
Events:
CatchAll:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
HelloPath:
Type: Api # More info about API Event Source: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-function-api.html
Properties:
Path: /hello
Method: GET
HelloYou:
Type: Api
Properties:
Path: /hello/{name}
Method: GET
# Policies: # Example inline policy
# - Version: "2012-10-17"
# Statement:
Expand All @@ -43,27 +58,26 @@ Resources:
# - "ssm:GetParameter"
# Resource:
# - "*"
Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object
Environment:
Variables:
PARAM1: VALUE
Tags:
SOLUTION: MyServerlessApplication
SOLUTION_MODULE: MyHelloWorldFunction
LambdaPowertools: python

# Sample policy to add additional permissions to your Lambda
HelloWorldFunctionAdditionalPermission:
Type: "AWS::IAM::Policy"
Properties:
PolicyName: "root"
PolicyDocument:
Version: "2012-10-17"
Statement:
-
Effect: "Allow"
Action: "ssm:GetParameters"
Resource: "*"
Roles:
- !Ref HelloWorldFunctionRole # Sample policy to demonstrate Implicit IAM Role created with SAM
# HelloWorldFunctionAdditionalPermission:
# Type: "AWS::IAM::Policy"
# Properties:
# PolicyName: "root"
# PolicyDocument:
# Version: "2012-10-17"
# Statement:
# -
# Effect: "Allow"
# Action: "ssm:GetParameters"
# Resource: "*"
# Roles:
# - !Ref HelloWorldFunctionRole # Sample policy to demonstrate Implicit IAM Role created with SAM

Outputs:
HelloWorldApigwURL:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

def test_lambda_handler(apigw_event, lambda_context):
ret = app.lambda_handler(apigw_event, lambda_context)
expected = json.dumps({"message": "hello universe"}, separators=(",", ":"))

assert ret['statusCode'] == 200
assert ret['body'] == json.dumps({'hello': 'world'})
assert ret["statusCode"] == 200
assert ret["body"] == expected

0 comments on commit 87f1f89

Please sign in to comment.