aws lambda_AWS API Gateway和AWS Lambda示例

公西苗宣
2023-12-01

aws lambda

The purpose of this article is to present the most relevant details and not-so-straight steps to create/use the two important services in Amazon Web Services – AWS API Gateway and AWS Lambda Function – at one place.

本文的目的是在一个地方展示最相关的细节和不太简单的步骤,以在Amazon Web Services中创建/使用两个重要服务-AWS API GatewayAWS Lambda Function

目录 (Table of Contents)

AWS API网关 (AWS API Gateway)

  1. What is AWS API Gateway?

    什么是AWS API Gateway?
  2. What should one use it for?

    一个人应该用它做什么?
  3. How does it work – Create and Deploy

    工作原理–创建和部署
  4. Advantages

    优点
  5. Limitations

    局限性
  6. Integrated AWS Services

    集成AWS服务

AWS Lambda (AWS Lambda)

  1. What is a Lambda function?

    什么是Lambda函数?
  2. Integrate your first Java based Lambda Function with AWS API Gateway

    将您的第一个基于Java的Lambda函数与AWS API Gateway集成

什么是AWS API Gateway? (What is AWS API Gateway?)

The AWS API Gateway is a relatively new service provided by Amazon to enable users to ‘create’, ‘publish’, ‘monitor’, ‘maintain’ and ‘secure’ their APIs.

AWS API Gateway是Amazon提供的一项相对较新的服务,使用户能够“创建”,“发布”,“监视”,“维护”和“保护”其API。

It acts as a ‘gateway’ for the end users to access your applications/business logic. If you have an existing public API or are planning to make your application public, you may like to deploy it on the AWS API Gateway to achieve better performance, scalability, availability with low maintenance and cost.

它充当最终用户访问您的应用程序/业务逻辑的“门户”。 如果您具有现有的公共API或计划将应用程序公开,则可能希望将其部署在AWS API Gateway上,以实现更好的性能,可伸缩性,可用性,而维护成本和成本却较低。

If you are planning to build your business logic/write the application code, you may also like to use AWS Lambda Functions that is another service by Amazon, in addition to deploying it on the API Gateway and get rid of the maintenance of servers.

如果您打算构建业务逻辑/编写应用程序代码,则除了将其部署在API网关上并摆脱服务器维护之外,您可能还希望使用Amazon的另一项服务AWS Lambda Functions

You can also expose your existing Lambda functions as APIs using the API gateway. Deploying an API doesn’t cost anything. You need to pay on the basis of the number of requests your API receives and the amount of the data it sends back.

您还可以使用API​​网关将现有的Lambda函数公开为API。 部署API不会花费任何费用。 您需要根据您的API收到的请求数和它发送回的数据量付费。

一个人应该用它做什么? (What should one use it for?)

  • To deploy an already public API to achieve better performance, monitoring and throttling.

    部署已经公开的API,以实现更好的性能,监视和限制。
  • To deploy an existing API hosted in AWS (EC2 instances)

    部署AWS中托管的现有API(EC2实例)
  • To re-package legacy applications and transform their request/response structures without having to re-write them

    重新打包旧版应用程序并转换其请求/响应结构,而不必重新编写它们
  • To expose Lambda functions as APIs, avoid managing servers

    要将Lambda函数公开为API,请避免管理服务器

工作原理–创建和部署 (How does it work – Create and Deploy)

You can deploy your existing API on AWS Gateway, if it is deployed/running on Amazon Cloud (on EC2 Instances) or is publicly accessible, no matter where it is deployed.

如果现有的API已部署在Amazon Cloud(在EC2实例上)上/在Amazon Cloud上运行(无论在何处部署),都可以将其部署在AWS Gateway上。

When you deploy an API, you need to create ‘Resources’ and ‘Methods’ inside those resources. A method in AWS API Gateway corresponds to the HTTP methods such as GET, POST, and DELETE etc. Resources are logical groupings of methods and are like URLs in your web application.

