Serverless 简明教程
Serverless - API Gateway Triggered Lambdas
API 网关是触发 Lambda 的另一种流行方法,就像 cron/速率事件一样。基本上,您可以为您的 Lambda 函数获取一个 URL 端点。此 URL 属于连接到您的 Lambda 的 API 网关。无论您在浏览器中还是通过应用程序调用 URL,您的 Lambda 函数都会被调用。在本章中,我们将介绍如何使用 Serverless 框架将 API 网关连接到您的 Lambda 函数,以及如何对其进行测试。
API Gateways are another popular method of triggering lambdas, just like cron/rate events. Basically, you get a URL endpoint for your lambda function. This URL belongs to the API Gateway connected to your lambda. Whenever you invoke the URL,either in the browser or through an application, your lambda function gets invoked. In this chapter, we will see how to connect an API Gateway to your lambda function using the serverless framework, and how to test it.
HTTP Events
要将 API 网关链接到 Lambda 函数,我们需要在 Serverless.yml 中的函数定义中创建 HTTP 事件。以下示例显示了如何将您的 Lambda 函数链接到 REST API 并使用 GET 请求触发它们。
To link an API Gateway to a lambda function, we need to create HTTP events in the function definition in serverless.yml. The following example shows how to link your lambda function(s) to a REST API and trigger it using the GET request.
functions:
user_details_api:
handler: handler.send_user_details
events:
- http:
path: details/{user_id}
method: get
integration: lambda-proxy
cors: true
location_api:
handler: handler.send_location
events:
- http:
path: location/{user_id}
method: get
integration: lambda-proxy
cors: true
让我们逐一解开这些键。我们只讨论上述列表中的第一个函数(user_details_api)。以下介绍的概念也适用于其他函数。
Let’s unpack the keys one by one. We will only discuss the first function from the above list (user_details_api). The concepts covered below hold for the other function as well.
path 的值指定调用 URL 时端点之后的地址。上面示例中定义的两个函数将共享相同的端点,但一个将使用 endpoint/details/{user_id} 进行调用,而另一个将使用 endpoint/location/{user_id} 进行调用。大括号内的元素是路径参数。我可以在 user_id 的位置发送任意值,而 Lambda 函数可以被编程为返回该特定用户的详细信息(请参见下面的示例函数)。
The value of the path specifies the address after the endpoint for invoking the URL. Both the functions defined in the above example will share the same endpoint, but one will be invoked using endpoint/details/{user_id}, while the other will be invoked by endpoint/location/{user_id} The elements within curly brackets are path parameters. I can send any value in place of user_id and the lambda function can be programmed to return details for that particular user (see the example function below).
method 的值表示请求方法。流行的方法是 get 和 post。还有其他几种方法。深入了解这些方法的详细信息不在本章的讨论范围内。还有另一个您可用来了解详细信息的 post on tutorialspoint 。
The value of the method indicates the request method. The popular methods are get and post. There are several other methods as well. Diving into the details of these methods is outside the scope of this chapter. There is another post on tutorialspoint which you can refer to for the details.
integration 字段指定 Lambda 函数将如何与 API 网关集成。默认值为 lambda-proxy ,而其他可能选项为 lambda、http、http-proxy、mock。在这两个选项中最广泛使用的选项是 lambda 和 lambda-proxy。用普通人的术语来说, lambda-proxy 将整个控制权交给您的 Lambda 函数,而 lambda 将一些控制权交给 API 网关,另一些控制权交给 Lambda 函数。
The integration field specifies how the lambda function will be integrated with the API Gateway. The default is lambda-proxy, while the other options which are possible are * lambda, http, http-proxy, mock*. The most widely used options out of these two are lambda and lambda-proxy. In layperson terms, lambda-proxy gives the entire control to your lambda function, while lambda gives some control to the API Gateway and some to the lambda function.
如果您选择 lambda-proxy 作为集成类型,那么整个 HTTP 请求将以原始形式传递给您的 Lambda 函数,Lambda 函数发送的响应将原样传递给提出请求的客户端。因此,您必须在您的 Lambda 函数的响应中定义 statusCode 和 headers。
If you choose lambda-proxy as the integration type, then the entire HTTP request will be passed in the raw form to your lambda function, and the response sent by the lambda function is passed without alteration to the client which made the request. Therefore,you have to define the statusCode and headers in the response of your lambda function.
如果您选择 lambda 作为集成类型,您的 API 网关可以在将收到的请求传递给 Lambda 函数之前对其进行更改。类似地,它还可以在将 Lambda 函数发送的响应转发给客户端之前对其进行修改。API 网关将状态代码和 headers 添加到响应中,因此,Lambda 函数只需担心发送正文。这两个选项各有优缺点。
If you choose lambda as the integration type, your API Gateway can make changes to the received request,before passing it on to the lambda function. Similarly, it can also modify the response sent by the lambda function before forwarding it to the client. The API Gateway adds the status code and the headers to the response, and therefore, the lambda function just has to worry about sending the body. Both options have their advantages and disadvantages.
如果您更喜欢简单,您可以使用 lambda-proxy 。如果您对一些复杂性没有意见(因为您必须担心 Lambda 函数的代码和 API 网关的配置),但需要更多的控制权,您可以选择 lambda 。
You can use lambda-proxy if you prefer simplicity. You can choose lambda if you are okay with some complexity (since you will have to worry about the lambda function’s code as well as the API Gateway’s configuration), but require more control.
您可以阅读 here 了解这两个类型之间的更多区别。在其他集成类型中, http 和 http-proxy 用于在将 API 网关与 HTTP 后端集成(而不是 Lambda 函数)时使用,因此与我们无关。mock 用于在不调用后端的情况下测试 API。
You can read more about the difference between these two types here.Out of the other integration types, http and http-proxy are used when integrating the API Gateway with an HTTP backend instead of the lambda function, so irrelevant for us. *mock*is used when you just want to test the API without invoking the backend.
cors − true 配置启用 CORS(跨域资源共享)。用普通人的术语来说,这意味着您允许来自另一个域的服务器的请求。如果没有 cors − true ,则只允许来自同一域的请求。当然,您可以只允许某些特定域,而不是允许所有域。要了解如何执行此操作,请参见 documentation 。
The cors − true configuration enables CORS (Cross-Origin Resource Sharing). In layperson terms, this means that you allow requests from servers from another domain. Without cors − true, only requests from the same domain will be allowed. Of course, instead of allowing all domains, you can allow only some specific domains. To understand how to do that, see the documentation.
在 Serverless 中,针对由 API 网关触发的 Lambda 函数,有许多可能的配置。强烈建议您仔细阅读 documentation ,或至少将链接加入书签,以便在需要时可以查找。
There are a lot more configurations possible within serverless, for API-Gateway triggered lambdas. You are strongly recommended to go through the documentation, or at least bookmark the link so that you can look it up whenever required.
Sample Lambda Function
此时,您可能想知道您已经创建了由 API 网关触发的函数,但是您如何在 Lambda 函数中访问路径参数?当集成类型为 lambda-proxy 时,以下示例 Python Lambda 函数将回答这个问题。我们基本上使用 'pathParameters' 属性。
At this point, you may be wondering that you created the API Gateway triggered function, but how do you access the path parameters in the lambda function? The following sample lambda function in python will answer that. We basically use the 'pathParameters' property, when the integration type is lambda-proxy.
import json
def lambda_handler(event, context):
# TODO implement
# print(event)
#helps you see the entire input request. The printed output can be found in CloudWatch logs
user = event['pathParameters']['user_id']
return {
'statusCode': 200,
'body': json.dumps('Hello ' + str(user))
}
Accessing the Endpoint
现在,您可能有的另一个问题是如何访问端点。有多种方法可以做到这一点。第一种方法是通过 Serverless 部署。无论您通过一项服务部署一个函数还是多个函数,此端点都会在 Serverless 部署的最后显示。
Now, another question that you may be having is how do you access the endpoint. There are multiple ways of doing that. The first way is through serverless deployment. Whenever you deploy a function, or multiple functions through a service, the endpoint is shown at the end of serverless deploy.
第二种方法是通过 Lambda 控制台。如果您在 Lambda 控制台上导航到您的函数,您可以看到附加到它的 API 网关。点击它应该会显示端点。
The second method is through the Lambda console. If you navigate to your function on the lambda console, you can see the API Gateway attached to it. Clicking on it should reveal the endpoint.

请注意,如上所述,服务中的所有函数共享相同的端点。path 属性将一个函数的实际触发 URL 与另一个函数的 URL 区分开来。
Please note that, as discussed above, all the functions within a service share the same endpoint.The path property differentiates the actual trigger URL of one function from another.