lambda 使用_如何使用Lambda和API网关构建API

lambda 使用

Do you want to access your database, control your system, or execute some code from another website? An API can do all of this for you, and they’re surprisingly easy to set up.

您是否要访问数据库,控制系统或从其他网站执行一些代码? API可以为您完成所有这些工作,而且它们设置起来非常简单。

An API is a URL that you can perform GET, PUT, POST, and DELETE requests on to control another service. If you make one yourself, then you can build these APIs to do whatever you want behind the scenes. Common uses are providing database control, performing actions on third-party APIs (API-ception), or controlling another service.

API是可以执行GET PUT POSTDELETE的URL 请求控制其他服务。 如果您自己创建,则可以构建这些API,以在后台执行您想做的任何事情。 常见用途是提供数据库控制,对第三方API执行操作(API接收)或控制其他服务。

为什么要使用API​​? (Why use an API?)

You may ask why we need an API when we can access the database directly or run the code on the website. There are a few massive advantages to APIs over running the code in your website.

您可能会问,当我们可以直接访问数据库或在网站上运行代码时,为什么需要API。 与在您的网站中运行代码相比,API有许多巨大的优势。

隐藏您的访问密钥和令牌 (Hide your access keys and tokens)

This is possibly the most important reason to use an API. If you are accessing a database, then you’re going to need the database details as well as user and access token/key data.

这可能是使用API​​的最重要原因 。 如果要访问数据库,则将需要数据库详细信息以及用户和访问令牌/密钥数据。

If you access the database from the website, then you’re going to have all of these details in the source code of your site. This is really bad practice, as anyone can look into the source control and steal your details. This doesn’t sound too bad, but what if these are your AWS or Google Cloud Compute credentials? The people accessing your site could then use these to run whatever they want on your account, leaving you with a huge bill.

如果您从网站访问数据库,那么您将在网站的源代码中包含所有这些详细信息。 这是一种非常糟糕的做法,因为任何人都可以调查源代码控制并窃取您的详细信息。 听起来还不错,但是如果这些是您的AWS或Google Cloud Compute凭证怎么办? 然后,访问您网站的人可以使用它们来运行他们想要在您的帐户上进行的操作,从而给您带来巨额费用。

Running these processes from behind an API means no one can see any of the private details — they can’t steal them to use in their own projects. If you store your website code in GitHub or another public source control, then it also means that they aren’t visible there, either.

从API后面运行这些进程意味着没有人可以看到任何私有细节-他们无法窃取它们以用于自己的项目。 如果您将网站代码存储在GitHub或其他公共源代码控件中,那么这也意味着它们在此处也不可见。

在其他地方运行代码 (Run the code elsewhere)

What if you aren’t using any other services and aren’t using any secret keys? If you are running a large or complex bit of code, or if you don’t want anyone else reading your code and discovering how it works, then you can still use an API.

如果您不使用任何其他服务并且不使用任何秘密密钥怎么办? 如果您正在运行大量或复杂的代码,或者不希望其他人阅读您的代码并发现其工作原理,那么仍然可以使用API​​。

控制谁有权访问 (Control who has access)

Providing an API also allows you to restrict who is able to access the database or run the code. You can do this by requiring an API key. This key is used to identify the user making the request, and then allowing or rejecting the request.

提供API还可以使您限制谁可以访问数据库或运行代码。 您可以通过要求API密钥来执行此操作。 该密钥用于识别发出请求的用户,然后允许或拒绝该请求。

This can be used to allow only a few people to access the service, or even to create a tier system. This is how a lot of paid APIs work. Everyone is given free but limited access, and then you allow payment for access to superior parts of the service or just a higher rate of requests.

这可以用于仅允许少数人访问该服务,甚至可以创建一个层系统。 这就是许多付费API的工作方式。 每个人都可以免费使用,但访问权限有限,然后您就可以通过付费获得对服务高级部分的访问权或只是更高的请求率。

构建API (Building the API)

Now that we know some reasons why we might want to create an API, let’s do just that. We’re going to use API Gateway and AWS Lambdas, because it’s simpler than running a server. Make sure you have an AWS account and are logged in.

现在,我们知道了可能要创建API的一些原因,让我们开始吧。 我们将使用API​​ Gateway和AWS Lambdas,因为它比运行服务器更简单。 确保您拥有一个AWS账户并已登录。

设置API网关 (Setting up an API Gateway)

We’ll start by opening the API Gateway service and clicking “Get Started”. On the next page, we need to select the “New API” option. Then we’ll give our API a name and description, and click “Create API”.