部署API时,需要在这些资源内创建“资源”和“方法”。 AWS API Gateway中的方法对应于HTTP方法,例如GET,POST和DELETE等。资源是方法的逻辑分组,类似于Web应用程序中的URL。

In the API Gateway, a method is a place where you as a developer, would define the structure of your API. Here, you would define the back end that this method will call (a Lambda function or your existing public application) and the request-response structures. The method contains four sections defined in the next section to build this structure.

在API网关中,方法是您作为开发人员定义API结构的地方。 在这里,您将定义此方法将调用的后端(Lambda函数或您现有的公共应用程序)和请求-响应结构。 该方法包含在下一部分中定义的四个部分,以构建此结构。

Below, I’ve noted down the steps you need to take to create and deploy a basic API in AWS API Gateway with simplified information about what each step does.

下面,我已记录了在AWS API Gateway中创建和部署基本API所需采取的步骤,并提供了有关每个步骤的简化信息。

  1. Create an API: This is the first step, once you launch the API Gateway Console. It creates a ‘gate’ for your existing API, or creates a new API on top of your business logic/back-end code or clone an API existing in AWS API gateway.

    创建API :启动API网关控制台后,这是第一步。 它会为您现有的API创建一个“门”,或者在您的业务逻辑/后端代码之上创建一个新的API,或者克隆AWS API网关中现有的API。
  2. Create a Resource: A resource in the AWS API is similar to a resource in a web application – just as in a web app, you define a URL to access a physical resource, similarly in AWS API, while creating a ‘Resource’, define a URL to access a piece of our physical resources – the back-end code, lambda functions or an existing API. In this step, you just create a logical name, the actual target of this URL is defined while creating a method in the next step.

    创建资源 :AWS API中的资源类似于Web应用程序中的资源–就像在Web应用程序中一样,您在创建“资源”的同时,定义一个访问物理资源的URL,类似于AWS API,一个URL,用于访问我们的一部分物理资源-后端代码,lambda函数或现有的API。 在此步骤中,您只需创建一个逻辑名,然后在下一步中创建方法时定义此URL的实际目标。
  3. Create a Method: A method corresponds to an HTTP verb like GET, POST, DELETE “inside a Resource”. In a method, you would define your request/response structure for the method call and the end target which will be called when this method is invoked. The end target can be a Lambda function or an existing public application (either deployed on Amazon Cloud or is publicly accessible otherwise).

    创建方法 :方法与HTTP动词相对应,例如“在资源内部”,例如GET,POST,DELETE。 在方法中,您将定义方法调用的请求/响应结构以及将在调用此方法时调用的最终目标。 最终目标可以是Lambda函数或现有的公共应用程序(可以部署在Amazon Cloud上,也可以通过其他方式公开访问)。

Now comes the main and tricky part – transformation – which enables users to re-package their existing APIs by changing their request/response structures without re-writing the code. Inside a method, you can define the transformations you want to apply on the request and the response of this method.

现在出现了主要且棘手的部分-转换-它使用户可以通过更改其请求/响应结构来重新打包其现有的API,而无需重新编写代码。 在方法内部,可以定义要应用于此方法的请求和响应的转换。

In the transformation process, you can change the format of the input and the output and/or add/remove header information.

在转换过程中,您可以更改输入和输出的格式和/或添加/删除标题信息。

By using these transformations, you can change the way your existing API interacts with the end users without re-writing it.

通过使用这些转换,您可以更改现有API与最终用户交互的方式,而无需重新编写。

A method contains four sections defined below to build its request/response structure:

