AWS Amplify + API Gateway + Lambda + Python returns a normal response

When I configured Lambda + API Gateway with AWS Amplify, I sometimes had a little trouble because I couldn't get a normal response even when I tried to execute the test. So, along with how to add API in Amplify, I will write it as a memorandum and learning.

Conclusion

In conclusion, when calling the Lambda function from API Gateway, it seems that it is necessary to return the following response.

Lambda function output format for proxy integration (https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-output-format)

return {
    "isBase64Encoded": true|false,
    "statusCode": httpStatusCode,
    "headers": { "headerName": "headerValue", ... },
    "multiValueHeaders": { "headerName": ["headerValue", "headerValue2", ...], ... },
    "body": "..."
}

headers and nultiValueHeaders are not specially required, it seems that you should at least return statusCode and body. 。

procedure

environment

--WINdows10 version 20H2

Add Lambda function with Amplify

Start with the project being created in Amplfy.

Add a Lambda function.

$ amplify add function 
? Select which capability you want to add: Lambda function (serverless function)
? Provide an AWS Lambda function name: myfunc
? Choose the runtime that you want to use: Python
Only one template found - using Hello World by default.

Available advanced settings:
- Resource access permissions
- Scheduled recurring invocation
- Lambda layers configuration

? Do you want to configure advanced settings? No
? Do you want to edit the local lambda function now? Yes

If you answer Yes to Do you want to edit the local lambda function now ?, a text editor will open with the initial code similar to the following.

def handler(event, context):
  print('received event:')
  print(event)
  return {
    'message': 'Hello from your new Amplify Python lambda!'
  }

Normally, when Lambda is written in python, the handler name is lambda_handler, but when making it with Amplify, it seems that it is only handler. The handler name specified in Lambda has also been changed, so there is no need to modify it.

Changed to have a normal response

If this is left as it is, the response that API Gateway does not expect is not obtained, so modify the code as follows.

def handler(event, context):
  print('received event:')
  print(event)
  return {
      'isBase64Encoded': False,
      'statusCode': 200,
      'headers': {},
      'body': '{"message": "Hello from your new Amplify Python lambda!"}'
   }

Press Enter in the terminal to add the Lambda function to your Amplify project.

? Press enter to continue 
Successfully added resource myfunc locally.

Next steps:
Check out sample function code generated in <project-dir>/amplify/backend/function/myfunc/src
"amplify function build" builds all of your functions currently in the project
"amplify mock function <functionName>" runs your function locally
"amplify push" builds all of your local backend resources and provisions them in the cloud
"amplify publish" builds all of your local backend and front-end resources (if you added hosting category) and provisions them in the cloud

Add API

Add the API to your Amplify project.

$ amplify add api
? Please select from one of the below mentioned services: REST
? Provide a friendly name for your resource to be used as a label for this category in the project: myapi
? Provide a path (e.g., /book/{isbn}): /items
? Choose a Lambda source Use a Lambda function already added in the current Amplify project
? Choose the Lambda function to invoke by this path myfunc
? Restrict API access No
? Do you want to add another path? No
Successfully added resource myapi locally

Some next steps:
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

Deploying the Amplify project

Now that it's just added locally, deploy the Amplify project on your AWS account.

To deploy your project on AWS, use the command amplify push. When you run this command, the resources will be provisioned in the cloud as follows:

!image.png

API test execution

By default, the method is registered as ANY, so select ANY.

image.png

If you choose to test the client, you will be taken to a screen where you can enter a method or query string. This time we will run the test with GET.

image.png I got the expected response.

If this returns the response of the Lambda function in an incorrect format that lacks the status code etc., it will be as follows. image.png

Summary

When using Lambda + API Gateway, the response must be in the correct format.

Also, Amplify is a lot of fun because it's easy to implement the API.

Recommended Posts

AWS Amplify + API Gateway + Lambda + Python returns a normal response
[Python] I wrote a REST API using AWS API Gateway and Lambda.
LINE BOT with Python + AWS Lambda + API Gateway
Amazon API Gateway and AWS Lambda Python version
AWS CDK-Lambda + API Gateway (Python)
Try implementing a Cisco Spark bot with AWS Lambda + Amazon API Gateway (Python)
Quickly take a query string with API Gateway-> Lambda (Python)
[AWS] Create API with API Gateway + Lambda
Create API with Python, lambda, API Gateway quickly using AWS SAM
Periodically run a python program on AWS Lambda
[AWS SAM] Create API with DynamoDB + Lambda + API Gateway
[AWS] Try tracing API Gateway + Lambda with X-Ray
A python lambda expression ...
Create a Layer for AWS Lambda Python with Docker
A note that connects to Lambda via AWS API Gateway (HTTP API) to process POST data
[Python] Scraping in AWS Lambda
Send images taken with ESP32-WROOM-32 to AWS (API Gateway → Lambda → S3)
Make a request from Device Farm (appium python) to API Gateway
I tried ChatOps with Slack x API Gateway x Lambda (Python) x RDS
How to create a serverless machine learning API with AWS Lambda
LINE BOT (Messaging API) development with API Gateway and Lambda (Python) [Part 2]
Summary if using AWS Lambda (Python)
Write AWS Lambda function in Python
Run Python on Schedule on AWS Lambda
[Python] Make the function a lambda function
Using Lambda with AWS Amplify with Go
Notify HipChat with AWS Lambda (Python)
Python calling Google Cloud Vision API from LINE BOT via AWS Lambda
[AWS] Create a Python Lambda environment with CodeStar and do Hello World
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)
[AWS] Using ini files with Lambda [Python]
Use print in a Python2 lambda expression
[Python] Run Headless Chrome on AWS Lambda
Connect to s3 with AWS Lambda Python
Easy REST API with API Gateway / Lambda / DynamoDB
Python + Selenium + Headless Chromium with aws lambda
A story about cross-compiling a python package for AWS Lambda and deploying it serverless
Create a setting in terraform to send a message from AWS Lambda Python3.8 to Slack