AWS CDK-Lambda + API Gateway (Python)

Since there are many cases of TypeScript, a memorandum when I tried it with Python.

Overview

--A sample that exposes Lambda processing of Python implementation via API Gateway.

Impressions

--TypeScript comparison --Add the dependent library to setup.py (unlike npm install --save, write it directly in the file). --Since there are no build steps, the basic operation proceeds quickly (on the other hand, the weakness of type checking is a disadvantage). --Encountered the phenomenon that .gitignore is not included in the repository generated by cdk init. Add a separate file based on the following (it does not seem to occur when language = typescript). - https://github.com/aws/aws-cdk/blob/m1aster/packages/aws-cdk/lib/init-templates/app/python/.gitignore --General ――Since the code completion function based on TypeScript type information is powerful, I don't feel a strong reason to write in Python even if I lose it. On the other hand, it may be advantageous if the implementation code such as Lambda is also implemented in Python and the source is managed in a unified language with Infra (CDK).

procedure

The procedure used to check the operation.

Premise

$ npm install -g aws-cdk
$ cdk --version
1.19.0 (build 5597bbe)

Initialize the application with cdk-init. Also, enable virtualenv with the source command.

$ mkdir lambda-sample && cd $_
$ cdk init --language=python
$ source .env/bin/activate

setup.py Dependent library definitions (by default, only ʻaws-cdk.core exists, so add ʻaws-lambda and ʻaws-apigateway`).

...

    install_requires=[
        "aws-cdk.core",
        "aws-cdk.aws-lambda",
        "aws-cdk.aws-apigateway",
    ],

...

Install dependent libraries based on definition.

$ pip install -r requirements.txt

Implementation

Script implementation.

$ mkdir lambda
$ touch lambda/handler.py

lambdahandler.py

import json
import logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)
 
def main(event, context):
    logger.info(json.dumps(event))
 
    return {
        'statusCode': 200,
        'body': 'Hello World'
    }

lamba_sample/lambda_sample.py

Added Lambda and API Gateway deployment definitions to Stack.

from aws_cdk import (
    aws_lambda,
    aws_apigateway,
    core
)

class LambdaSampleStack(core.Stack):

    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        handler = aws_lambda.Function(
            self, "backend",
            runtime=aws_lambda.Runtime.PYTHON_3_7,
            handler="handler.main",
            code=aws_lambda.AssetCode(path="./lambda"))

        api = aws_apigateway.LambdaRestApi(self, "SampleLambda", handler=handler)

Deploy the defined stack. If you call the API Gateway Endpoint that is output in the ʻOutputs` field, the Lamba output result will be returned.

$ cdk deploy
...
Outputs:
lambda-sample.SampleLambdaEndpoint9FAA5D96 = https://4rtjc3pjfh.execute-api.ap-northeast-1.amazonaws.com/prod/
$ curl https://4rtjc3pjfh.execute-api.ap-northeast-1.amazonaws.com/prod/
Hello World

reference

Recommended Posts

AWS CDK-Lambda + API Gateway (Python)
LINE BOT with Python + AWS Lambda + API Gateway
Amazon API Gateway and AWS Lambda Python version
[AWS] Create API with API Gateway + Lambda
AWS Amplify + API Gateway + Lambda + Python returns a normal response
Create API with Python, lambda, API Gateway quickly using AWS SAM
[Python] I wrote a REST API using AWS API Gateway and Lambda.
[AWS SAM] Create API with DynamoDB + Lambda + API Gateway
[AWS] Try tracing API Gateway + Lambda with X-Ray
Try implementing a Cisco Spark bot with AWS Lambda + Amazon API Gateway (Python)
Evernote API in Python
OpenCV3 Python API list
AWS CDK with Python
C API in Python 3
TensorFlow API memo (Python)
Hit Mastodon's API in Python
Use Trello API with python
[Python] Scraping in AWS Lambda
Quickly take a query string with API Gateway-> Lambda (Python)
EXE Web API by Python
Use Twitter API with Python
Web API with Python + Falcon
Play RocketChat with API / Python
Blender Python API in Houdini (Python 3)
Call the API with python3.
Use subsonic API with python3
Google Drive Api Tips (Python)
(Python) Get AWS billing amount
Use e-Stat API from Python
Hit API Gateway for IAM authentication. Create SigV4 signature header (python)
Send images taken with ESP32-WROOM-32 to AWS (API Gateway → Lambda → S3)
Make a request from Device Farm (appium python) to API Gateway
I tried ChatOps with Slack x API Gateway x Lambda (Python) x RDS
LINE BOT (Messaging API) development with API Gateway and Lambda (Python) [Part 2]
Create Awaitable with Python / C API
Summary if using AWS Lambda (Python)
Data acquisition using python googlemap api
Hit the Sesami API in Python
Run Rotrics DexArm with python API
[Python] Hit the Google Translation API
[Python3] Google translate google translate without using api
Text extraction with AWS Textract (Python3.6)
Write AWS Lambda function in Python
Quine Post with Qiita API (Python)
Exception handling during Python API communication
Try using Pleasant's API (python / FastAPI)
Run Python on Schedule on AWS Lambda
My favorite boto3 (Python) API sample
Cooperation between python module and API
Hit the Etherpad-lite API with Python
Create Gmail in Python without API
[python] Read information with Redmine API
boto3 (AWS SDK for Python) Note
Use kabu Station® API from Python
Hit the web API in Python
How to use OpenPose's Python API
Use the Flickr API from Python
AWS Layer Creation Script for python
Get upcoming weather from python weather api
Try using Python argparse's action API
Quickly implement REST API in Python