一个方法包含下面定义的四个部分,以构建其请求/响应结构:

  1. Method Request – Defines who is authorized to access this method and the request structure (headers, body data format through ‘Models’) expected by the AWS API Gateway.

    方法请求 –定义谁有权访问此方法,以及AWS API Gateway期望的请求结构(标头,主体数据格式(通过“模型”))。
  2. Integration Request – Defines the ‘end point’, and the request structure as expected by the end target (the original application). Here, you can have transformations to change your original input request data to a format expected by the end target.

    集成请求 –定义“端点”和最终目标(原始应用程序)期望的请求结构。 在这里,您可以进行转换以将原始输入请求数据更改为最终目标所需的格式。
  3. Integration Response – Defines the actual response returned by the end target, apply transformations here to change the response body/headers.

    集成响应 –定义最终目标返回的实际响应,在此处应用转换以更改响应主体/标题。
  4. Method Response – Defines the response returned by the AWS API to the end user (after being transformed if required), you can have different transformations for different response codes.

    方法响应 –定义AWS API返回给最终用户的响应(如果需要,在转换之后),您可以对不同的响应代码进行不同的转换。

The first two sections deal with Requests as their names suggest. The ‘Method Request’ section defines the ‘structure of your request as is needed by the API being deployed on the Gateway’. The ‘Integration Request’ section contains the ‘transformations’ you would like to apply on the original request to convert it into the one expected by your back end application.

前两节按名称建议处理请求。 “方法请求”部分定义了“部署在网关上的API所需的请求结构”。 “集成请求”部分包含您要对原始请求进行的“转换”,以将其转换为后端应用程序期望的转换。

After the transformations, the Gateway calls your back end application whose URL you defined when you created the method.

转换之后,网关将调用您的后端应用程序,该应用程序的URL是您在创建方法时定义的。

The next section, ‘Integration Response’ is the one where you get the response sent by your application. Here, you can apply transformations on this response to make it one which you want to send back to the user. The last section ‘Method Response’ has the transformed response. Here, you can also define custom headers if you want to add some more information in the original response.

下一节“集成响应”是您获得应用程序发送的响应的部分。 在这里,您可以对此响应应用转换,以使其成为要发送回用户的响应。 最后一部分“方法响应”具有转换后的响应。 如果要在原始响应中添加更多信息,还可以在此处定义自定义标头。

Request/Response Transformation
While learning to work with AWS API Gateway, Transformation seemed the trickiest part, not because of the complexity (it’s not very complex), but because of the lack of clear documentation.

请求/响应转换
在学习使用AWS API Gateway的过程中,转换似乎是最棘手的部分,这并不是因为复杂(不是很复杂),而是因为缺少清晰的文档。

Throughout the documentation, Amazon claims that you can convert data from JSON to XML and vice versa, and in each step of the transformation process, they say – ‘specify the data format’ which gives the impression that any valid data type can be transformed, which is not true. I found it works only one way – JSON to XML.

在整个文档中,Amazon声称您可以将数据从JSON转换为XML,反之亦然,并且在转换过程的每个步骤中,他们都说–“指定数据格式”,给人的印象是任何有效的数据类型都可以转换,这是不对的。 我发现它仅以一种方式起作用-从JSON到XML。

There are three important aspects of the input data and its transformation:

输入数据及其转换包含三个重要方面:

  • The data itself – the input data in the JSON format

    数据本身– JSON格式的输入数据
  • The schema or the Model that the input data should follow

    输入数据应遵循的模式或模型
  • The Mapping template or the transformation using which you can convert the JSON data to a format that our java program expects.

    您可以使用Mapping模板或转换将JSON数据转换为Java程序期望的格式。

The ‘Model’ is a schema that defines the ‘format’ of the JSON data (like an XSD for an XML data) and the ‘Mapping Template’ defines the transformation to be applied on the JSON data (like XSLT transformations for XML).

“模型”是一种模式,用于定义JSON数据的“格式”(例如XML数据的XSD),而“映射模板”则定义要应用于JSON数据的转换(例如XML的XSLT转换)。

Using the Mapping Templates, you can convert the JSON data to any other format. I explain here with a basic example where I had to convert a JSON input to XML for calling a temperature conversion web service:

