教程:使用 Lambda 代理集成构建 Hello World REST API
Lambda 代理集成 是一种轻量型、灵活的 API Gateway API 集成类型,可让您能够使用 Lambda 函数集成 API 方法(或整个 API)。Lambda 函数可以用 Lambda 支持的任何语言编写。由于这是代理集成,因此您可以随时更改 Lambda 函数实现,而无需重新部署您的 API。
在本教程中,您将执行以下操作:
-
创建“Hello, World!” 要作为 API 的后端的 Lambda 函数。
-
创建并测试“Hello, World!” API 与 Lambda 代理集成。
创建“Hello, World!” Lambda 函数
此函数会将问候语作为以下格式的 JSON 对象返回给调用方:
{ "greeting": "Good
{time}
,{name}
of{city}
.[ Happy{day}
!]" }
创建“Hello, World!” Lambda 控制台中的 Lambda 函数
通过以下网址登录 Lambda 控制台:https://console.aws.amazon.com/lambda
。 -
在 Amazon 导航栏中,选择一个区域(例如,美国东部 (弗吉尼亚北部))。
注意 请注意您创建 Lambda 函数时所在的区域。在创建 API 时,会需要它。
-
在导航窗格中,选择 Functions (函数)。
-
选择创建函数。
-
选择 Author from scratch (从头开始创作)。
-
在 Basic information (基本信息) 中,执行以下操作:
-
在 Function name (函数名称) 中,输入
GetStartedLambdaProxyIntegration
。 -
在 Permissions (权限) 下,展开 Choose or create an execution role (选择或创建执行角色)。从 Execution role (执行角色) 下拉列表中,选择 Create new role from Amazon policy templates (从亚马逊云科技策略模板创建新角色)。
-
在 Role Name (角色名称) 中,输入
GetStartedLambdaBasicExecutionRole
。 -
将 Policy templates (策略模板) 字段留空。
-
选择创建函数。
-
-
在 Function code (函数代码) 下,在内联代码编程中,复制/粘贴以下代码:
'use strict'; console.log('Loading hello world function'); export const handler = async (event) => { let name = "you"; let city = 'World'; let time = 'day'; let day = ''; let responseCode = 200; console.log("request: " + JSON.stringify(event)); if (event.queryStringParameters && event.queryStringParameters.name) { console.log("Received name: " + event.queryStringParameters.name); name = event.queryStringParameters.name; } if (event.queryStringParameters && event.queryStringParameters.city) { console.log("Received city: " + event.queryStringParameters.city); city = event.queryStringParameters.city; } if (event.headers && event.headers['day']) { console.log("Received day: " + event.headers.day); day = event.headers.day; } if (event.body) { let body = JSON.parse(event.body) if (body.time) time = body.time; } let greeting = `Good ${time}, ${name} of ${city}.`; if (day) greeting += ` Happy ${day}!`; let responseBody = { message: greeting, input: event }; // The output from a Lambda proxy integration must be // in the following JSON object. The 'headers' property // is for custom response headers in addition to standard // ones. The 'body' property must be a JSON string. For // base64-encoded payload, you must also set the 'isBase64Encoded' // property to 'true'. let response = { statusCode: responseCode, headers: { "x-custom-header" : "my custom header value" }, body: JSON.stringify(responseBody) }; console.log("response: " + JSON.stringify(response)) return response; };
-
选择 Deploy (部署)。
创建“Hello, World!” API
现在为您的“Hello, World!”创建 API。使用 API Gateway 控制台的 Lambda 函数。
构建“Hello, World!” API
通过以下网址登录到 Amazon API Gateway 控制台:https://console.aws.amazon.com/apigateway
。 -
如果您是第一次使用 API Gateway,您会看到一个介绍服务功能的页面。在 REST API 下,选择 Build (生成)。当 Create Example API (创建示例 API) 弹出框出现时,选择 OK (确定)。
如果这不是您首次使用 API Gateway,请选择创建 API。在 REST API 下,选择 Build (生成)。
-
创建一个空的 API,如下所示:
-
在 Create a new API (创建新 API) 下,选择 New API (新建 API)。
-
在 Settings (设置) 下:
-
对于 API Name (API 名称),请输入
LambdaSimpleProxy
。 -
如果需要,在 Description (说明) 字段中输入说明;否则,将其保留为空。
-
将终端节点类型设置为区域。
-
-
选择 Create API (创建 API)。
-
-
创建
helloworld
资源,如下所示:-
在 Resources (资源) 树下选择根资源 (/)。
-
从 Actions (操作) 下拉菜单中,选择 Create Resource (创建资源)。
-
取消选中 Configure as proxy resource (作为代理资源进行配置)。
-
对于资源名称,输入
helloworld
。 -
将资源路径设置为 /helloworld。
-
取消选中 Enable API Gateway CORS (启用 API Gateway CORS)。
-
选择 Create Resource (创建资源)。
-
-
在代理集成中,整个请求将通过表示任何 HTTP 方法的“捕获全部”
ANY
方法按原样发送到后端 Lambda 函数。实际的 HTTP 方法由客户端在运行时指定。ANY
方法可让您对所有支持的 HTTP 方法使用单个 API 方法设置:DELETE
、GET
、HEAD
、OPTIONS
、PATCH
、POST
和PUT
。要设置
ANY
方法,请执行以下操作:-
在 Resources (资源) 列表中,选择 /helloworld。
-
在 Actions (操作) 菜单中,选择 Create method (创建方法)。
-
从下拉菜单中选择任何,然后选中复选标记图标
-
将集成类型设置为 Lambda 函数。
-
选择 Use Lambda Proxy integration (使用 Lambda 代理集成)。
-
对于 Lambda 区域下拉菜单,选择您在其中创建
GetStartedLambdaProxyIntegration
Lambda 函数的区域。 -
在 Lambda 函数字段中,键入任何字符并从下拉菜单中选择
GetStartedLambdaProxyIntegration
。 -
将 Use Default Timeout (使用默认超时) 保持选中状态。
-
选择 Save。
-
在出现 Add Permission to Lambda Function (向 Lambda 函数添加权限) 提示时,选择 OK (确定)。
-
部署并测试 API
在 API Gateway 控制台中部署 API
-
从 Actions (操作) 下拉菜单中选择 Deploy API (部署 API)。
-
对于部署阶段,选择[新阶段]。
-
对于 Stage name (阶段名称),输入
test
。 -
如果需要,输入一个 Stage description (阶段说明)。
-
如果需要,输入一个 Deployment description (部署说明)。
-
选择 Deploy (部署)。
-
请记下 API 的 Invoke URL (调用 URL)。
使用浏览器和 cURL 来通过 Lambda 代理集成测试 API
您可以使用浏览器或 cURL
要仅使用查询字符串参数测试 GET
请求,您可以在浏览器地址栏中键入 API 的 helloworld
资源的 URL。例如:https://r275xc9bmd
.execute-api.us-east-1
.amazonaws.com/test/helloworld?name=John&city=Seattle
对于其他方法,您必须使用更高级的 REST API 测试实用程序,如 POSTMAN
使用 cURL 测试已部署的 API:
-
打开终端窗口。
-
复制以下 cURL 命令将其粘贴到终端窗口中,同时将
替换为您的 API 的 API ID 并将r275xc9bmd
替换为部署您的 API 的区域。us-east-1
curl -v -X POST \ 'https://
r275xc9bmd
.execute-api.us-east-1
.amazonaws.com/test/helloworld?name=John&city=Seattle' \ -H 'content-type: application/json' \ -H 'day: Thursday' \ -d '{ "time": "evening" }'注意 如果您在 Windows 上运行命令,请改用以下语法:
curl -v -X POST "https://
r275xc9bmd
.execute-api.us-east-1
.amazonaws.com/test/helloworld?name=John&city=Seattle" -H "content-type: application/json" -H "day: Thursday" -d "{ \"time\": \"evening\" }"
您应获得一个包含类似于以下负载的成功响应:
{ "message":"Good evening, John of Seattle. Happy Thursday!", "input":{ "resource":"/helloworld", "path":"/helloworld", "httpMethod":"POST", "headers":{"Accept":"*/*", "content-type":"application/json", "day":"Thursday", "Host":"r275xc9bmd.execute-api.us-east-1.amazonaws.com", "User-Agent":"curl/7.64.0", "X-Amzn-Trace-Id":"Root=1-1a2b3c4d-a1b2c3d4e5f6a1b2c3d4e5f6", "X-Forwarded-For":"72.21.198.64", "X-Forwarded-Port":"443", "X-Forwarded-Proto":"https"}, "multiValueHeaders":{"Accept":["*/*"], "content-type":["application/json"], "day":["Thursday"], "Host":["r275xc9bmd.execute-api.us-east-1.amazonaws.com"], "User-Agent":["curl/0.0.0"], "X-Amzn-Trace-Id":["Root=1-1a2b3c4d-a1b2c3d4e5f6a1b2c3d4e5f6"], "X-Forwarded-For":["11.22.333.44"], "X-Forwarded-Port":["443"], "X-Forwarded-Proto":["https"]}, "queryStringParameters":{"city":"Seattle", "name":"John" }, "multiValueQueryStringParameters":{ "city":["Seattle"], "name":["John"] }, "pathParameters":null, "stageVariables":null, "requestContext":{ "resourceId":"3htbry", "resourcePath":"/helloworld", "httpMethod":"POST", "extendedRequestId":"a1b2c3d4e5f6g7h=", "requestTime":"20/Mar/2019:20:38:30 +0000", "path":"/test/helloworld", "accountId":"123456789012", "protocol":"HTTP/1.1", "stage":"test", "domainPrefix":"r275xc9bmd", "requestTimeEpoch":1553114310423, "requestId":"test-invoke-request", "identity":{"cognitoIdentityPoolId":null, "accountId":null, "cognitoIdentityId":null, "caller":null, "sourceIp":"test-invoke-source-ip", "accessKey":null, "cognitoAuthenticationType":null, "cognitoAuthenticationProvider":null, "userArn":null, "userAgent":"curl/0.0.0","user":null }, "domainName":"r275xc9bmd.execute-api.us-east-1.amazonaws.com", "apiId":"r275xc9bmd" }, "body":"{ \"time\": \"evening\" }", "isBase64Encoded":false } }
如果您在之前的请求中将 POST
更改为 PUT
,则应收到相同的响应。
要测试 GET
方法,请复制以下 cURL
命令并将其粘贴到终端窗口中,同时将
替换为您的 API 的 API ID 并将 r275xc9bmd
替换为部署您的 API 的区域。us-east-1
curl -X GET \ 'https://
r275xc9bmd
.execute-api.us-east-1
.amazonaws.com/test/helloworld?name=John&city=Seattle' \ -H 'content-type: application/json' \ -H 'day: Thursday'
您应收到与之前的 POST
请求的结果类似的响应,区别在于 GET
请求没有任何负载。因此,body
参数将为 null
。