我们将首先打开API网关服务,然后单击“入门” 在下一页上,我们需要选择“新API” 选项。 然后,给我们的API命名和描述,然后单击“创建API”。

Clicking “Create API” will get us into the configuration page for the API.

点击“创建API” 将使我们进入API的配置页面。

The first thing we need to do is to add a resource onto the API. Using resources allows us to group similar API calls together using nested slashes. We are going to create an API that we can use to make recommendations on what to watch. Therefore we can have /tv-shows and /movies as two base methods.

我们需要做的第一件事是在API上添加资源。 使用资源可以使我们使用嵌套的斜杠将类似的API调用分组在一起。 我们将创建一个API,该API可用于就观看内容提出建议。 因此,我们可以有/tv-shows /movies作为两种基本方法。

Click the “Actions” dropdown and select “Create Resource”. Name your resources, making sure that they are both in the “/” path.

点击“操作”下拉菜单,然后选择“创建资源” 命名您的资源,确保它们都在“ /”路径中。

We want users to be able to go to “/movies/horror”or “/tv-shows/comedy”, and we can do this by adding path parameters. These are variables that we can access inside the API. To create one of these, we need to set the resource to {resourceName} as shown below. This can be done for “tv-shows”and “movies”.

我们希望用户能够转到“ /电影/恐怖”或“ /电视节目/喜剧”,我们可以通过添加路径参数来做到这一点。 这些是我们可以在API中访问的变量。 要创建其中之一,我们需要将资源设置为{resourceName} ,如下所示。 可以对“电视节目”和“电影”进行此操作。

Now that we have length and genre, we can create methods for getting and adding data to a table. Select one of the {genre} resources, click “Actions”, and thenCreate Method”. This will create a small grey box below the resource which we can click. We are going to start with a GET request, so select that and click the tick button.

现在我们有了长度和体裁,我们可以创建用于获取数据并将数据添加到表的方法。 选择{genre}资源之一,单击“操作”,然后 然后创建方法” 这将在我们可以单击的资源下方创建一个小的灰色框。 我们将从GET开始 请求,因此选择该请求,然后单击对勾按钮。

This is where we get to decide how to handle the request. We are going to use AWS Lambdas, but we need to create them before we can finish setting up the methods.

这是我们决定如何处理请求的地方。 我们将使用AWS Lambda,但是我们需要先创建它们,然后才能完成方法的设置。

创建Lambda (Creating the Lambdas)

We are able to respond to these API requests using Lambdas, which is great as they only run when we need them to. They are also really easy to create, so that’s what we’ll do now.

我们能够使用Lambda响应这些API请求,这很棒,因为它们仅在需要它们时运行。 它们也确实很容易创建,因此我们现在要做的是。

In the Lambda console, click “Create function”. Then we can name our first API function movieAPI, set it to run Node 8.10, and “Create new role from template(s)”. We’ll name our new role “tableAPI” and add “Simple Microservice permissions” as the only template.

在Lambda控制台中,单击“创建功能”。 然后,我们可以将第一个API函数movieAPI 将其设置为运行Node 8.10,并“从模板创建新角色” 我们将新角色命名为“ tableAPI”,并添加“简单微服务权限”作为唯一模板。

All code can be found at https://github.com/SamWSoftware/Projects/tree/master/movieAPI

所有代码都可以在https://github.com/SamWSoftware/Projects/tree/master/movieAPI中找到

Clicking “Create function” will send us into the Lambda window. Scroll down to the “Function code” section and we’ll change the code. The first thing we’re going to do is to check what request method was used.

单击“创建功能”将使我们进入Lambda窗口。 向下滚动到“功能代码”部分,我们将更改代码。 我们要做的第一件事是检查使用了哪种请求方法。

exports.handler = async (event) => {
    console.log(event);
    if (event.httpMethod === 'PUT'){
        let response = putMovie(event)
        return done(response);
    } else if (event.httpMethod === 'GET'){
        let response = getMovie(event);
        return done(response);
    }
};

We’re going to start by writing the getMoviefunction. This function will start by getting the genrefrom the path parameters. This is where using path parameters can make this process easy.

我们将从编写getMovie函数开始。 此功能将从路径参数中获取genre开始。 在这里,使用路径参数可以使此过程变得容易。

const getMovie = event => {
    let genre = event.pathParameters.genre;
    return;
}

With the genre that the user requested, we are going to get a recommended movie for them. I copied these from 25 Top Films From Each Genre and added them to an object with the genre as the key. We can then get the film by getting the value of the genre requested.

根据用户要求的类型,我们将为他们准备推荐的电影。 我从《每个流派的25部顶级电影》中复制了这些影片 ,并将它们添加到以该流派为关键的对象中。 然后,我们可以通过获取所需类型的电影来获得电影。

