建立資料表
首先,在 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 | import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; |
點選 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" |