[For beginners] You can do it from scratch! Creating APIs with AWS SAM and outputting OpenAPI documentation in Python

Introduction

Previously, I introduced the flow of OpenAPI document creation and API automatic generation using the Swagger tool. [For super beginners] You can try it in 5 minutes! OpenAPI (Swagger3.0) document creation-API automatic generation

This time, using AWS SAM (Serverless Application Model), API Gateway + AWS Lambda Create a serverless web API of / jp / api-gateway /) and output the OpenAPI document. This is my first time using AWS SAM. I will write it so that I can do it from scratch.

What is AWS SAM?

The AWS Serverless Application Model (SAM) is an open source framework for building serverless applications. You can express functions, APIs, databases, and event source mappings in a fast-descriptable syntax. With just a few lines per resource, you can define any application and model it using YAML. During deployment, SAM can speed up the construction of serverless applications by converting and extending the SAM syntax to AWS CloudFormation syntax.

Use the AWS SAM CLI to start building SAM-based applications. The SAM CLI provides a Lambda-like execution environment that allows you to build, test, and debug applications defined in SAM templates locally. You can also deploy your application to AWS using the SAM CLI.

https://aws.amazon.com/jp/serverless/sam/

It seems to be a framework that makes CloudFormation easy to use in serverless applications. API Gateway, AWS Lambda, [DynamoDB]( You can manage https://aws.amazon.com/jp/dynamodb/) all at once.

Premise

OS:Mac AWS account created

things to do

  1. Environment construction (pyenv, pipenv)
  2. Make the AWS CLI available
  3. Enable the AWS SAM CLI
  4. Try Hello World on AWS SAM
  5. Output OpenAPI document

Environment construction (pyenv, pipenv)

1. Install pyenv

$ brew install pyenv

If you cannot use the brew command, install Homebrew from the following https://brew.sh/index_ja.html

2. Check the version of pyenv

$ pyenv --version
pyenv 1.2.15

3. Install python 3.7.0 with pyenv

$ pyenv install 3.7.0

4. Switch to the version installed with pyenv

If it is local, it will be reflected in the current directory, and if it is global, it will be reflected in the whole.

$ pyenv global 3.7.0
$ pyenv local 3.7.0

5. Check if it is reflected

$ pyenv versions
  system
* 3.7.0 (set by /Users/yusaku/.pyenv/version)

6. Installation of pipenv

$ brew install pipenv

7. Enter the virtual environment of pipenv

$ pipenv shell

Make the AWS CLI available

1. Install aws cli

$ pipenv install awscli

2. Check the version of aws cli

$ aws --version
aws-cli/1.16.294 Python/3.7.5 Darwin/19.0.0 botocore/1.13.30

3. Confirmation of access key ID and secret access key

https://console.aws.amazon.com/iam/home?#/security_credentials Create an access key from Create a new access key inAccess key (access key ID and secret access key)and check the access key ID and secret access key.

4. awscli settings

Set with the information confirmed in 3. https://docs.aws.amazon.com/ja_jp/cli/latest/userguide/cli-chap-welcome.html

$ aws configure
AWS Access Key ID [None]: XXXXXXXXXXXXXXXXXXXX
AWS Secret Access Key [None]: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Default region name [None]: ap-northeast-1
Default output format [None]: json

Enable AWS SAM CLI

1. Install AWS SAM CLI

$ pipenv install aws-sam-cli

2. Check the version of AWS SAM CLI

sam --version
SAM CLI, version 0.34.0

Try Hello World on AWS SAM

This time, I will use python3.7 installed in the pipenv environment.

1. Application initialization

$ sam init

	SAM CLI now collects telemetry to better understand customer needs.

	You can OPT OUT and disable telemetry collection by setting the
	environment variable SAM_CLI_TELEMETRY=0 in your shell.
	Thanks for your help!

	Learn More: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-telemetry.html

Which template source would you like to use?
	1 - AWS Quick Start Templates
	2 - Custom Template Location
Choice: 1

Which runtime would you like to use?
	1 - nodejs12.x
	2 - python3.8
	3 - ruby2.5
	4 - go1.x
	5 - java11
	6 - dotnetcore2.1
	7 - nodejs10.x
	8 - nodejs8.10
	9 - nodejs6.10
	10 - python3.7
	11 - python3.6
	12 - python2.7
	13 - java8
	14 - dotnetcore2.0
	15 - dotnetcore1.0
Runtime: 10

Project name [sam-app]: AWSsam_test    

Allow SAM CLI to download AWS-provided quick start templates from Github [Y/n]: y

-----------------------
Generating application:
-----------------------
Name: AWSsam_test
Runtime: python3.7
Dependency Manager: pip
Application Template: hello-world
Output Directory: .

Next steps can be found in the README file at ./AWSsam_test/README.md

2. Build the application

$ cd AWSsam_test/
$ sam build

3. Deploy the application

$ sam deploy --guided

From the second time onwards, sam deploy is OK.

4. Operation check

Try to access the endpoint output in 3.

$ curl https://hoge.hoge-api.ap-northeast-1.amazonaws.com/Prod/hello/
{"message": "hello world"}

hello world is back! When I logged in to the AWS console and looked at Lambda, API Gateway and Lambda were started as shown below. スクリーンショット 2019-12-05 15.48.19.png

5. Try executing the Lambda function with a slight change

Let's change hello_world / app.py as follows.

hello_world/app.py


import json

# import requests


def lambda_handler(event, context):
    return {
        "statusCode": 200,
        "body": json.dumps({
            "message": "hello Qiita",
            # "location": ip.text.replace("\n", "")
        }),
    }

Build and deploy.

$ sam build
$ sam deploy

Try to access the endpoint.

$ curl https://hoge.hoge-api.ap-northeast-1.amazonaws.com/Prod/hello/
{"message": "hello Qiita"}

I was able to confirm that the changes were reflected.

Output OpenAPI document

Select Amazon API Gateway from the AWS console and select the API you deployed. The following screen will be displayed. Click the stage and select Export to output the Swagger specification or OpenAPI specification document in json format or yaml format. スクリーンショット 2019-12-06 9.24.16.png

in conclusion

This time, I created a REST API with AWS SAM and exported the OpenAPI Specification document. On the contrary, I would like to import the OpenAPI Specification and create an API using AWS SAM. It is introduced in the following article, but it does not seem to be so easy. .. https://dev.classmethod.jp/cloud/aws/serverless-swagger-apigateway/

reference

Tutorial: Deploying a Hello World Application https://dev.classmethod.jp/cloud/aws/aws-sam-simplifies-deployment/

Recommended Posts

[For beginners] You can do it from scratch! Creating APIs with AWS SAM and outputting OpenAPI documentation in Python
Consideration when you can do a good job in 10 years with Python3 and Scala3.
Until you can install blender and run it with python for the time being
If you write TinderBot in Python, she can do it
Consider what you can do with Python from the Qiita article
Python | What you can do with Python
You can do it with Python! Structural analysis of two-dimensional colloidal crystals
You can do it in 5 minutes !? Create a face detection API with FastAPI and OpenCV and publish it on Heroku
You will be an engineer in 100 days --Day 35 --Python --What you can do with Python
If you guys in the scope kitchen can do it with a margin ~ ♪
Causal reasoning and causal search with Python (for beginners)
~ Tips for Python beginners from Pythonista with love ① ~
~ Tips for Python beginners from Pythonista with love ② ~
[Introduction for beginners] Working with MySQL in Python
What to do if you run python in IntelliJ and end with an error
Rock-paper-scissors poi in Python for beginners (answers and explanations)
% And str.format () in Python. Which one do you use?
Get mail from Gmail and label it with Python3
What you can and cannot do with Tensorflow 2.x
A learning roadmap that allows you to develop and publish services from scratch with Python
Precautions when inputting from CSV with Python and outputting to json to make it an exe
Put Ubuntu in Raspi, put Docker on it, and control GPIO with python from the container
[For beginners] Summary of standard input in Python (with explanation)
What you can do with the Python standard library statistics
Install CaboCha in Ubuntu environment and call it with Python.
[For beginners] Baseball statistics and PyData that can be remembered in 33 minutes and 4 seconds ~ With Dai-Kang Yang