Roughly speaking, AWS CDK is to write a design document (CloudFormation) for an application built on AWS in a programming language. In this article, I will implement the simple flow of processing POSTed JSON with Lambda through API Gateway using Python. For the settings to use AWS CDK, refer to the official documents below:
First, create an appropriate directory and create the following cdk.json.
cdk.json
{
"app": "python3 app.py"
}
Next, create a new directory (eg lambda) in that directory and create a Lambda function in it (here webhook.py). It is a function that simply returns the JSON of the request body part as it is.
lambda/webhook.py
import json
def handler(event, content):
try:
body = event.get("body")
print(body)
status_code = 200
except Exception as e:
status_code = 500
body = {"description": str(e)}
return {
"statusCode": status_code,
"headers": {
"Content-Type": "text/plain"
},
"body": json.dumps(body)
}
Finally, go back to the original directory and define the Honmaru app (ʻapp.py`).
app.py
import os
from aws_cdk import (
core,
aws_lambda as _lambda,
aws_apigateway as apigw
)
class PrintPostStack(core.Stack):
def __init__(self, scope: core.App, name: str, **kwargs) -> None:
super().__init__(scope, name, **kwargs)
lambda_func = _lambda.Function(
self, "PrintPostFunc",
code=_lambda.Code.from_asset("lambda"),
handler="webhook.handler",
runtime=_lambda.Runtime.PYTHON_3_7,
)
api = apigw.RestApi(self, "PrintPostApi")
api.root.add_method("POST", apigw.LambdaIntegration(lambda_func))
app = core.App()
PrintPostStack(
app, "PrintPostStack",
env={
"region": os.environ["CDK_DEFAULT_REGION"],
"account": os.environ["CDK_DEFAULT_ACCOUNT"]
}
)
app.synth()
--Stack is a term that refers to the set of all AWS resources that are built.
--The Lambda function is set with lambda_func.
-- code = _lambda.Code.from_asset ("lambda ") means that your Lambda function file is in the lambda directory.
--handler = "webhook.handler"means look at the handler function in webhook.py
--runtime = _lambda.Runtime.PYTHON_3_7 should use Python 3.7
--The API Gateway is set with ʻapi. --Added POST method with ʻapi.root.add_method ("POST", apigw.LambdaIntegration (lambda_func)) , integrated with lambda_func
that's all. All you have to do is deploy with the command below.
$ cdk deploy
If all goes well, you will see the endpoint URL. POST an appropriate JSON with the cURL command and check the response.
$ curl -X POST \
> -H "Content-Type: application/json" \
> -d '{"Key1":"Value1", "Key2":"Value2"}' \
> https://xxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/prod/
"{\"Key1\":\"Value1\", \"Key2\":\"Value2\"}"
If JSON is returned as it is as above, it is successful.
Also, in webhook.py, the request body part isprint (body). You can see this log from CloudWatch. From the AWS Console> Services, find and click CloudWatch and go to the Logs> Logs group to see the log named PrintPostStack. You should see the JSON as shown below.

that's all! I introduced AWS CDK through super simple API Gateway + Lambda. Please see the official example below as well.
Recommended Posts