AWS API Gateway和Lambda的简单测试

文章目录

  • 具体流程
  • 创建Lambda应用
  • 创建API Gateway
  • S3 Bucket网页测试触发API Gateway和Lambda函数
  • 碰到S3 Bucket删除问题
  • 术语
  • Reference

测试了一下使用API Gateway来触发Lambda应用,并将结果显示在网页上。
Lambda支持语言为: Node.js,Java,Python,C#,Go,PowerShell,等等。它具有无需管理服务器,根据需求自动扩展,便宜等优势。

具体流程

在S3 Bucket里存放网页,显示网页后,在网页里通过API Gateway来触发Lambda功能应用,并将Lambda功能应用返回的结果显示在网页上。Route53来使用DNS网址为可选。

创建Lambda应用

Lambda是EC2在一起的Compute界面下,点进去后,再点Create Function来创建函数, 取名为:XiongLambdaFunction,语言设置为Python 3.6,这样会自动生成以下代码:

import json

def lambda_handler(event, context):
    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

进行以下替换:

import json
def lambda_handler(event, context):
    print("In lambda handler")

    resp = {
        "statusCode": 200,
        "headers": {
            "Access-Control-Allow-Origin": "*",
        },
        "body": "Xiong Huilin"
    }

    return resp

创建API Gateway

创建一个API Gateway,在Networking & Content Delivery下点API Gateway,选择
REST,API取名为:XiongTestAPI,在Actions下点Create Method,选择GET方法,Integration type选择Lambda Function,并选择前面已经创建的XiongLambdaFunction。点保存,有以下提示。

You are about to give API Gateway permission to invoke your Lambda function:
arn:aws:lambda:ap-southeast-1:606255748358:function:XiongLambdaFunction

Deploy API对API进行发布,发布成功后会有一个URL生成,这个生成的URL将会被用做第三步测试:

Invoke URL: https://p9ciqi7imh.execute-api.ap-southeast-1.amazonaws.com/XiongReturnNameAPI

S3 Bucket网页测试触发API Gateway和Lambda函数

创建两个文件:Index.html和error.html,此测试是根据ACloud Guru所做的示例。
在index.html里,将GET请求的URL替换为: https://p9ciqi7imh.execute-api.ap-southeast-1.amazonaws.com/XiongReturnNameAPI,如下html代码所示:

<html>
<script>

function myFunction() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
        document.getElementById("my-demo").innerHTML = this.responseText;
        }
    };
    xhttp.open("GET", "https://p9ciqi7imh.execute-api.ap-southeast-1.amazonaws.com/XiongReturnNameAPI", true);
    xhttp.send();

}

script>
<body><div align="center"><br><br><br><br>
<h1>Hello <span id="my-demo">2nd December 2019!span>h1>
<button onclick="myFunction()">Click mebutton><br>
<img src="https://www.dropbox.com/s/2965glxbyqjmi9h/SanTi.jpg?raw=1">div>
body>
html>

error.html

<html><body><h1>There has been an error for Xiong's website!h1>body>html>

创建一个S3 Bucket,取名为: xionglambdatest,在Properties下面进行设置,Static website hosting,创建了以下Endpoint, Index document设置为index.htmlError Document设置为error.html,保存。
Static website hosting
Endpoint : http://xionglambdatest.s3-website-ap-southeast-1.amazonaws.com

将前面创建的index.htmlerror.html进行上传,

如果你注册了域名的话,可以使用Route53来设置 A Record来指向S3 Bucket的Endpoint达到域名访问的目的。

这里直接测试:
Static website hosting
Endpoint : http://xionglambdatest.s3-website-ap-southeast-1.amazonaws.com

返回以下错误:

403 Forbidden
Code: AccessDenied
Message: Access Denied
RequestId: 0264A5A5BC4FBDE3
HostId: r03Yr+l5vDDiR/0YQL8if2qmRP1lBvBzLoeoGgw6z3jec8XnyWJsz790UwmZGI49ejY5QFYWrfE=
An Error Occurred While Attempting to Retrieve a Custom Error Document
Code: AccessDenied
Message: Access Denied

在S3 Bucket xionglambdatest中,设置Make Public,确认,再试,可以成功访问。

点按钮无反应,在Chrome的Develop Tool里发现碰到以下错误:

Access to XMLHttpRequest at 
'https://byaaiuzpad.execute-api.ap-southeast-1.amazonaws.com/XiongReturnNameAPI' 
from origin 'http://xionglambdatest.s3-website-ap-southeast-1.amazonaws.com' 
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is 
present on the requested resource.

CORS在作怪,在Resource下里的Action里点Enable CORS,再试, 点按钮后,界面返回如下:

Hello {"statusCode": 200, "headers": {"Access-Control-Allow-Origin": "*"}, 
"body": "Xiong Huilin"}

说明https://p9ciqi7imh.execute-api.ap-southeast-1.amazonaws.com/XiongReturnNameAPI返回了{"statusCode": 200, "headers": {"Access-Control-Allow-Origin": "*"}, "body": "Xiong Huilin"}

重新再试,在创建GET方法时,记得把Use Lambda Proxy integration选择项选上, 表明是Lambda返回值 。另外记得在Resource下里的Action里点Enable CORS, 最后Deploy API。这次成功。

点按钮后,以下文字:
Hello 2nd December 2019!
变为:
Hello Xiong Huilin
也就是https://p9ciqi7imh.execute-api.ap-southeast-1.amazonaws.com/XiongReturnNameAPI返回了Xiong Huilin,测试成功!

点完按钮的效果如下:

AWS API Gateway和Lambda的简单测试_第1张图片

碰到S3 Bucket删除问题

前面做Elastic Beanstalk测试的时候:AWS的CloudFormation和Elastic Beanstalk的简单测试,自动创建了名为elasticbeanstalk-ap-southeast-1-606255748358的S3 Bucket,删除时返回了Access Denied的错误。

参见: AWS Forum: can’t delete empty elasticbeanstalk created bucket

在以下Bucket Policy的JSON文件里将Deny改成Allow,就可以删除了,问题解决。

        {
            "Sid": "eb-58950a8c-feb6-11e2-89e0-0800277d041b",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:DeleteBucket",
            "Resource": "arn:aws:s3:::elasticbeanstalk-ap-southeast-1-606255748358"
        }

参见Bucket Policy Examples,可以使用以下JSON文件设置Bucket Policy以达到Bucket为公共访问的目的:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::xionglambdatest/*"
        }
    ]
}

术语

Lambda:参见什么是 AWS Lambda?
REST:参见Representational_state_transfer 维基

Reference

Lambda Troubleshooting - Acloudguru
什么是 AWS Lambda?
Representational_state_transfer 维基
AWS的CloudFormation和Elastic Beanstalk的简单测试
AWS Forum: can’t delete empty elasticbeanstalk created bucket
ACloud Guru
Bucket Policy Examples

你可能感兴趣的:(AWS,REST,AWS,lambda,API,Gateway,S3,Bucket)