使用映射模板,您可以将JSON数据转换为任何其他格式。 我在这里用一个基本示例进行说明,其中我必须将JSON输入转换为XML才能调用温度转换Web服务:

Define the Model in ‘Method Request’

在“方法请求”中定义模型

In the model, define how your input data would look like:

在模型中,定义输入数据的外观:

{
  "$schema": "https://json-schema.org/draft-04/schema#", 
  "title": "TempConvertInputModel",
  "type": "object",
  "properties": {
    "Temperature": { "type": "integer" },
    "FromUnit": {"type": "string"},
    "ToUnit": {"type": "string"}
	}
}

Define the ‘Mapping Template’ in ‘Integration Request’: Here, you define the template that will apply on the input data conforming to the data model defined in the first step and will convert it into an XML which is needed by your end target.

在“集成请求”中定义“映射模板” :在这里,您将定义模板,该模板将应用于符合第一步中定义的数据模型的输入数据,并将其转换为最终目标所需的XML。

#set($inputRoot = $input.path('$'))
<soap12:Envelope xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="https://www.w3.org/2001/XMLSchema" xmlns:soap12="https://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
	<ConvertTemp xmlns="https://www.webserviceX.NET/">
		<Temperature>$inputRoot.Temperature</Temperature>
		<FromUnit>$inputRoot.FromUnit</FromUnit>
		<ToUnit>$inputRoot.ToUnit</ToUnit>
	</ConvertTemp>
</soap12:Body>
</soap12:Envelope>

The variable $inputRoot defined in the first line represents the root of the JSON data which you can use to traverse inside the data.

第一行中定义的变量$ inputRoot表示JSON数据的根,可用于遍历数据内部。

The Result: This set of model and the mapping template will convert the temperature data in JSON format to the XML expected by the end target. And a JSON input like:

结果 :这组模型和映射模板会将JSON格式的温度数据转换为最终目标所需的XML。 和JSON输入类似:

{
    	"Temperature" : 123,
	"FromUnit" : "degreeCelsius",
	"ToUnit" : "degreeFahrenheit"
}

Will be converted into an XML input like this:

将被转换成这样的XML输入:

<soap12:Envelope xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="https://www.w3.org/2001/XMLSchema" xmlns:soap12="https://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
	<ConvertTemp xmlns="https://www.webserviceX.NET/">
		<Temperature>123</Temperature>
		<FromUnit>degreeCelsius</FromUnit>
		<ToUnit>degreeFahrenheit</ToUnit>
	</ConvertTemp>
</soap12:Body>
</soap12:Envelope>

Apart from converting the data to XML, you can convert it to any other format you want. E.g. in the section – Integrating your Lambda function with the API Gateway, I’ve taken an example to convert a JSON data to a simple integer value which is expected by the Lambda function written in Java.

除了将数据转换为XML外,您还可以将其转换为所需的任何其他格式。 例如,在“将Lambda函数与API网关集成在一起”部分中,我以一个示例将JSON数据转换为Java编写的Lambda函数期望的简单整数值为例。

Deploy the API: After creating the API, its resources and methods, its available for testing through the AWS console. To expose it to your end users, deploy the API to any stage like ‘Testing’ or ‘Production’ or any other stage that makes sense for your project and you’ll get a public URL which you can provide to your end users to call.

部署API :创建API,其资源和方法之后,即可通过AWS控制台进行测试。 要将其公开给最终用户,请将API部署到“测试”或“生产”等任何阶段,或者对项目有意义的任何其他阶段,您都会获得一个公共URL,您可以将其提供给最终用户进行调用。

While deploying an API, you can enable the cache to further improve performance, enable CloudWatch logs and metrics to monitor the API performance, the ‘Throttling’ Settings to control the traffic on your API before it becomes the bottleneck for your back-end and any client certificate if the Amazon API needs one to connect to your end target.

