Create API with Python, lambda, API Gateway quickly using AWS SAM

In the project, I decided to create a simple API using Python, so I will prepare the environment to create the API quickly.

Premise

Editor ... VS Code OS…Windows10 Python 3.8 installed AWS CLI installed

Installing AWS CLI Version 2 on Windows-AWS Command Line Interface

Required environment

Benefits of AWS SAM

According to the Official Document

--Single deployment configuration --AWS CloudFormation extensions --Built-in best practices --Local debugging and testing --Tight integration with development tools

Is a merit. Personally, being able to debug lambda locally was a big advantage. Since the actual situation is CloudFormation, it is also highly customizable.

Introducing the AWS SAM CLI

Follow the Official Documents. In summary

  1. Install docker
  2. Install from the installer (.msi file) distributed by AWS or install with pip install aws-sam-cli
  3. OK if the version is output with sam --version

docker is installed to create a lambda execution environment on the local machine.

Introducing AWS Toolkit for Visual Studio Code

This is a VS Code extension for working with AWS SAMs from VS Code with a GUI. AWS Toolkit - Visual Studio Marketplace

Create a new project

Follow the Official Documents.

  1. Open the command palette (Ctrl + Shift + P) and select Create new SAM Application image.png
  2. Select the runtime you want to use. This time Python 3.8 image.png
  3. Select a template. This time I will use it alone, so Hwllo World image.png
  4. Specify the directory where you want to create the project. Explorer will open, so select any folder. image.png
  5. Specify the project name. Press Enter to create the project. image.png image.png

Run local debug

  1. Open hello_world / app.py and select Debug Locally to create a virtual environment in docker and execute the function. image.png
  2. OK if the result is output to the debug console image.png

set event

.aws/templates.jsonで設定できる image.png

Deploy

We will deploy based on template.yaml.

  1. Select Deploy SAM Application from the command palette image.png
  2. Select a template. This time templete.yaml image.png
  3. Select any deployment destination region. This time Tokyo image.png
  4. Specify the S3 bucket name. You must specify an existing bucket name here. image.png
  5. Specify the Stack name. Stack is the name of the service group created by CloudFormation. It has the same name as the project name. image.png
  6. If the deployment is successful, the debug console will be displayed. image.png

Confirm that it has been deployed

You can see that the lambda is created as shown below. image.png You can see that the API is also created in API Gateway. image.png

Customize

The API created by default is GET: / hello, so you need to edit templete.yaml to change this.

Below is the default templete.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  trial-sam

  Sample SAM Template for trial-sam

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 3

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
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.8
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /hello
            Method: get

Outputs:
  # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
  # Find out more about other implicit resources you can reference within SAM
  # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
  HelloWorldApi:
    Description: "API Gateway endpoint URL for Prod stage for Hello World function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  HelloWorldFunction:
    Description: "Hello World Lambda Function ARN"
    Value: !GetAtt HelloWorldFunction.Arn
  HelloWorldFunctionIamRole:
    Description: "Implicit IAM Role created for Hello World function"
    Value: !GetAtt HelloWorldFunctionRole.Arn

You can change the path and HTTP method by rewriting this as follows

Before

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
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.8
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /hello
            Method: get

After

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
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.8
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /anypath # hello → anypath
            Method: post # get → post

POST: I was able to change to ʻanypath`. image.png

All you have to do is write the logic

All you have to do is assemble the logic according to your requirements.

If you deploy again, your changes will take effect.

Recommended Posts

Create API with Python, lambda, API Gateway quickly using AWS SAM
[AWS SAM] Create API with DynamoDB + Lambda + API Gateway
[AWS] Create API with API Gateway + Lambda
LINE BOT with Python + AWS Lambda + API Gateway
Quickly take a query string with API Gateway-> Lambda (Python)
[AWS] Using ini files with Lambda [Python]
[Python] Quickly create an API with Flask
[Python] I wrote a REST API using AWS API Gateway and Lambda.
Serverless application with AWS SAM! (APIGATEWAY + Lambda (Python))
[AWS] Try tracing API Gateway + Lambda with X-Ray
Amazon API Gateway and AWS Lambda Python version
Create an API server quickly with Python + Falcon
AWS CDK-Lambda + API Gateway (Python)
Create a Layer for AWS Lambda Python with Docker
Try implementing a Cisco Spark bot with AWS Lambda + Amazon API Gateway (Python)
Create Awaitable with Python / C API
Summary if using AWS Lambda (Python)
AWS Amplify + API Gateway + Lambda + Python returns a normal response
[AWS] Try adding Python library to Layer with SAM + Lambda (Python)
Using Lambda with AWS Amplify with Go
Create API using hug with mod_wsgi
Notify HipChat with AWS Lambda (Python)
I wrote a script to create a Twitter Bot development environment quickly with AWS Lambda + Python 2.7
[SAM] Try using RDS Proxy with Lambda (Python) [user/pass, IAM authentication]
I tried ChatOps with Slack x API Gateway x Lambda (Python) x RDS
[For Python] Quickly create an upload file to AWS Lambda Layer
How to create a serverless machine learning API with AWS Lambda
LINE BOT (Messaging API) development with API Gateway and Lambda (Python) [Part 2]
Automatically create Python API documentation with Sphinx
Quickly create an excel file with Python #python
Connect to s3 with AWS Lambda Python
Easy REST API with API Gateway / Lambda / DynamoDB
Python + Selenium + Headless Chromium with aws lambda
[AWS] Create a Python Lambda environment with CodeStar and do Hello World
View images on S3 with API Gateway + Lambda
Serverless scraping using selenium with [AWS Lambda] -Part 1-
Recent ranking creation using Qiita API with Python
AWS CDK with Python
Dynamic HTML pages made with AWS Lambda and Python
[AWS] Play with Step Functions (SAM + Lambda) Part.3 (Branch)
Create Python version Lambda function (+ Lambda Layer) with Serverless Framework
[Python] Create a ValueObject with a complete constructor using dataclasses
Check types_map when using mimetypes on AWS Lambda (Python)
How to set layer on Lambda using AWS SAM
Register a ticket with redmine API using python requests
Deploy Python3 function with Serverless Framework on AWS Lambda
[AWS] Play with Step Functions (SAM + Lambda) Part.1 (Basic)
I want to AWS Lambda with Python on Mac!
Make ordinary tweets fleet-like with AWS Lambda and Python
Create a company name extractor with python using JCLdic
[AWS] Play with Step Functions (SAM + Lambda) Part.2 (Parameter)
[LINE Messaging API] Create parrot return BOT with Python
Quickly create a Python data analysis dashboard with Streamlit and deploy it to AWS
Try hitting the Twitter API quickly and easily with Python
Operate TwitterBot with Lambda, Python
[S3] CRUD with S3 using Python [Python]
[Python] Scraping in AWS Lambda
Create an API with Django
Made "Unofficial Apple Refurbished Product Introduction" BOT with LINE Messaging API (v2) + API Gateway + lambda (python)
Use Twitter API with Python
Using Quaternion with Python ~ numpy-quaternion ~