API 伺服器與 DynamoDB
在本教學中,讓我們看看如何使用它來建立一個小型 API,該 API 具有端點以插入和檢索資訊,並由 DynamoDB 支援。
本教學假設您擁有 AWS 和 Deno Deploy 帳戶。
總覽 Jump to heading
我們將建置一個 API,該 API 具有單一端點,可接受 GET/POST 請求並傳回適當的資訊
# A GET request to the endpoint should return the details of the song based on its title.
GET /songs?title=Song%20Title # '%20' == space
# response
{
title: "Song Title"
artist: "Someone"
album: "Something",
released: "1970",
genres: "country rap",
}
# A POST request to the endpoint should insert the song details.
POST /songs
# post request body
{
title: "A New Title"
artist: "Someone New"
album: "Something New",
released: "2020",
genres: "country rap",
}
設定 DynamoDB Jump to heading
我們流程的第一步是產生 AWS 憑證,以程式化方式存取 DynamoDB。
產生憑證
- 前往 https://console.aws.amazon.com/iam/ 並前往「使用者」區段。
- 點擊建立使用者按鈕,填寫使用者名稱欄位(也許使用
denamo
)並選取程式化存取類型。 - 點擊下一步
- 選取直接附加政策並搜尋
AmazonDynamoDBFullAccess
。勾選結果中此政策旁邊的方框。 - 點擊下一步和建立使用者
- 在產生的使用者頁面上,點擊您剛建立的使用者
- 點擊建立存取金鑰
- 選取在 AWS 外部執行的應用程式
- 點擊 *建立
- 點擊下載 .csv 檔案以下載您剛建立的憑證。
建立資料庫表格
- 前往 https://console.aws.amazon.com/dynamodb 並點擊建立表格按鈕。
- 在表格名稱欄位中填寫
songs
,在分割區鍵中填寫title
。 - 向下捲動並點擊建立表格。
- 表格建立完成後,點擊表格名稱並找到其一般資訊
- 在 Amazon Resource Name (ARN) 下,記下新表格的區域(例如 us-east-1)。
撰寫應用程式 Jump to heading
建立一個名為 index.js
的檔案並插入以下內容
import {
json,
serve,
validateRequest,
} from "https://deno.land/x/sift@0.6.0/mod.ts";
// AWS has an official SDK that works with browsers. As most Deno Deploy's
// APIs are similar to browser's, the same SDK works with Deno Deploy.
// So we import the SDK along with some classes required to insert and
// retrieve data.
import {
DynamoDBClient,
GetItemCommand,
PutItemCommand,
} from "https://esm.sh/@aws-sdk/client-dynamodb";
// Create a client instance by providing your region information.
// The credentials are obtained from environment variables which
// we set during our project creation step on Deno Deploy.
const client = new DynamoDBClient({
region: Deno.env.get("AWS_TABLE_REGION"),
credentials: {
accessKeyId: Deno.env.get("AWS_ACCESS_KEY_ID"),
secretAccessKey: Deno.env.get("AWS_SECRET_ACCESS_KEY"),
},
});
serve({
"/songs": handleRequest,
});
async function handleRequest(request) {
// The endpoint allows GET and POST request. A parameter named "title"
// for a GET request to be processed. And body with the fields defined
// below are required to process POST request.
// validateRequest ensures that the provided terms are met by the request.
const { error, body } = await validateRequest(request, {
GET: {
params: ["title"],
},
POST: {
body: ["title", "artist", "album", "released", "genres"],
},
});
if (error) {
return json({ error: error.message }, { status: error.status });
}
// Handle POST request.
if (request.method === "POST") {
try {
// When we want to interact with DynamoDB, we send a command using the client
// instance. Here we are sending a PutItemCommand to insert the data from the
// request.
const {
$metadata: { httpStatusCode },
} = await client.send(
new PutItemCommand({
TableName: "songs",
Item: {
// Here 'S' implies that the value is of type string
// and 'N' implies a number.
title: { S: body.title },
artist: { S: body.artist },
album: { S: body.album },
released: { N: body.released },
genres: { S: body.genres },
},
}),
);
// On a successful put item request, dynamo returns a 200 status code (weird).
// So we test status code to verify if the data has been inserted and respond
// with the data provided by the request as a confirmation.
if (httpStatusCode === 200) {
return json({ ...body }, { status: 201 });
}
} catch (error) {
// If something goes wrong while making the request, we log
// the error for our reference.
console.log(error);
}
// If the execution reaches here it implies that the insertion wasn't successful.
return json({ error: "couldn't insert data" }, { status: 500 });
}
// Handle GET request.
try {
// We grab the title form the request and send a GetItemCommand
// to retrieve the information about the song.
const { searchParams } = new URL(request.url);
const { Item } = await client.send(
new GetItemCommand({
TableName: "songs",
Key: {
title: { S: searchParams.get("title") },
},
}),
);
// The Item property contains all the data, so if it's not undefined,
// we proceed to returning the information about the title
if (Item) {
return json({
title: Item.title.S,
artist: Item.artist.S,
album: Item.album.S,
released: Item.released.S,
genres: Item.genres.S,
});
}
} catch (error) {
console.log(error);
}
// We might reach here if an error is thrown during the request to database
// or if the Item is not found in the database.
// We reflect both conditions with a general message.
return json(
{
message: "couldn't find the title",
},
{ status: 404 },
);
}
在新專案中初始化 git 並 將其推送到 GitHub。
部署應用程式 Jump to heading
現在我們已準備就緒,讓我們部署您的新應用程式!
- 在您的瀏覽器中,造訪 Deno Deploy 並連結您的 GitHub 帳戶。
- 選取包含您新應用程式的儲存庫。
- 您可以為您的專案命名,或允許 Deno 為您產生一個名稱
- 在「進入點」下拉選單中選取
index.js
- 點擊部署專案
為了使您的應用程式正常運作,我們需要設定其環境變數。
在您專案的成功頁面或專案儀表板中,點擊新增環境變數。在「環境變數」下,點擊 + 新增變數。建立以下變數
AWS_ACCESS_KEY_ID
- 使用您下載的 CSV 中的值AWS_SECRET_ACCESS_KEY
- 使用您下載的 CSV 中的值。AWS_TABLE_REGION
- 使用您表格的區域
點擊以儲存變數。
讓我們測試 API。
POST 一些資料。
curl --request POST --data \
'{"title": "Old Town Road", "artist": "Lil Nas X", "album": "7", "released": "2019", "genres": "Country rap, Pop"}' \
--dump-header - https://<project_name>.deno.dev/songs
GET 關於標題的資訊。
curl https://<project_name>.deno.dev/songs?title=Old%20Town%20Road
恭喜您學習如何將 DynamoDB 與 Deno Deploy 搭配使用!