在部署API时,您可以启用缓存以进一步提高性能,启用CloudWatch日志和指标以监视API性能,使用“限制”设置来控制API上的流量,然后再成为后端和任何其他设备的瓶颈客户端证书(如果Amazon API需要一个证书来连接到您的最终目标)。

优点 (Advantages)

  • Deploy APIs without having to manage servers

    无需管理服务器即可部署API
  • Monitor and ‘Throttle’ requests and protect your back-end

    监视和“限制”请求并保护您的后端
  • Achieve better performance levels by utilizing AWS Cache

    通过利用AWS缓存获得更高的性能水平
  • Achieve reduced latency and protection against Distributed Denial of Server (DDoS) through Amazon CloudFront, ensure high scalability and availability

    通过Amazon CloudFront减少延迟并保护其免受分布式拒绝服务器(DDoS)的影响,确保高可扩展性和可用性
  • Re-package existing API (change its request/response structure and customize headers) without re-writing, though with limited capabilities

    重新包装现有的API(更改其请求/响应结构并自定义标头),而无需重写,但功能有限
  • Authorize developers to handle APIs through API keys

    授权开发人员通过API密钥处理API
  • Manage multiple versions of the same API

    管理同一API的多个版本
  • Deploy into multiple stages

    部署到多个阶段
  • Utilize AWS lambda – if you don’t want to have dedicated servers (EC2 Instances) to keep your business logic

    利用AWS Lambda –如果您不想拥有专用服务器(EC2实例)来保持业务逻辑
  • Have custom domain names for your APIs

    为您的API有自定义域名
  • No cost of deploying the API, pay only for the API calls and the amount of data it sends out.

    无需部署API,只需支付API调用及其发出的数据量。
  • Generate SDKs for Android, iOS and JavaScript

    生成适用于Android,iOS和JavaScript的SDK
  • Low learning curve, integration with other Cloud Services has added advantage for existing users of those services

    学习曲线低,与其他Cloud Services集成为这些服务的现有用户增加了优势

局限性 (Limitations)

While building a few APIs for my POC, I encountered a big restriction on transformation capabilities. Though the documents at Amazon claim that the requests and responses can be converted from JSON to XML and vice versa, but I found the conversion to be working only one way. The possible conversion is:

在为POC构建一些API时,我遇到了对转换功能的很大限制。 尽管亚马逊上的文档声称可以将请求和响应从JSON转换为XML,反之亦然,但是我发现这种转换仅是一种方法。 可能的转换是:

  • Receive JSON input and convert to XML to send it to your XML-based back-end

    接收JSON输入并转换为XML,以将其发送到基于XML的后端
  • Receive JSON from your back-end (lambda function or any public API) and convert to XML to return to the end user

    从后端(lambda函数或任何公共API)接收JSON,并转换为XML以返回给最终用户

I really missed the ability to convert an XML response to a JSON format. Why I think it is required is, because if my existing legacy system takes XML as an input, it most likely will return XML as an output. So, if I want to re-package my legacy application to provide support for JSON (a feature highlighted by the documentation), I can only make it work one way – I can take a JSON as input and convert it to XML for my legacy application (which would sit at the back-end of the API Gateway) but I cannot transform the XML returned by my legacy application to a JSON response, because there seems to be no way to convert an XML response to JSON, if I didn’t miss any important detail.

我真的很想不能将XML响应转换为JSON格式。 我之所以认为这是必需的,是因为如果我现有的旧系统将XML作为输入,则很可能会将XML作为输出。 因此,如果我想重新打包我的旧应用程序以提供对JSON(文档中突出显示的功能)的支持,我只能使其工作一种方式–我可以将JSON作为输入并将其转换为XML以用于我的旧版应用程序(位于API网关的后端),但是我无法将遗留应用程序返回的XML转换为JSON响应,因为如果没有的话,似乎没有办法将XML响应转换为JSON。不要错过任何重要的细节。

