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!
・ Windows10 Home ・ Docker Toolbox OR Docker for Windows ・ Python ・ AWS SAM CLI Surface.
Browser → API GATEWAY → Lambda (Python)
https://www.python.org/downloads/ Downloaded from python-3.8.1.exe Install around. Check the red circle and put it in your PATH.
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
I think there is such an icon, so If you run it and open a terminal like this, installation is OK!
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!
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.
If you see this display, Press 1
Project name [sam-app]:
Enter as it is
Next is 1 again 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
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. I think the test will pass like this!
Let's build and run the program!
sam build --use-container
Once built, HelloWorldFunction will be defined and ready to run!
Run the API locally so that you can access it from your browser and run the program!
sam local start-api
Because a display like this appears
http://127.0.0.1:3000/hello
You can see that you can access!
http://127.0.0.1:3000/hello
Let's access. The first one may take some time.
If you see this display, it's OK!
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!
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.) 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!
Build again and run the API.
sam build --use-container
sam local start-api
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 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