使用 AWS Lambda 和 DynamoDB 建立 REST API 無伺服器應用程式

建立資料表

首先,在 DynamoDB 建立一個資料表。

  • Table name: http-crud-tutorial-items
  • Partition key: id
  • 選擇 On-demand 模式

建立函式

AWS Lambda 建立一個函式。

  • Function name: http-crud-tutorial-function
  • Runtime: Node.js
  • Execution role name: http-crud-tutorial-role
  • Policy templates: Simple microservice permissions

建立範例函式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import {
DynamoDBDocumentClient,
ScanCommand,
PutCommand,
GetCommand,
DeleteCommand,
} from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});

const dynamo = DynamoDBDocumentClient.from(client);

const tableName = "http-crud-tutorial-items";

export const handler = async (event, context) => {
let body;
let statusCode = 200;
const headers = {
"Content-Type": "application/json",
};

try {
switch (event.routeKey) {
case "DELETE /items/{id}":
await dynamo.send(
new DeleteCommand({
TableName: tableName,
Key: {
id: event.pathParameters.id,
},
})
);
body = `Deleted item ${event.pathParameters.id}`;
break;
case "GET /items/{id}":
body = await dynamo.send(
new GetCommand({
TableName: tableName,
Key: {
id: event.pathParameters.id,
},
})
);
body = body.Item;
break;
case "GET /items":
body = await dynamo.send(
new ScanCommand({ TableName: tableName })
);
body = body.Items;
break;
case "PUT /items":
let requestJSON = JSON.parse(event.body);
await dynamo.send(
new PutCommand({
TableName: tableName,
Item: {
id: requestJSON.id,
price: requestJSON.price,
name: requestJSON.name,
},
})
);
body = `Put item ${requestJSON.id}`;
break;
default:
throw new Error(`Unsupported route: "${event.routeKey}"`);
}
} catch (err) {
statusCode = 400;
body = err.message;
} finally {
body = JSON.stringify(body);
}

return {
statusCode,
body,
headers,
};
};

點選 Deploy 按鈕。

建立 API

API Gateway 建立一個 REST API。

  • API name: http-crud-tutorial-api

建立 routes 如下:

  • GET /items/{id}
  • GET /items
  • PUT /items
  • DELETE /items/{id}

為每個路由建立 integration 如下:

  • 選擇路由
  • Integration type: Lambda function
  • Choose an existing integration: http-crud-tutorial-function

測試

新增物件

使用 curl 進行呼叫。

1
curl -X "PUT" -H "Content-Type: application/json" -d "{\"id\": \"123\", \"price\": 12345, \"name\": \"myitem\"}" https://xxx.execute-api.ap-northeast-1.amazonaws.com/items

回應如下:

1
"Put item 123"

取得物件列表

1
curl https://xxx.execute-api.ap-northeast-1.amazonaws.com/items

回應如下:

1
[{"price":12345,"id":"123","name":"myitem"}]

取得指定物件

1
curl https://xxx.execute-api.ap-northeast-1.amazonaws.com/items/123

回應如下:

1
{"price":12345,"id":"123","name":"myitem"}

刪除物件

1
curl -X "DELETE" https://xxx.execute-api.ap-northeast-1.amazonaws.com/items/123

回應如下:

1
"Deleted item 123"

參考資料