- LocalStackとSAM CLIを用いたローカルLambda + DynamoDB APIの作成方法についてメモする。
- POSTメソッドでリクエストボディに指定した値をDynamoDBテーブル検索して返却する。
構成
LocalStack 準備
- こちらの手順でDocker LocalStack環境を準備しておく。
Dynamo DB 準備
- テーブル(
sample-table
)作成
aws dynamodb create-table --table-name sample-table --attribute-definitions AttributeName=Data,AttributeType=S --key-schema AttributeName=Data,KeyType=HASH --provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1 --endpoint-url=http://localhost:4566 --profile localstack
{
"TableDescription": {
"AttributeDefinitions": [
{
"AttributeName": "Data",
"AttributeType": "S"
}
],
"TableName": "sample-table",
"KeySchema": [
{
"AttributeName": "Data",
"KeyType": "HASH"
}
],
"TableStatus": "ACTIVE",
"CreationDateTime": "2021-10-09T14:55:59.763000+09:00",
"ProvisionedThroughput": {
"LastIncreaseDateTime": "1970-01-01T09:00:00+09:00",
"LastDecreaseDateTime": "1970-01-01T09:00:00+09:00",
"NumberOfDecreasesToday": 0,
"ReadCapacityUnits": 1,
"WriteCapacityUnits": 1
},
"TableSizeBytes": 0,
"ItemCount": 0,
"TableArn": "arn:aws:dynamodb:ddblocal:000000000000:table/sample-table"
}
}
- 動作確認(データ登録)
aws dynamodb put-item --table-name sample-table --item={\"Data\":{\"S\":\"fuga\"}} --endpoint-url=http://localhost:4566 --profile localstack
-
登録データ確認
aws dynamodb scan --table-name sample-table --endpoint-url=http://localhost:4566 --profile localstack { "Items": [ { "Data": { "S": "fuga" } } ], "Count": 1, "ScannedCount": 1, "ConsumedCapacity": null }
Lambda準備
Lambda
- ひな形作成
sam init
※ランタイムはPython3.8を選択。
-
template.yml
- Hello World Exampleを利用する。
- Pathを
/search_data
に変更する。 - POSTメソッドを受け付けるように
Method
をpost
に変更する。
... Events: HelloWorld: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /search_data Method: post ...
requrements.txt
requests
boto3
※DynamoDBアクセス用にboto3追加
- Lambda処理(
app.py
)修正
import json
from boto3.session import Session
# DynamoDB接続設定
session = Session(aws_access_key_id='dummy',
aws_secret_access_key='dummy',
region_name='ap-northeast-1'
)
dynamodb = session.resource(
service_name='dynamodb',
endpoint_url='http://localstack:4566'
)
table= dynamodb.Table('sample-table')
def lambda_handler(event, context):
req_body = json.loads(event["body"])
primary_key = {"Data": req_body['data']}
res = table.get_item(Key=primary_key)
item = res["Item"]
print(item,type(item))
return {
"statusCode": 200,
"body": json.dumps(item),
}
動作確認
- ビルド
sam build
- 実行
sam local start-api --docker-network docker.internal
- リクエスト
POST /search_data HTTP/1.1
Host: localhost:3000
Content-Type: application/json
Content-Length: 23
{
"data":"fuga"
}
- レスポンス
{
"Data": "fuga"
}