1. Overview
1.概述
AWS Lambda is a serverless computing service provided by Amazon Web Services.
AWS Lambda是由Amazon Web Services提供的无服务器计算服务。
In two previous articles, we discussed how to create an AWS Lambda function using Java, as well as how to access DynamoDB from a Lambda function.
在之前的两篇文章中,我们讨论了如何使用 Java 创建 AWS Lambda 函数,以及如何从 Lambda 函数访问 DynamoDB。
In this tutorial, we’ll discuss how to publish a Lambda function as a REST endpoint, using AWS Gateway.
在本教程中,我们将讨论如何使用AWS Gateway将Lambda函数作为REST端点发布。
We’ll have a detailed look at the following topics:
我们将详细了解以下主题。
- Basic concepts and terms of API Gateway
- Integration of Lambda functions with API Gateway using Lambda Proxy integration
- Creation of an API, its structure, and how to map the API resources onto Lambda functions
- Deployment and test of the API
2. Basics and Terms
2.基础知识和术语
API Gateway is a fully managed service that enables developers to create, publish, maintain, monitor, and secure APIs at any scale.
API网关是一种完全管理的服务,使开发人员能够以任何规模创建、发布、维护、监控和保护API。
We can implement a consistent and scalable HTTP-based programming interface (also referred to as RESTful services) to access backend services like Lambda functions, further AWS services (e.g., EC2, S3, DynamoDB), and any HTTP endpoints.
我们可以实现一个一致的、可扩展的基于HTTP的编程接口(也被称为RESTful服务)访问后端服务,如Lambda函数、进一步的AWS服务(如EC2、S3、DynamoDB),以及任何HTTP端点。
Features include, but are not limited to:
特点包括但不限于:。
- Traffic management
- Authorization and access control
- Monitoring
- API version management
- Throttling requests to prevent attacks
Like AWS Lambda, API Gateway is automatically scaled out and is billed per API call.
与AWS Lambda一样,API Gateway是自动扩展的,并按API调用计费。
Detailed information can be found in the official documentation.
详细信息可以在官方文档中找到。
2.1. Terms
2.1.术语
API Gateway is an AWS service that supports creating, deploying, and managing a RESTful application programming interface to expose backend HTTP endpoints, AWS Lambda functions, and other AWS services.
API Gateway是一项AWS服务,支持创建、部署和管理RESTful应用程序编程接口,以暴露后端HTTP端点、AWS Lambda函数和其他AWS服务。
An API Gateway API is a collection of resources and methods that can be integrated with Lambda functions, other AWS services, or HTTP endpoints in the backend. The API consists of resources that form the API structure. Each API resource can expose one or more API methods that must have unique HTTP verbs.
API Gateway API是资源和方法的集合,可与Lambda函数、其他AWS服务或后端HTTP端点集成。该API由构成API结构的资源组成。每个API资源可以暴露一个或多个API方法,这些方法必须有独特的HTTP动词。
To publish an API, we have to create an API deployment and associate it with a so-called stage. A stage is like a snapshot in time of the API. If we redeploy an API, we can either update an existing stage or create a new one. By that, different versions of an API at the same time are possible, for example a dev stage, a test stage, and even multiple production versions, like v1, v2, etc.
为了发布API,我们必须创建一个API部署,并将其与所谓的stage相关联。一个阶段就像API的一个时间快照。如果我们重新部署一个API,我们可以更新现有的阶段或创建一个新的阶段。这样一来,API的不同版本就有可能同时出现,例如,dev阶段、test阶段,甚至多个生产版本,如v1、v2等。
Lambda Proxy integration is a simplified configuration for the integration between Lambda functions and API Gateway.
Lambda Proxy集成是Lambda函数和API Gateway之间集成的简化配置。
The API Gateway sends the entire request as an input to a backend Lambda function. Response-wise, API Gateway transforms the Lambda function output back to a frontend HTTP response.
API Gateway将整个请求作为输入发送到后端Lambda函数。响应方面,API Gateway将Lambda函数的输出转换为前端的HTTP响应。
3. Dependencies
3.依赖性
We’ll need the same dependencies as in the AWS Lambda Using DynamoDB With Java article.
我们需要与AWS Lambda Using DynamoDB With Java文章中的依赖关系相同。
On top of that, we also need the JSON Simple library:
在此基础上,我们还需要JSON Simple库。
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
4. Developing and Deploying the Lambda Functions
4.开发和部署Lambda函数
In this section, we’ll develop and build our Lambda functions in Java, we’ll deploy it using AWS Console, and we’ll run a quick test.
在本节中,我们将用Java开发和构建我们的Lambda函数,我们将使用AWS控制台进行部署,并运行一个快速测试。
As we want to demonstrate the basic capabilities of integrating API Gateway with Lambda, we’ll create two functions:
由于我们要演示将API Gateway与Lambda集成的基本功能,我们将创建两个函数。
- Function 1: receives a payload from the API, using a PUT method
- Function 2: demonstrates how to use an HTTP path parameter or HTTP query parameter coming from the API
Implementation-wise, we’ll create one RequestHandler class, which has two methods — one for each function.
在实现上,我们将创建一个RequestHandler类,它有两个方法–每个函数一个。
4.1. Model
4.1.模型
Before we implement the actual request handler, let’s have a quick look at our data model:
在我们实现实际的请求处理程序之前,让我们快速看一下我们的数据模型。
public class Person {
private int id;
private String name;
public Person(String json) {
Gson gson = new Gson();
Person request = gson.fromJson(json, Person.class);
this.id = request.getId();
this.name = request.getName();
}
public String toString() {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(this);
}
// getters and setters
}
Our model consists of one simple Person class, which has two properties. The only notable part is the Person(String) constructor, which accepts a JSON String.
我们的模型由一个简单的Person类组成,它有两个属性。唯一值得注意的部分是Person(String)构造函数,它接受一个JSON字符串。
4.2. Implementation of the RequestHandler Class
4.2.RequestHandler类的实现
Just like in the AWS Lambda With Java article, we’ll create an implementation of the RequestStreamHandler interface:
就像在AWS Lambda With Java文章中一样,我们将创建一个RequestStreamHandler接口的实现。
public class APIDemoHandler implements RequestStreamHandler {
private static final String DYNAMODB_TABLE_NAME = System.getenv("TABLE_NAME");
@Override
public void handleRequest(
InputStream inputStream, OutputStream outputStream, Context context)
throws IOException {
// implementation
}
public void handleGetByParam(
InputStream inputStream, OutputStream outputStream, Context context)
throws IOException {
// implementation
}
}
As we can see, the RequestStreamHander interface defines only one method, handeRequest(). Anyhow, we can define further functions in the same class, as we’ve done here. Another option would be to create one implementation of RequestStreamHander for each function.
我们可以看到,RequestStreamHander接口只定义了一个方法,handeRequest()。无论如何,我们可以在同一个类中定义更多的函数,就像我们在这里做的那样。另一个选择是为每个函数创建一个RequestStreamHander的实现。
In our specific case, we chose the former for simplicity. However, the choice must be made on a case-by-case basis, taking into consideration such factors as performance and code maintainability.
在我们的具体案例中,为了简单起见,我们选择了前者。然而,选择必须在个案的基础上进行,考虑到性能和代码可维护性等因素。
We also read the name of our DynamoDB table from the TABLE_NAME environment variable. We’ll define that variable later during deployment.
我们还从TABLE_NAME 环境变量中读取我们DynamoDB表的名称。我们将在以后的部署中定义该变量。
4.3. Implementation of Function 1
4.3.函数1的实现
In our first function, we want to demonstrate how to get a payload (like from a PUT or POST request) from the API Gateway:
在我们的第一个函数中,我们要演示如何从API网关获得一个有效载荷(如从PUT或POST请求)。
public void handleRequest(
InputStream inputStream,
OutputStream outputStream,
Context context)
throws IOException {
JSONParser parser = new JSONParser();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
JSONObject responseJson = new JSONObject();
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient();
DynamoDB dynamoDb = new DynamoDB(client);
try {
JSONObject event = (JSONObject) parser.parse(reader);
if (event.get("body") != null) {
Person person = new Person((String) event.get("body"));
dynamoDb.getTable(DYNAMODB_TABLE_NAME)
.putItem(new PutItemSpec().withItem(new Item().withNumber("id", person.getId())
.withString("name", person.getName())));
}
JSONObject responseBody = new JSONObject();
responseBody.put("message", "New item created");
JSONObject headerJson = new JSONObject();
headerJson.put("x-custom-header", "my custom header value");
responseJson.put("statusCode", 200);
responseJson.put("headers", headerJson);
responseJson.put("body", responseBody.toString());
} catch (ParseException pex) {
responseJson.put("statusCode", 400);
responseJson.put("exception", pex);
}
OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
writer.write(responseJson.toString());
writer.close();
}
As discussed before, we’ll configure the API later to use Lambda proxy integration. We expect the API Gateway to pass the complete request to the Lambda function in the InputStream parameter.
正如之前所讨论的,我们稍后将配置API以使用Lambda代理集成。我们希望API Gateway在InputStream参数中向Lambda函数传递完整的请求。
All we have to do is to pick the relevant attributes from the contained JSON structure.
我们所要做的是,从包含的JSON结构中挑选相关的属性。
As we can see, the method basically consists of three steps:
我们可以看到,该方法基本上包括三个步骤。
- Fetching the body object from our input stream and creating a Person object from that
- Storing that Person object in a DynamoDB table
- Building a JSON object, which can hold several attributes, like a body for the response, custom headers, as well as an HTTP status code
One point worth mentioning here: API Gateway expects the body to be a String (for both request and response).
这里有一点值得一提。API Gateway希望body是一个String(对于请求和响应)。
As we expect to get a String as body from the API Gateway, we cast the body to String and initialize our Person object:
由于我们期望从API Gateway获得一个String作为body,我们将body转换为String并初始化我们的Person对象。
Person person = new Person((String) event.get("body"));
API Gateway also expects the response body to be a String:
API Gateway还希望响应body是一个String。
responseJson.put("body", responseBody.toString());
This topic is not mentioned explicitly in the official documentation. However, if we have a close look, we can see that the body attribute is a String in both snippets for the request as well as for the response.
这个话题在官方文档中没有明确提及。然而,如果我们仔细观察,我们可以看到在请求和响应两个片段中,body属性都是一个String。
The advantage should be clear: even if JSON is the format between API Gateway and the Lambda function, the actual body can contain plain text, JSON, XML, or whatever. It is then the responsibility of the Lambda function to handle the format correctly.
优势应该很明显:即使JSON是API Gateway和Lambda函数之间的格式,实际的主体也可以包含纯文本、JSON、XML或其他。然后,Lambda函数有责任正确地处理这种格式。
We’ll see how the request and response body look later when we test our functions in the AWS Console.
稍后,当我们在AWS控制台测试我们的功能时,我们将看到请求和响应体的样子。
The same also applies to the following two functions.
这一点也适用于以下两个功能。
4.4. Implementation of Function 2
4.4.函数2的实施
In a second step, we want to demonstrate how to use a path parameter or a query string parameter for retrieving a Person item from the database using its ID:
第二步,我们要演示如何使用路径参数或查询字符串参数从数据库中使用其ID检索Person项目。
public void handleGetByParam(
InputStream inputStream, OutputStream outputStream, Context context)
throws IOException {
JSONParser parser = new JSONParser();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
JSONObject responseJson = new JSONObject();
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient();
DynamoDB dynamoDb = new DynamoDB(client);
Item result = null;
try {
JSONObject event = (JSONObject) parser.parse(reader);
JSONObject responseBody = new JSONObject();
if (event.get("pathParameters") != null) {
JSONObject pps = (JSONObject) event.get("pathParameters");
if (pps.get("id") != null) {
int id = Integer.parseInt((String) pps.get("id"));
result = dynamoDb.getTable(DYNAMODB_TABLE_NAME).getItem("id", id);
}
} else if (event.get("queryStringParameters") != null) {
JSONObject qps = (JSONObject) event.get("queryStringParameters");
if (qps.get("id") != null) {
int id = Integer.parseInt((String) qps.get("id"));
result = dynamoDb.getTable(DYNAMODB_TABLE_NAME)
.getItem("id", id);
}
}
if (result != null) {
Person person = new Person(result.toJSON());
responseBody.put("Person", person);
responseJson.put("statusCode", 200);
} else {
responseBody.put("message", "No item found");
responseJson.put("statusCode", 404);
}
JSONObject headerJson = new JSONObject();
headerJson.put("x-custom-header", "my custom header value");
responseJson.put("headers", headerJson);
responseJson.put("body", responseBody.toString());
} catch (ParseException pex) {
responseJson.put("statusCode", 400);
responseJson.put("exception", pex);
}
OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
writer.write(responseJson.toString());
writer.close();
}
Again, three steps are relevant:
同样,有三个步骤是相关的。
- We check whether a pathParameters or an queryStringParameters array with an id attribute are present.
- If true, we use the belonging value to request a Person item with that ID from the database.
- We add a JSON representation of the received item to the response.
The official documentation provides a more detailed explanation of input format and output format for Proxy Integration.
4.5. Building Code
4.5.建筑法规
Again, we can simply build our code using Maven:
同样,我们可以简单地用Maven构建我们的代码。
mvn clean package shade:shade
The JAR file will be created under the target folder.
JAR文件将在target文件夹下创建。
4.6. Creating the DynamoDB Table
4.6.创建DynamoDB表
We can create the table as explained in AWS Lambda Using DynamoDB With Java.
我们可以按照AWS Lambda Using DynamoDB With Java中的解释创建表。
Let’s choose Person as table name, id as primary key name, and Number as type of the primary key.
让我们选择Person作为表名,id作为主键名,Number作为主键的类型。
4.7. Deploying Code via AWS Console
4.7.通过AWS控制台部署代码
After building our code and creating the table, we can now create the functions and upload the code.
在建立我们的代码和创建表格后,我们现在可以创建函数并上传代码。
This can be done by repeating steps 1-5 from the AWS Lambda with Java article, one time for each of our two methods.
这可以通过重复AWS Lambda with Java文章中的步骤1-5来完成,对我们的两种方法各进行一次。
Let’s use the following function names:
让我们使用以下函数名称。
- StorePersonFunction for the handleRequest method (function 1)
- GetPersonByHTTPParamFunction for the handleGetByParam method (function 2)
We also have to define an environment variable TABLE_NAME with value “Person”.
我们还必须定义一个环境变量TABLE_NAME,值为“Person”。
4.8. Testing the Functions
4.8.测试函数
Before continuing with the actual API Gateway part, we can run a quick test in the AWS Console, just to check that our Lambda functions are running correctly and can handle the Proxy Integration format.
在继续进行实际的API网关部分之前,我们可以在AWS控制台中运行一个快速测试,只是为了检查我们的Lambda函数是否正常运行,并能处理代理集成格式。
Testing a Lambda function from the AWS Console works as described in AWS Lambda with Java article.
如AWS Lambda with Java文章中所述,从AWS控制台测试Lambda函数。
However, when we create a test event, we have to consider the special Proxy Integration format, which our functions are expecting. We can either use the API Gateway AWS Proxy template and customize that for our needs, or we can copy and paste the following events:
然而,当我们创建一个测试事件时,我们必须考虑特殊的代理集成格式,我们的函数正在期待这个格式。我们可以使用API Gateway AWS Proxy模板并根据我们的需要进行定制,或者我们可以复制并粘贴以下事件。
For the StorePersonFunction, we should use this:
对于StorePersonFunction,我们应该使用这个。
{
"body": "{\"id\": 1, \"name\": \"John Doe\"}"
}
As discussed before, the body must have the type String, even if containing a JSON structure. The reason is that the API Gateway will send its requests in the same format.
如前所述,body必须具有String类型,即使是包含JSON结构。原因是,API网关将以相同的格式发送其请求。
The following response should be returned:
应返回以下响应。
{
"isBase64Encoded": false,
"headers": {
"x-custom-header": "my custom header value"
},
"body": "{\"message\":\"New item created\"}",
"statusCode": 200
}
Here, we can see that the body of our response is a String, although it contains a JSON structure.
在这里,我们可以看到我们响应的body是一个String,尽管它包含一个JSON结构。
Let’s look at the input for the GetPersonByHTTPParamFunction.
让我们看看GetPersonByHTTPParamFunction.的输入。
For testing the path parameter functionality, the input would look like this:
对于测试路径参数的功能,输入会是这样的。
{
"pathParameters": {
"id": "1"
}
}
And the input for sending a query string parameter would be:
而发送查询字符串参数的输入将是。
{
"queryStringParameters": {
"id": "1"
}
}
As a response, we should get the following for both cases methods:
作为回应,我们应该对两种情况下的方法得到以下结果。
{
"headers": {
"x-custom-header": "my custom header value"
},
"body": "{\"Person\":{\n \"id\": 88,\n \"name\": \"John Doe\"\n}}",
"statusCode": 200
}
Again, the body is a String.
同样,body是一个String。
5. Creating and Testing the API
5.创建和测试API
After we created and deployed the Lambda functions in the previous section, we can now create the actual API using the AWS Console.
在上一节中我们创建并部署了Lambda函数后,我们现在可以使用AWS控制台创建实际的API。
Let’s look at the basic workflow:
让我们来看看基本的工作流程。
- Create an API in our AWS account.
- Add a resource to the resources hierarchy of the API.
- Create one or more methods for the resource.
- Set up the integration between a method and the belonging Lambda function.
We’ll repeat steps 2-4 for each of our two functions in the following sections.
我们将在下面的章节中为我们的两个函数分别重复步骤2-4。
5.1. Creating the API
5.1.创建API
For creating the API, we’ll have to:
对于创建API,我们必须。
- Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway
- Click on “Get Started” and then select “New API”
- Type in the name of our API (TestAPI) and acknowledge by clicking on “Create API”
Having created the API, we can now create the API structure and link it to our Lambda functions.
在创建了API之后,我们现在可以创建API结构,并将其链接到我们的Lambda函数。
5.2. API Structure for Function 1
5.2.功能1的API结构
The following steps are necessary for our StorePersonFunction:
以下步骤对我们的StorePersonFunction是必要的。
- Choose the parent resource item under the “Resources” tree and then select “Create Resource” from the “Actions” drop-down menu. Then, we have to do the following in the “New Child Resource” pane:
- Type “Persons” as a name in the “Resource Name” input text field
- Leave the default value in the “Resource Path” input text field
- Choose “Create Resource”
- Choose the resource just created, choose “Create Method” from the “Actions” drop-down menu, and carry out the following steps:
- Choose PUT from the HTTP method drop-down list and then choose the check mark icon to save the choice
- Leave “Lambda Function” as integration type, and select the “Use Lambda Proxy integration” option
- Choose the region from “Lambda Region”, where we deployed our Lambda functions before
- Type “StorePersonFunction” in “Lambda Function”
- Choose “Save” and acknowledge with “OK” when prompted with “Add Permission to Lambda Function”
5.3. API Structure for Function 2 – Path Parameters
5.3.函数2的API结构–路径参数
The steps for our retrieving path parameters are similar:
我们检索路径参数的步骤是类似的。
- Choose the /persons resource item under the “Resources” tree and then select “Create Resource” from the “Actions” drop-down menu. Then, we have to do the following in the New Child Resource pane:
- Type “Person” as a name in the “Resource Name” input text field
- Change the “Resource Path” input text field to “{id}”
- Choose “Create Resource”
- Choose the resource just created, select “Create Method” from the “Actions” drop-down menu, and carry out the following steps:
- Choose GET from the HTTP method drop-down list and then choose the check mark icon to save the choice
- Leave “Lambda Function” as integration type, and select the “Use Lambda Proxy integration” option
- Choose the region from “Lambda Region”, where we deployed our Lambda functions before
- Type “GetPersonByHTTPParamFunction” in “Lambda Function”
- Choose “Save” and acknowledge with “OK” when prompted with “Add Permission to Lambda Function”
Note: it is important here to set the “Resource Path” parameter to “{id}”, as our GetPersonByPathParamFunction expects this parameter to be named exactly like this.
注意:在这里将 “资源路径 “参数设置为“{id}”很重要,因为我们的GetPersonByPathParamFunction希望这个参数的命名与此完全一致。
5.4. API Structure for Function 2 – Query String Parameters
5.4.函数2的API结构–查询字符串参数
The steps for receiving query string parameters are a bit different, as we don’t have to create a resource, but instead have to create a query parameter for the id parameter:
接收查询字符串参数的步骤有点不同,因为我们不需要创建一个资源,而是要为id参数创建一个查询参数。
- Choose the /persons resource item under the “Resources” tree, select “Create Method” from the “Actions” drop-down menu, and carry out the following steps:
- Choose GET from the HTTP method drop-down list and then select the checkmark icon to save the choice
- Leave “Lambda Function” as integration type, and select the “Use Lambda Proxy integration” option
- Choose the region from “Lambda Region”, where we deployed our Lambda functions before
- Type “GetPersonByHTTPParamFunction” in “Lambda Function”.
- Choose “Save” and acknowledge with “OK” when prompted with “Add Permission to Lambda Function”
- Choose “Method Request” on the right and carry out the following steps:
- Expand the URL Query String Parameters list
- Click on “Add Query String”
- Type “id” in the name field, and choose the check mark icon to save
- Select the “Required” checkbox
- Click on the pen symbol next to “Request validator” on the top of the panel, select “Validate query string parameters and headers”, and choose the check mark icon
Note: It is important to set the “Query String” parameter to “id”, as our GetPersonByHTTPParamFunction expects this parameter to be named exactly like this.
注意:将 “查询字符串 “参数设置为“id”很重要,因为我们的GetPersonByHTTPParamFunction希望这个参数的名称与此完全一致。
5.5. Testing the API
5.5.测试API
Our API is now ready, but it’s not public yet. Before we publish it, we want to run a quick test from the Console first.
我们的API现在已经准备好了,但它还没有公开。在我们发布它之前,我们想先从控制台运行一个快速测试。
For that, we can select the respective method to be tested in the “Resources” tree and click on the “Test” button. On the following screen, we can type in our input, as we would send it with a client via HTTP.
为此,我们可以在 “资源 “树中选择各自要测试的方法,然后点击 “测试 “按钮。在下面的屏幕上,我们可以键入我们的输入,就像我们通过HTTP向客户端发送一样。
For StorePersonFunction, we have to type the following structure into the “Request Body” field:
对于StorePersonFunction,我们必须在 “Request Body “字段中输入以下结构。
{
"id": 2,
"name": "Jane Doe"
}
For the GetPersonByHTTPParamFunction with path parameters, we have to type 2 as a value into the “{id}” field under “Path”.
对于带有路径参数的GetPersonByHTTPParamFunction,我们必须在 “路径 “下的”{id}”字段中输入2作为一个值。
For the GetPersonByHTTPParamFunction with query string parameters, we have to type id=2 as a value into the “{persons}” field under “Query Strings”.
对于带有查询字符串参数的GetPersonByHTTPParamFunction,我们必须将id=2作为一个值输入 “查询字符串 “下的”{persons}”字段。
5.6. Deploying the API
5.6.部署API
Up to now, our API wasn’t public and thereby was only available from the AWS Console.
到目前为止,我们的API并不公开,因此只能从AWS控制台获得。
As discussed before, when we deploy an API, we have to associate it with a stage, which is like a snapshot in time of the API. If we redeploy an API, we can either update an existing stage or create a new one.
正如之前所讨论的,当我们部署一个API时,我们必须将其与一个阶段联系起来,这就像API的时间快照。如果我们重新部署一个API,我们可以更新现有的阶段或创建一个新的阶段。
Let’s see how the URL scheme for our API will look:
让我们看看我们的API的URL方案会是什么样子。
https://{restapi-id}.execute-api.{region}.amazonaws.com/{stageName}
The following steps are required for deployment:
部署时需要采取以下步骤。
- Choose the particular API in the “APIs” navigation pane
- Choose “Actions” in the Resources navigation pane and select “Deploy API” from the “Actions” drop-down menu
- Choose “[New Stage]” from the “Deployment stage” drop-down, type “test” in “Stage name”, and optionally provide a description of the stage and deployment
- Trigger the deployment by choosing “Deploy”
After the last step, the console will provide the root URL of the API, for example, https://0skaqfgdw4.execute-api.eu-central-1.amazonaws.com/test.
最后一步之后,控制台将提供API的根URL,例如,https://0skaqfgdw4.execute-api.eu-central-1.amazonaws.com/test。
5.7. Invoking the Endpoint
5.7.调用端点
As the API is public now, we can call it using any HTTP client we want.
由于该API现在是公开的,我们可以使用任何我们想要的HTTP客户端调用它。
With cURL, the calls would look like as follows.
使用cURL,调用将看起来如下。
StorePersonFunction:
StorePersonFunction。
curl -X PUT 'https://0skaqfgdw4.execute-api.eu-central-1.amazonaws.com/test/persons' \
-H 'content-type: application/json' \
-d '{"id": 3, "name": "Richard Roe"}'
GetPersonByHTTPParamFunction for path parameters:
GetPersonByHTTPParamFunction为路径参数。
curl -X GET 'https://0skaqfgdw4.execute-api.eu-central-1.amazonaws.com/test/persons/3' \
-H 'content-type: application/json'
GetPersonByHTTPParamFunction for query string parameters:
GetPersonByHTTPParamFunction用于查询字符串参数。
curl -X GET 'https://0skaqfgdw4.execute-api.eu-central-1.amazonaws.com/test/persons?id=3' \
-H 'content-type: application/json'
6. Conclusion
6.结论
In this article, we had a look how to make AWS Lambda functions available as REST endpoints, using AWS API Gateway.
在这篇文章中,我们看了如何使用AWS API Gateway使AWS Lambda函数作为REST端点可用。
We explored the basic concepts and terminology of API Gateway, and we learned how to integrate Lambda functions using Lambda Proxy Integration.
我们探讨了API网关的基本概念和术语,并学习了如何使用Lambda Proxy Integration来整合Lambda函数。
Finally, we saw how to create, deploy, and test an API.
最后,我们看到如何创建、部署和测试一个API。
As usual, all the code for this article is available over on GitHub.
像往常一样,本文的所有代码都可以在GitHub上获得。