{APIGateway}チュートリアル: Lambda と DynamoDB を使用した CRUD API の構築

https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/http-api-dynamo-db.html
https://cloudaffaire.com/how-to-create-an-api-gateway-with-lambda-integration-using-aws-cli/


-- 1. コマンド等のインストール

-- 1.1 aws cli version 2 インストール

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install

aws --version

-- 1.2 jqインストール
sudo yum -y install jq


-- 2. DynamoDB テーブルを作成する


aws dynamodb create-table \
--table-name tab1 \
--attribute-definitions \
    AttributeName=id,AttributeType=S \
--key-schema \
    AttributeName=id,KeyType=HASH \
--billing-mode=PAY_PER_REQUEST


aws dynamodb list-tables
aws dynamodb describe-table --table-name tab1

 

-- 3. IAMポリシー作成
vim policy01.json

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1428341300017",
      "Action": [
        "dynamodb:DeleteItem",
        "dynamodb:GetItem",
        "dynamodb:PutItem",
        "dynamodb:Query",
        "dynamodb:Scan",
        "dynamodb:UpdateItem"
      ],
      "Effect": "Allow",
      "Resource": "*"
    },
    {
      "Sid": "",
      "Resource": "*",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Effect": "Allow"
    }
  ]
}

aws iam create-policy \
--policy-name policy01 \
--policy-document file://policy01.json

-- 4. IAMロール作成
vim role01.json

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

aws iam create-role \
--role-name role01 \
--assume-role-policy-document file://role01.json

-- 5. ポリシーをロールにアタッチ
aws iam attach-role-policy \
--policy-arn arn:aws:iam::999999999999:policy/policy01 \
--role-name role01


-- 6. Lambda関数作成

vim test.js


const AWS = require("aws-sdk");

const dynamo = new AWS.DynamoDB.DocumentClient();

exports.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
          .delete({
            TableName: "tab1",
            Key: {
              id: event.pathParameters.id
            }
          })
          .promise();
        body = `Deleted item ${event.pathParameters.id}`;
        break;
      case "GET /items/{id}":
        body = await dynamo
          .get({
            TableName: "tab1",
            Key: {
              id: event.pathParameters.id
            }
          })
          .promise();
        break;
      case "GET /items":
        body = await dynamo.scan({ TableName: "tab1" }).promise();
        break;
      case "PUT /items":
        let requestJSON = JSON.parse(event.body);
        await dynamo
          .put({
            TableName: "tab1",
            Item: {
              id: requestJSON.id,
              name: requestJSON.name,
              price: requestJSON.price
            }
          })
          .promise();
        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
  };
};

 


chmod 755 test.js
zip test.zip test.js

aws lambda create-function \
--function-name func01 \
--zip-file fileb://test.zip \
--handler test.handler \
--runtime nodejs14.x \
--role arn:aws:iam::999999999999:role/role01

 

aws lambda list-functions | grep func01

aws lambda get-function --function-name func01

 

-- 7. HTTP API を作成する

aws apigatewayv2 create-api \
--name api01 \
--protocol-type HTTP \
--target arn:aws:lambda:ap-northeast-1:999999999999:function:func01

 

aws apigatewayv2 get-apis
aws apigatewayv2 get-apis| jq -r .Items.ApiId


aws apigatewayv2 get-api \
--api-id 1111111111

 

-- 8. ルートを作成する

aws apigatewayv2 get-integrations \
--api-id 1111111111

aws apigatewayv2 get-integrations \
--api-id 1111111111| jq -r .Items.IntegrationId


aws apigatewayv2 create-route \
--api-id 1111111111 \
--route-key 'GET /items/{id}' \
--target integrations/2222222

aws apigatewayv2 create-route \
--api-id 1111111111 \
--route-key 'GET /items' \
--target integrations/2222222

aws apigatewayv2 create-route \
--api-id 1111111111 \
--route-key 'PUT /items' \
--target integrations/2222222

aws apigatewayv2 create-route \
--api-id 1111111111 \
--route-key 'DELETE /items/{id}' \
--target integrations/2222222


aws apigatewayv2 get-routes \
--api-id 1111111111


-- 9. Lambda関数に権限を追加する

aws lambda add-permission \
--function-name func01 \
--statement-id apigw \
--action lambda:InvokeFunction \
--principal apigateway.amazonaws.com \
--source-arn "arn:aws:execute-api:ap-northeast-1:999999999999:1111111111/*"

 

aws lambda get-policy \
--function-name func01 | jq -r .Policy  | jq .

 

-- 10. API をテストする

 

curl -v -X "PUT" -H "Content-Type: application/json" \
-d "{\"id\": \"001\", \"name\": \"item01\", \"price\": 100}" \
https://1111111111.execute-api.ap-northeast-1.amazonaws.com/items

curl -v -X "PUT" -H "Content-Type: application/json" \
-d "{\"id\": \"002\", \"name\": \"item02\", \"price\": 200}" \
https://1111111111.execute-api.ap-northeast-1.amazonaws.com/items

aws dynamodb scan --table-name tab1

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


curl -v https://1111111111.execute-api.ap-northeast-1.amazonaws.com/items/001


curl -v -X "DELETE" https://1111111111.execute-api.ap-northeast-1.amazonaws.com/items/001

aws dynamodb scan --table-name tab1


-- 11. クリーンアップ


-- HTTP APIの削除
aws apigatewayv2 get-apis

aws apigatewayv2 delete-api \
--api-id 1111111111

 

-- Lambda関数の削除
aws lambda get-function --function-name func01
aws lambda delete-function --function-name func01


-- IAMロールの削除
aws iam list-roles | grep role01

aws iam detach-role-policy \
--role-name role01 \
--policy-arn arn:aws:iam::999999999999:policy/policy01

aws iam delete-role --role-name role01


-- IAMポリシーの削除
aws iam list-policies | grep policy01

aws iam delete-policy \
--policy-arn arn:aws:iam::999999999999:policy/policy01

 

-- DynamoDB テーブル削除
aws dynamodb list-tables
aws dynamodb delete-table --table-name tab1