[PYTHON] [AWS] Create API with API Gateway + Lambda

Thing you want to do

I want to create an API without using a server. Confirm that the request is thrown and returned from the EC2 instance to the REST API created by API Gateway. Qiita logo

procedure

Let's create a REST API using Amazon API Gateway and Lambda.

[1. Create a Lambda function](# 1-lambda% E9% 96% A2% E6% 95% B0% E3% 82% 92% E4% BD% 9C% E6% 88% 90% E3% 81% 99 % E3% 82% 8B) [2. Create REST API with API Gateway](# 2-api-gateway% E3% 81% A7rest-api% E3% 82% 92% E4% BD% 9C% E6% 88% 90% E3% 81% 99% E3% 82% 8B) [3. Deploy REST API](# 3-rest-api% E3% 82% 92% E3% 83% 87% E3% 83% 97% E3% 83% AD% E3% 82% A4% E3% 81 % 99% E3% 82% 8B) [4. Create a second Lambda function](# 4-2% E7% 95% AA% E7% 9B% AE% E3% 81% AElambda% E9% 96% A2% E6% 95% B0% E3% 82% 92% E4% BD% 9C% E6% 88% 90% E3% 81% 99% E3% 82% 8B) [5. Add resources, methods and parameters to REST API with API Gateway](# 5-api-gateway% E3% 81% A7rest-api% E3% 81% AB% E3% 83% AA% E3% 82% BD% E3% 83% BC% E3% 82% B9% E3% 83% A1% E3% 82% BD% E3% 83% 83% E3% 83% 89% E3% 83% 91% E3% 83% A9% E3% 83% A1% E3% 83% BC% E3% 82% BF% E3% 82% 92% E8% BF% BD% E5% 8A% A0% E3% 81% 99% E3% 82% 8B)

Reference: https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/apigateway-getting-started-with-rest-apis.html

1. Create a Lambda function

When you create the API Gateway, you need to specify the Lambda function, so create the Lambda function first.

Select "Function"-> "Create Function" from the Lambda console screen. Select "Create from scratch" on the function creation screen.

Function name: my-function Runtime: Python 3.7 And press "Create Function". 2.png

If the message "The function my-function was created successfully" appears, the function creation is complete. 3.png

By the way, the created function returns "Hello from Lambda!" By default. 4.png

2. Create a REST API with API Gateway

Click "Create API" from the console screen of API Gateway. Since this is a verification, select "Build" in "REST API Private". 5.png

A pop-up will appear, so select OK. 6.png

Set as shown in the image below. After completing the selection and input, click "Create API". 7.png

When completed, only "/" will be displayed. This "/" is the root level resource and corresponds to the URL of the API base path. 8.png

Next, add a method. Select Actions> Create Method. 9.png

Select "GET" and press the check mark. 10.png

Then, the GET setup screen will appear, so enter the necessary information and "Save". 11.png

The set contents are displayed. Please refer to Official for details of each item. 12.png

Creating the REST API is now complete.

3. Deploy the REST API

To actually use it, you need to deploy the REST API you created.

Select Actions> Deploy API for the REST API you created. 13.png

A pop-up will appear, so select "New Stage" and Set the stage name to "dev" and press "Deploy". 14.png

Then, the stage editor screen is displayed and you can actually send a request to the API with the URL of the URL call. 15.png

Let's actually make a request from an EC2 instance.

$ curl -X GET 'URL of the call'

"Hello from Lambda!"

It is OK if the response "Hello from Lambda!" Returned by the set Lambda is returned.

4. Create a second Lambda function

Next, we will also perform a pattern with parameters in the GET request. In the previous API, Lambda now returns a fixed value of'Hello from Lambda!'. So, this time, I will create an API with Lambda that puts the parameters of the received GET request in the response.

Create a Lambda function in the same way as before. Function name: my-function2 Runtime: Python 3.7 Run Role: Select the role you just created in Use Existing Role. 16.png

When the creation is complete, rewrite the function code. 17.png

Put the received parameters in the response.

lambda_function.py


import json

def lambda_handler(event, context):
    myParam = event['myParam']
    return {
        'statusCode': 200,
        'body': json.dumps(myParam)
    }

Lambda settings are complete.

5. Add resources, methods and parameters to the REST API with API Gateway

We will create resources with API Gateway.

"Action"-> "Create Resource" 18.png

Resource name: my-resource → "Create resource" 19.png

Next, we will create the method. With my-resource selected, "Action"-> "Create Method" 20.png

Select "GET" and confirm with the check button. 21.png

The my-resource GET setup screen will appear, so select the "my-function2" created earlier for the Lambda function and save it. 22.png

A pop-up for adding authority will appear, so click "OK". 23.png

Select "Integration Request" on the method execution screen. 24.png

Since there is a "mapping template" setting at the bottom, Request body passthrough: If no template is defined (recommended) Content-Type:application/json Is specified. 25.png

Enter the template and save it. 26.png

template


{
    "myParam": "$input.params('myParam')"
}

Now, you can get the item "myParam" of the request parameter by event ['myParam'] on the Lambda function side.

lambda_function.py


import json

def lambda_handler(event, context):
    myParam = event['myParam'] #← here
    return {
        'statusCode': 200,
        'body': json.dumps(myParam)
    }

This completes the settings on the API side, so let's deploy and execute it as before.

I will check

Try to request by adding "my-resource? MyParam = Hello% 20from% 20API% 20Gateway!" To the parameter.

$ curl -X GET 'https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/dev/my-resource?myParam=Hello%20from%20API%20Gateway!'

{"statusCode": 200, "body": "\"Hello from API Gateway!\""}

I was able to confirm that the "Hello from API Gateway!" Assigned to the request parameter responds as a body.

This time, we implemented it with the minimum necessary settings, so it seems that more research will be required when introducing it, but I think that we have grasped the whole picture of API Gateway + Lambda as serverless.

Recommended Posts

[AWS] Create API with API Gateway + Lambda
Create API with Python, lambda, API Gateway quickly using AWS SAM
LINE BOT with Python + AWS Lambda + API Gateway
[AWS] Try tracing API Gateway + Lambda with X-Ray
Easy REST API with API Gateway / Lambda / DynamoDB
Send images taken with ESP32-WROOM-32 to AWS (API Gateway → Lambda → S3)
How to create a serverless machine learning API with AWS Lambda
View images on S3 with API Gateway + Lambda
Amazon API Gateway and AWS Lambda Python version
Create an API with Django
AWS CDK-Lambda + API Gateway (Python)
AWS Lambda with PyTorch [Lambda import]
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
Quickly take a query string with API Gateway-> Lambda (Python)
AWS Amplify + API Gateway + Lambda + Python returns a normal response
Using Lambda with AWS Amplify with Go
Create API using hug with mod_wsgi
Notify HipChat with AWS Lambda (Python)
I tried ChatOps with Slack x API Gateway x Lambda (Python) x RDS
[Python] I wrote a REST API using AWS API Gateway and Lambda.
LINE BOT (Messaging API) development with API Gateway and Lambda (Python) [Part 2]
Automatically create Python API documentation with Sphinx
[AWS] Link Lambda and S3 with boto3
[Python] Quickly create an API with Flask
Connect to s3 with AWS Lambda Python
Create Page / Todo Block with Notion API
Create a private repository with AWS CodeArtifact
[AWS] Do SSI-like things with S3 / Lambda
Python + Selenium + Headless Chromium with aws lambda
I just did FizzBuzz with AWS Lambda
Let's create a chat function with Vue.js + AWS Lambda + dynamo DB [AWS settings]
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
Understanding from the mechanism Twilio # 3-1 --AWS API Gateway + Lambda implementation Walkthrough (Part 1)
Serverless scraping using selenium with [AWS Lambda] -Part 1-
Serverless application with AWS SAM! (APIGATEWAY + Lambda (Python))
I tried connecting AWS Lambda with other services
Infrastructure construction automation with CloudFromation + troposphere + AWS Lambda
Pass Cognito Id to Lambda via API Gateway
Create an API server quickly with Python + Falcon
Create a bot with AWS Lambda that automatically starts / stops Instances with specific tags
A note that connects to Lambda via AWS API Gateway (HTTP API) to process POST data
Make Lambda Layers with Lambda
Dynamic HTML pages made with AWS Lambda and Python
[AWS] Play with Step Functions (SAM + Lambda) Part.3 (Branch)
Create Amazon Linux with AWS EC2 and log in
Create Python version Lambda function (+ Lambda Layer) with Serverless Framework
Deploy Python3 function with Serverless Framework on AWS Lambda
Create a tweet heatmap with the Google Maps API
Extrude with Fusion360 API
Create games with Pygame
Create filter with scipy
[AWS] Play with Step Functions (SAM + Lambda) Part.1 (Basic)
I want to AWS Lambda with Python on Mac!
Tweet from AWS Lambda
Manage your Amazon CloudWatch loggroup retention with AWS Lambda
AWS CDK with Python
Make ordinary tweets fleet-like with AWS Lambda and Python
Try AWS Lambda Destinations
[AWS] Play with Step Functions (SAM + Lambda) Part.2 (Parameter)