Serverless application with AWS SAM! (APIGATEWAY + Lambda (Python))

Introduction

It was when I built an API in the AWS environment at work a while ago. Opportunity to form a serverless that you were interested in! I was happy to think that There was a period before we started development, so I would like to try something at home ... But I'm scared if I accidentally charge a lot when I set up a load test ... Is there a way to build it locally? When I looked for it, it seemed to be there.

It seems that you can build a serverless application environment in the local environment with the AWS SAM CLI. AWS Serverless Application Model (SAM) command line interface. Build, test, and debug serverless applications locally](https://aws.amazon.com/jp/blogs/news/aws-serverless-application-model-sam-command-line-interface-build-test- and-debug-serverless-apps-locally /)

Let's play Hello World locally!


1: Implementation environment

・ Windows10 Home ・ Docker Toolbox OR Docker for Windows ・ Python ・ AWS SAM CLI Surface.


2: Composition

Browser → API GATEWAY → Lambda (Python)


3: Environmental preparation

1. 1. Python installation

https://www.python.org/downloads/ Downloaded from python-3.8.1.exe Install around. image.png Check the red circle and put it in your PATH.


2. Install Docker

You need Docker to run it, so put in the Docker toolbox! (* If the OS is not Home, you should install Docker for Windows in this item! This is also easy because I think you can go with just the installer!)

https://github.com/docker/toolbox/releases From DockerToolbox-19.03.1.exe Drop and install! (The exe version changes depending on the time.)

Once installed image.png

I think there is such an icon, so If you run it and open a terminal like this, installation is OK! image.png

3. 3. install sam

You can install it by hitting the command, so Let's enter from the command! Open PowerShell and type:

pip install aws-sam-cli

Then the download will start and the installation is complete! Then hit the following command to check.

PS C:\> sam --version
SAM CLI, version 0.40.0

It's OK if the version comes out like this!


4: Sample execution

1. 1. Install sample Hello World

Let's put the sample application in a suitable folder.

mkdir C:\Users\User name\samtest
cd C:\Users\User name\samtest

Create a folder like this and move it. (User name is login user name) Then

sam init --runtime python3.7

Execute.

image.png If you see this display, Press 1

Project name [sam-app]:

Enter as it is

image.png Next is 1 again image.png This completes the installation!

In the previous folder sam-app A folder has been created and a sample file has been created inside. ↓ Tree display

└─sam-app
    │  .gitignore
    │  README.md
    │  template.yaml
    │
    ├─events
    │      event.json
    │
    ├─hello_world
    │      app.py
    │      requirements.txt
    │      __init__.py
    │
    └─tests
        └─unit
                test_handler.py
                __init__.py

2. Test run

After confirming that the installation is complete, let's run a test.

cd sam-app
python -m pip install --upgrade pip
pip install pytest pytest-mock --user
python -m pytest tests/ -v

Update pip on the second line, Install test on line 3 The test is executed on the 4th line. image.png I think the test will pass like this!


3. 3. Build

Let's build and run the program!

sam build --use-container

image.png Once built, HelloWorldFunction will be defined and ready to run!


4. API execution

Run the API locally so that you can access it from your browser and run the program!

sam local start-api

image.png Because a display like this appears

http://127.0.0.1:3000/hello

You can see that you can access!


5. access!

http://127.0.0.1:3000/hello

Let's access. The first one may take some time.

image.png If you see this display, it's OK!


EX: Try to modify

At this rate, just running the sample program I don't know what's going on, so I'll just play around with it and try again!


1. 1. Program modification

Stop the API once!

Ctrl key+C key

Press it with the keyboard to stop.

Then In the hello_world folder Edit app.py! (Please edit with a text editor etc.) image.png This file is the actual processing part.

import json

# import requests


def lambda_handler(event, context):
    """Sample pure Lambda function

    Parameters
    ----------
    event: dict, required
        API Gateway Lambda Proxy Input Format

        Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format

    context: object, required
        Lambda Context runtime methods and attributes

        Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html

    Returns
    ------
    API Gateway Lambda Proxy Output Format: dict

        Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
    """

    # try:
    #     ip = requests.get("http://checkip.amazonaws.com/")
    # except requests.RequestException as e:
    #     # Send some context about this error to Lambda Logs
    #     print(e)

    #     raise e

    #Postscript
    Dataout = [{'Data 1': 'Hello','Data 2': 'Good night' , 'cd':'Z01'}]

    return {
        "statusCode": 200,
        "body": json.dumps({
            #Rewrite"message": "hello world",
            "message": Dataout,
            # "location": ip.text.replace("\n", "")
        }),
    }

Addition of Dataout variables Replaced the message output. Please save!


2. Rebuild & API execution

Build again and run the API.

sam build --use-container
sam local start-api

3. 3. Re-access

If you can do it, try accessing it again.

http://127.0.0.1:3000/hello

I think that such a result is returned.

{"message": [{"\u30c7\u30fc\u30bf1": "\u306f\u308d\u30fc", "\u30c7\u30fc\u30bf2": "\u304a\u3084\u3059\u307f", "\uff43\uff44": "Z01"}]}

Let's decode the returned character string with a service like the one below. http://dev.digitra.net/tools/jsonfairing.php image.png If you get such a result, you are successful!

Now you can run Hello World and make some changes! Next, I would like to connect DynamoDB to the one I made this time!

Recommended Posts

Serverless application with AWS SAM! (APIGATEWAY + Lambda (Python))
Deploy Python3 function with Serverless Framework on AWS Lambda
Notify HipChat with AWS Lambda (Python)
[AWS] Try adding Python library to Layer with SAM + Lambda (Python)
Create API with Python, lambda, API Gateway quickly using AWS SAM
[AWS] Using ini files with Lambda [Python]
Connect to s3 with AWS Lambda Python
Touch AWS with Serverless Framework and Python
Python + Selenium + Headless Chromium with aws lambda
Install pip in Serverless Framework and AWS Lambda with Python environment
[AWS SAM] Create API with DynamoDB + Lambda + API Gateway
Regular serverless scraping with AWS lambda + scrapy Part 1.8
Serverless scraping using selenium with [AWS Lambda] -Part 1-
LINE BOT with Python + AWS Lambda + API Gateway
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
Create a Layer for AWS Lambda Python with Docker
[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
[AWS] Play with Step Functions (SAM + Lambda) Part.2 (Parameter)
Operate TwitterBot with Lambda, Python
[Python] Scraping in AWS Lambda
Deploy Django serverless with Lambda
AWS Lambda with PyTorch [Lambda import]
Web application with Python + Flask ② ③
Effortlessly with Serverless Python Requirements
Web application with Python + Flask ④
Site monitoring and alert notification with AWS Lambda + Python + Slack
[Introduction to Udemy Python 3 + Application] 58. Lambda
Summary if using AWS Lambda (Python)
[AWS] Create API with API Gateway + Lambda
Text extraction with AWS Textract (Python3.6)
Face detection with Lambda (Python) + Rekognition
Write AWS Lambda function in Python
Monitor Python application performance with Dynatrace ♪
Run Python on Schedule on AWS Lambda
Using Lambda with AWS Amplify with Go
Use PostgreSQL with Lambda (Python + psycopg2)
Application development with Docker + Python + Flask
Python application: Data cleansing # 2: Data cleansing with DataFrame
[AWS SAM] Introduction to Python version
[Python] Convert CSV file uploaded to S3 to JSON file with AWS Lambda
Build a Flask / Bottle-like web application on AWS Lambda with Chalice
Manipulating kintone data with Python & C Data ODBC Driver from AWS Lambda
[SAM] Try using RDS Proxy with Lambda (Python) [user/pass, IAM authentication]
Serverless scraping on a regular basis with AWS lambda + scrapy Part 1
Let's make a web chat using WebSocket with AWS serverless (Python)!
How to create a serverless machine learning API with AWS Lambda
ImportError when trying to use gcloud package with AWS Lambda Python version
[AWS] Create a Python Lambda environment with CodeStar and do Hello World
Manipulate DynamoDB data with Lambda (Node & Python)
I want to play with aws with python
[Python] A quick web application with Bottle!
[AWS] Link Lambda and S3 with boto3
Use Application Insights with Python 3 (including bottles)
[Python] Run Headless Chrome on AWS Lambda
Run a Python web application with Docker
Serverless face recognition API made with Python