Write cdk and lambda code in python to deploy a REST API in API Gateway backed by a lambda function. Make sure you follow best practices (use aws lambda powertools, latest cdk constructs, etc). You should create a /test resource with both GET and POST options. The lambda code should be modular, with each unique request in a separate module. The entrypoint function should in another module and just encapsulate the routing (and basic error handling) logic.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To deploy a REST API in API Gateway backed by a Lambda function using AWS CDK and AWS Lambda Powertools, follow these steps. We'll create a modular Lambda function with separate modules for each unique request and an entrypoint module for routing and basic error handling.
Step 1: Set Up Your Project
Initialize a new CDK project:
sh
mkdir cdk-api-gateway-lambda
cd cdk-api-gateway-lambda
cdk init app --language python
from aws_cdk import (
aws_apigateway as apigateway,
aws_lambda as _lambda,
aws_lambda_event_sources as event_sources,
aws_iam as iam,
core,
)
from aws_cdk.aws_lambda_python_alpha import PythonFunction
class CdkApiGatewayLambdaStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
# Define the Lambda function
lambda_function = PythonFunction(
self, "ApiGatewayLambdaFunction",
entry="lambda",
index="handler.py",
handler="lambda_handler",
runtime=_lambda.Runtime.PYTHON_3_9,
environment={
"POWERTOOLS_SERVICE_NAME": "ApiGatewayLambdaFunction",
"POWERTOOLS_LOG_LEVEL": "INFO",
},
timeout=core.Duration.seconds(30),
)
# Define the API Gateway
api = apigateway.RestApi(
self, "ApiGateway",
rest_api_name="ApiGateway",
description="API Gateway for Lambda Function",
)
# Define the /test resource
test_resource = api.root.add_resource("test")
# Define the GET method
get_integration = apigateway.LambdaIntegration(
lambda_function,
request_templates={"application/json": '{"statusCode": 200}'}
)
test_resource.add_method("GET", get_integration)
# Define the POST method
post_integration = apigateway.LambdaIntegration(
lambda_function,
request_templates={"application/json": '{"statusCode": 200}'}
)
test_resource.add_method("POST", post_integration)
# Grant API Gateway permission to invoke the Lambda function
lambda_function.add_permission(
"ApiGatewayInvokePermission",
principal=iam.ServicePrincipal("apigateway.amazonaws.com"),
action="lambda:InvokeFunction",
source_arn=api.arn_for_execute_api(
stage="prod",
method="ANY",
resource="{proxy+}"
),
)
Step 4: Deploy the Stack
app.py:
python
from aws_cdk import core
from cdk_api_gateway_lambda.cdk_api_gateway_lambda_stack import CdkApiGatewayLambdaStack
app = core.App()
CdkApiGatewayLambdaStack(app, "CdkApiGatewayLambdaStack")
app.synth()
Deploy the stack:
sh
cdk deploy
This setup creates a REST API in API Gateway with a /test resource that supports both GET and POST methods. The Lambda function is modular, with separate handlers for each request type, and uses AWS Lambda Powertools for logging and tracing. The CDK stack defines the API Gateway and Lambda function, and grants the necessary permissions.