const movies = {
    action: 'Desperado (1995)',
    fantasy: 'Inception (2010)',
    ...
    horror: 'Black Swan (2010)'
}

const getMovie = event => {
    let genre = event.pathParameters.genre;
    return movies[genre];
}

This means that the title of the movie is being passed into the done function. This function is used, as API Gateway expects the data to come back in a very specific format. This function turns a string into that required format.

这意味着电影的标题正在传递给done 功能。 使用此功能是因为API网关希望数据以非常特定的格式返回。 此函数将字符串转换为所需的格式。

const done = response => {
    return {
        statusCode: '200',
        body: JSON.stringify(response),
        headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Methods': '*',
            'Access-Control-Allow-Origin': '*'
        }
    }
}

We can do a very similar thing for a tv-showsAPI function, reusing most of the code. Just change the function names and the movie suggestions to tv show.

我们可以对tv-showsAPI函数执行类似tv-showsAPI ,从而重用大部分代码。 只需将功能名称和电影建议更改为电视节目即可。

将Lambda连接到API网关 (Connecting the Lambdas to API Gateway)

Back in API Gateway, we can add our new Lambdas to the methods we created earlier. We need to make sure that “Use Lambda Proxy integration” is selected and that we are pointing at the correct Lambda. Clicking “Save” will ask you for permissions to access this Lambda, to which we can give the “OK”.

回到API网关,我们可以将新的Lambda添加到我们之前创建的方法中。 我们需要确保“使用Lambda代理集成” 被选中,我们指向正确的Lambda。 单击“保存”将询问您访问此Lambda的权限,我们可以向其授予“确定”

Do this for the GET methods on both resources and we can start to test. Selecting the methods should now show a method execution diagram. This sounds complicated but the only bit we need is the “TEST” section.

GET执行此操作 两种资源上的方法,我们可以开始进行测试。 现在,选择方法应显示一个方法执行图。 这听起来很复杂,但我们唯一需要的就是“测试” 部分。

Clicking “TEST” will open a new section where we can try out the API. There are lots of things you can set here, but the only one we care about is the Path {genre}. We need to set this to the genre we’re requesting. Entering “western” as the genre and hitting the “Test” button gets a response like this:

点击“测试”将打开一个新部分,我们可以在其中试用API。 您可以在此处设置很多东西,但是我们唯一关心的是Path {genre} 我们需要将此设置为我们要求的类型。 输入“ western”作为类型,然后单击“ Test”按钮,将得到如下响应:

We got our API working! Now we need to make sure that other people can access it. There are two steps to this.

我们的API正常运行了! 现在,我们需要确保其他人可以访问它。 有两个步骤。

  1. We enable CORS — Select the “{genre}” resource and then click “Actions” and “Enable CORS”. Leave everything as defaults and, when asked, click “Yes, replace existing values”.

    我们启用CORS-选择“ {genre}” 资源,然后单击“操作” 和“启用CORS” 将所有内容保留为默认值,并在询问时单击“是,替换现有值”

  2. Deploy our API — Click on “Actions” andDeploy API”. Set the deployment stage to “[New Stage]” and then give your stage a name like “production” orpublic”.

    部署我们的API-单击“操作” 部署API”。 将部署阶段设置为“ [New Stage]”,然后为您的阶段命名为“ production” 公共”

Once your API has deployed you should get a URL like this. This is the base of your API. You can add /movies/western to access your API.

部署API后,您应该会获得一个类似的URL。 这是您的API的基础。 您可以添加/movies/western来访问您的API。

https://{uniqueCode}.execute-api.eu-west-1.amazonaws.com/production

Your API URL might end up something like:

您的API URL可能最终类似于:

https://fds1fe31fes476s.execute-api.eu-west-1.amazonaws.com/production/movies/western

That’s all for this article. In the next one we’ll connect this API to Dynamo tables and let users vote on their favourite movies in each genre. You can read that article below.

这就是本文的全部内容。 在下一个中,我们将将此API连接到Dynamo表,并让用户对每种流派中他们喜欢的电影进行投票。 您可以在下面阅读该文章

Building an API with Lambdas and API Gateway — Part 2In the first part we created an API which passed requests through to a Lambda which returned the top tv show or movie…medium.com

建设有lambda表达式和API网关的API -第2部分 :第一部分,我们创建了穿过的LAMBDA其返回的前电视节目或电影的请求的API ... medium.com

翻译自: https://www.freecodecamp.org/news/building-an-api-with-lambdas-and-api-gateway-11254e23b703/

lambda 使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值