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 使用

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/393433.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/393433.shtml
英文地址,請注明出處:http://en.pswp.cn/news/393433.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Hyper-V Server聯機調整虛擬硬盤大小

1. 技術概述: 從 Windows Server 2012 R2開始,管理員可以在運行虛擬機的同時,使用 Hyper-V 來擴展或壓縮虛擬硬盤的大小。存儲管理員可以通過對運行中的虛擬硬盤執行維護操作來避免代價不菲的停機。不再需要關閉虛擬機,這可以避免…

leetcode162. 尋找峰值(二分法)

峰值元素是指其值大于左右相鄰值的元素。 給定一個輸入數組 nums,其中 nums[i] ≠ nums[i1],找到峰值元素并返回其索引。 數組可能包含多個峰值,在這種情況下,返回任何一個峰值所在位置即可。 你可以假設 nums[-1] nums[n] -…

python網絡爬蟲(5)BeautifulSoup的使用示范

創建并顯示原始內容 其中的lxml第三方解釋器加快解析速度 import bs4 from bs4 import BeautifulSoup html_str """ <html><head><title>The Dormouses story</title></head> <body> <p class"title"><…

Mingw編譯DLib

Mingw編譯DLib 因為機器上安裝了qt-opensource-windows-x86-mingw530-5.8.0&#xff0c;所以準備使用其自帶的mingw530來編譯DLib使用。 因為DLib使用CMake的構建腳本&#xff0c;所以還請先安裝好CMake。 cmake的下載地址如下https://cmake.org/files/v3.7/cmake-3.7.2-win64-…

探索JavaScript的關閉功能

Discover Functional JavaScript was named one of the best new Functional Programming books by BookAuthority!“發現功能JavaScript”被BookAuthority評為最佳新功能編程書籍之一 &#xff01; A closure is an inner function that has access to the outer scope, even…

QueryList 配置curl參數 的文檔位置 QueryList抓取https 終于找到了

需要設置ssl證書&#xff0c;或者不驗證證書&#xff0c;例&#xff1a;$ql QueryList::get(https://...,[],[verify > false]);設置這個 verify > false , 所以curl的其他參數就在這里配置即可 文檔在 https://guzzle-cn.readthedocs.io/zh_CN/latest/request-optio…

leetcode981. 基于時間的鍵值存儲(treemap)

創建一個基于時間的鍵值存儲類 TimeMap&#xff0c;它支持下面兩個操作&#xff1a; set(string key, string value, int timestamp) 存儲鍵 key、值 value&#xff0c;以及給定的時間戳 timestamp。 2. get(string key, int timestamp) 返回先前調用 set(key, value, times…

物聯網筆記

轉載于:https://www.cnblogs.com/16-C-kai/p/6596682.html

關于大學生玩網絡游戲的調查問卷

1.創建問卷&#xff0c;輸入調查名稱 2編輯問卷 3檢查問卷&#xff0c;是否有誤 4.提交并發布問卷 5分享問卷 6.問卷分析 轉載于:https://www.cnblogs.com/dzw1996/p/7786754.html

java自動排序_java ArrayList自動排序算法的實現

前幾天寫的那個是錯誤的&#xff0c;在這里將正確的更新。。。通過實現ComParator接口&#xff0c;并且對Compare函數進行重寫&#xff0c;自定義排序規則實現對ArrayList中對象的排序。。Student類定義&#xff1a;通過右鍵-》source-》自動生成Set和get方法package first;imp…

1到100的二進制編碼_每天經過100天的編碼后,我學到了什么

1到100的二進制編碼Eleftheria Batsou is a web developer from Thessaloniki, Greece. She gave a talk at the Codegarden conference about her experience doing a solid 100 days of coding every day as part of the #100DaysOfCode Challenge.Eleftheria Batsou是來自希…

第六次 實驗

轉載于:https://www.cnblogs.com/P201821440005/p/10967987.html

leetcode658. 找到 K 個最接近的元素(二分法)

給定一個排序好的數組&#xff0c;兩個整數 k 和 x&#xff0c;從數組中找到最靠近 x&#xff08;兩數之差最小&#xff09;的 k 個數。返回的結果必須要是按升序排好的。如果有兩個數與 x 的差值一樣&#xff0c;優先選擇數值較小的那個數。 示例 1: 輸入: [1,2,3,4,5], k4,…

du命令、df命令用法

一、du命令 [plain] view plaincopy print?[rootwc1 mysql]# du --help Usage: du [OPTION]... [FILE]... or: du [OPTION]... --files0-fromF Summarize disk usage of each FILE, recursively for directories. Mandatory arguments to long options are mandatory…

mysql 循環創建列_mysql – 查詢列中的循環值

我需要創建一個查詢,一次只將一列的值移動一行↑&#xff1a;----------------------------| anotherCOL | values_to_loop |----------------------------| 1 | 1 || 2 | 2 || 3 | 3 || 4 | 4 || 5 | 5 || 6 | 6 || 7 | 7 || 8 | 8 || 9 | 9 || 10 | 10 |--------------------…

因子個數與因子和

題目&#xff1a;LightOJ:1341 - Aladdin and the Flying Carpet(因子個數&#xff09; Its said that Aladdin had to solve seven mysteries before getting the Magical Lamp which summons a powerful Genie. Here we are concerned about the first mystery. Aladdin was …

如何在JavaScript中直觀地設計狀態

by Shawn McKay肖恩麥凱(Shawn McKay) 如何在JavaScript中直觀地設計狀態 (How to visually design state in JavaScript) 使用狀態機和狀態圖開發應用程序的路線圖 (A roadmap for developing applications with state machines & statecharts) Why does state managemen…

SQL Server 2008 - Cannot set a credential for principal 'sa'.

很久沒有用到SQL Server了&#xff0c;今天有幸在幫同事解決一個SQL Server數據連接的問題時突然發現我無法修改我的sa用戶的密碼了。過程是這樣的&#xff1a;一開始我本地的數據庫實例是Windows認證方式&#xff0c;我想將它改成Windows和數據庫混合認證方式后用sa賬戶登錄&a…

leetcode50. Pow(x, n)(快速冪)

實現 pow(x, n) &#xff0c;即計算 x 的 n 次冪函數。 示例 1: 輸入: 2.00000, 10 輸出: 1024.00000 代碼 class Solution {public double myPow(double x, int n) {long tn;return t>0?Pow(x,t):1/Pow(x,-t);//判斷冪指數}public double Pow(double x, long n) {if(n…

Java DES 加解密(DES/CBC/PKCS5Padding)

/*** DES加密** param data 加密數據* param key 密鑰* return 返回加密后的數據*/public static byte[] desEncrypt(byte[] data, String key, String charset) {try {Cipher cipher Cipher.getInstance("DES/CBC/PKCS5Padding");byte[] k charset null || char…