集成AWS服务 (Integrated AWS Services)

  • AWS Identity and Access Management – to authorize access to APIs

    AWS Identity and Access Management –授权对API的访问
  • Amazon CloudFront to manage API traffic

    Amazon CloudFront管理API流量
  • Amazon CloudWatch – for analysis – have a look at the out of the box metrics provided by CloudWatch on a console

    Amazon CloudWatch –用于分析–查看由CloudWatch在控制台上提供的现成指标
  • AWS Lambda – create your back-ends without managing servers

    AWS Lambda –在不管理服务器的情况下创建后端
  • Amazon Cognito

    亚马逊Cognito

什么是AWS Lambda函数? (What is AWS Lambda Function?)

Lambda is a compute service provided by Amazon that lets you upload your code/business logic to the AWS infrastructure and manages it. The code that you upload is called the ‘Lambda Function’. Once uploaded, you don’t need to manage the servers required to run your code. You can run this code –

Lambda是Amazon提供的计算服务,可让您将代码/业务逻辑上载到AWS基础架构并进行管理。 您上传的代码称为“ Lambda函数”。 上传后,您无需管理运行代码所需的服务器。 您可以运行此代码–

  • As an event driven service which triggers on some change like a change in the data of an S3 bucket or a Dynamo DB table.

    作为事件驱动的服务,它会触发某些更改,例如S3存储桶或Dynamo DB表的数据更改。
  • As the back-end of an AWS API gateway

    作为AWS API网关的后端

I have focused on the second use case here.

我在这里专注于第二个用例。

将您的第一个基于Java的AWS Lambda Function与AWS API Gateway集成 (Integrate you first Java-based AWS Lambda Function with AWS API Gateway)

In the AWS document, it’s clear how to create your first Java-based Lambda function. As a separate activity, calling a Lambda function through the AWS API Gateway is also described in easy to follow steps.

在AWS文档中,很清楚如何创建您的第一个基于Java的Lambda函数。 作为单独的活动,通过简单的步骤还介绍了通过AWS API Gateway调用Lambda函数。

But the problem that I faced, is to integrate both these activities, i.e. to write a java based Lambda function and then call it through the API Gateway, the reason being the AWS documentation’s focus on JSON. From the present documentation, it’s easy to deploy and test your API or a Lambda function if it takes JSON as input and gives JSON back, but it is not easy, at least not directly, to create an API in the gateway that has a Lambda function as it’s backend but does not take JSON as its input.

但是我面临的问题是集成这两个活动,即编写基于Java的Lambda函数,然后通过API网关调用它,原因是AWS文档着重于JSON。 根据当前文档,如果将JSON作为输入并返回JSON,则很容易部署和测试您的API或Lambda函数,但是要在具有Lambda的网关中创建API并非易事,至少不是直接这样做作为后端运行,但不使用JSON作为输入。

Below I am presenting an example of a JSON data Model and the Mapping Template I used to convert the JSON input to a simple integer value which was the input of my java based Lambda Function.

下面,我将提供一个JSON数据模型和映射模板的示例,该示例用于将JSON输入转换为一个简单的整数值,该值是基于Java的Lambda函数的输入。

Model:
{
  "$schema": "https://json-schema.org/draft-04/schema#", 
  "title": "SimpleInputModel",
  "type": "object",
  "properties": {
    "myCount": { "type": "integer" }
	}
}

Mapping Template:

映射模板:

#set($inputRoot = $input.path('$'))
"$inputRoot.myCount"

This mapping template converted the JSON data:

此映射模板转换了JSON数据:

{
    "myCount" : "1234"
}

to a simple integer value – 1234 which I passed to my java based Lambda function.

到一个简单的整数值– 1234,该值传递给基于Java的Lambda函数。

That’s all for now, we will look into more AWS features in coming posts.

到此为止,我们将在以后的文章中探讨更多的AWS功能。

翻译自: https://www.journaldev.com/10113/aws-api-gateway-and-aws-lambda-example

aws lambda

 类似资料: