Receive POST on API Gateway + Lambda using AWS CDK (Python)

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:

procedure

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. スクリーンショット 2020-09-07 6.40.51.png

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

Recommended Posts

Receive POST on API Gateway + Lambda using AWS CDK (Python)
Create API with Python, lambda, API Gateway quickly using AWS SAM
[Python] I wrote a REST API using AWS API Gateway and Lambda.
LINE BOT with Python + AWS Lambda + API Gateway
Amazon API Gateway and AWS Lambda Python version
Check types_map when using mimetypes on AWS Lambda (Python)
Run Python on Schedule on AWS Lambda
Post images of Papillon regularly on Python + AWS Lambda + Slack
[Python] Run Headless Chrome on AWS Lambda
[AWS] Try tracing API Gateway + Lambda with X-Ray
Try implementing a Cisco Spark bot with AWS Lambda + Amazon API Gateway (Python)
How to set layer on Lambda using AWS SAM
Send and receive Gmail via the Gmail API using Python
Deploy Python3 function with Serverless Framework on AWS Lambda
Support for Python 2.7 runtime on AWS Lambda (as of 2020.1)
Post to your account using the API on Twitter
I want to AWS Lambda with Python on Mac!
A little trick to know when writing a Twilio application using Python on AWS Lambda
Post to Twitter using Python
[Python] Allow pip3 packages to be imported on AWS Lambda
Things to note when running Python on EC2 from AWS Lambda
Best practice for logging in JSON format on AWS Lambda / Python
I compared Node.js and Python in creating thumbnails using AWS Lambda
I tried ChatOps with Slack x API Gateway x Lambda (Python) x RDS
Tweet WakaTime Summary using AWS Lambda
Notes on installing Python using PyEnv
Try using Python argparse's action API
Notes on using rstrip with python.
Install Python on CentOS using Pyenv
Notify HipChat with AWS Lambda (Python)
Install Python on CentOS using pyenv
Understanding from the mechanism Twilio # 3-1 --AWS API Gateway + Lambda implementation Walkthrough (Part 1)
Modules cannot be imported in Python on EC2 run from AWS Lambda
Setting up Basic authentication using Python @Lambda
Get Youtube data in Python using Youtube Data API
I tried using UnityCloudBuild API from Python
Run servomotor on Raspberry Pi 3 using python
Connect to s3 with AWS Lambda Python
Detect temperature using python on Raspberry Pi 3!
Creating Google Spreadsheet using Python / Google Data API
Easy REST API with API Gateway / Lambda / DynamoDB
Setting up Digest authentication using Python @Lambda
Feel free to turn Python using the library into an AWS Lambda function