LoginSignup
49
54

More than 5 years have passed since last update.

API Gateway + Lambda + DynamoDB

Posted at

image.png

利用するサービス
・DynamoDB
・IAM
・Lambda
・API Gateway


1.DynamoDB でテーブルを作成する

DynamoDB を開き、「テーブル」から「テーブルの作成」をクリック。
image.png

[テーブル名]に 「demo_test」 、[プライマリキー]に「test_id」と入力し、「作成」。
image.png

「項目」から「項目の作成」をクリック。
image.png

「Append」から「String」を追加します。
image.png

「name」を追加し、以下のように入力します。
image.png

同様に以下のテーブルになるように作成してください。
image.png

2.Lambda関数を作成する

2つの権限をもつ、IAMロールを作成しておきましょう。
 AWSLambdaBasicExecutionRole:ログの書き込み権限
 DynamoDBAmazonDynamoDBFullAccess:DynamoDBへのアクセス権限

Lambda を開き、「関数の作成」をクリック。
image.png

「一から作成」を選択し以下のとおり入力し、「関数の作成」
・名前:demo-lambda
・ランタイム:Python 3.6
・ロール:既存のロール
・既存のロール:作成済みのIAMロールを選択
image.png

コードを以下のように編集する。

import boto3

dynamodb = boto3.resource('dynamodb')
table    = dynamodb.Table('demo_test')

def get_person(id):
    response = table.get_item(
            Key={
                 'test_id': id
            }
        )
    return response['Item']

def lambda_handler(event, context):
    person = get_person('001')
    return person

table は dynamodbで作成した table名。
Key は プライマリキー。

「テスト」する。
image.png

3.API Gatewayを作成する

test_id を指定したらその値が返ってくるようにします。

API Gateway を開き、[API 名] に「demo-api」などと入力し、「APIの作成」
image.png

「アクション」から「メゾットの作成」。
image.png

「GET」を選択し、[統合タイプ]はLambda、[Lambda 関数]に作成したものを選択し、「保存」。
image.png

「テスト」を実行。
image.png

Lambda関数が実行されperson情報がレスポンスとして返却されていることが確認できます。
image.png

作成したLambda関数では、現状、Lambdaを実行時にはレスポンスとして常に test_id:001 を返すようになっています。
ということで、まずAPI Gateway側からLambdaに変数を引き渡す設定を追加します。
「統合リクエスト」をクリック。
image.png

「マッピングテンプレートの追加」をクリックし、「application/json」と追加します。
image.png

テンプレートの以下の内容を入力し、「保存」

{
    "test_id" : "$input.params('test_id')"
}

Lambda も以下の通り修正する。

import boto3

dynamodb = boto3.resource('dynamodb')
table    = dynamodb.Table('demo_test')

def get_person(id):
    response = table.get_item(
            Key={
                 'test_id': id
            }
        )
    return response['Item']

def lambda_handler(event, context):
    person = get_person(event['test_id'])
    return person

APIをインターネットに公開します。
「アクション」より「APIのデプロイ」をクリック。
image.png

適当な[ステージ名]を入力し、「デプロイ」。
image.png

https://mdqzdp29vb.execute-api.ap-northeast-1.amazonaws.com/demo?test_id=001
のように、test_idを入力すると、
{"name": "yamada", "test_id": "001"}
と結果が返ってくるようになります。

test_idを指定しないとエラーになる。
なので、
test_idの指定がなかったら全を返すように、Lambdaを編集してみる。

import boto3

dynamodb = boto3.resource('dynamodb')
table    = dynamodb.Table('demo_test')

def get_person(id):
    response = table.get_item(
            Key={
                 'test_id': id
            }
        )
    return response['Item']

def get_persons():
    response = table.scan()
    return response['Items']

def lambda_handler(event, context):
    return get_persons() if event['test_id'] == '' else get_person(event['test_id'])

test_idの指定がない場合は、以下のとおりに返ってくる。
[{"name": "yamada", "test_id": "001"}, {"name": "suzuki", "test_id": "003"}, {"name": "tanaka", "test_id": "002"}]

49
54
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
49
54