{APIGateway}チュートリアル: Lambda 非プロキシ統合を使用して API Gateway REST API をビルドする

https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/getting-started-lambda-non-proxy-integration.html

 

-- 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. 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

 

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


-- 4. Lambda関数作成

vim test.js

'use strict';
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var times = ['morning', 'afternoon', 'evening', 'night', 'day'];

console.log('Loading function');

exports.handler = function(event, context, callback) {
  // Parse the input for the name, city, time and day property values
  let name = event.name === undefined ? 'you' : event.name;
  let city = event.city === undefined ? 'World' : event.city;
  let time = times.indexOf(event.time)<0 ? 'day' : event.time;
  let day = days.indexOf(event.day)<0 ? null : event.day;

  // Generate a greeting
  let greeting = 'Good ' + time + ', ' + name + ' of ' + city + '. ';
  if (day) greeting += 'Happy ' + day + '!';
  
  // Log the greeting to CloudWatch
  console.log('Hello: ', greeting);
  
  // Return a greeting to the caller
  callback(null, {
      "greeting": greeting
  }); 
};


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


-- 5. API を作成する

aws apigateway create-rest-api \
--name api01 \
--description "api01" \
--endpoint-configuration '{"types": ["REGIONAL"]}'

aws apigateway get-rest-apis

aws apigateway get-rest-api \
--rest-api-id 1111111111

 

-- 6. API でリソースを作成する
aws apigateway get-resources \
--rest-api-id 1111111111

aws apigateway create-resource \
--rest-api-id 1111111111 \
--parent-id 2222222222 \
--path-part "{city}"

-- 7. モデルを作成する

aws apigateway get-models \
--rest-api-id 1111111111

aws apigateway get-model \
--rest-api-id 1111111111 \
--model-name model01


aws apigateway create-model \
--rest-api-id 1111111111 \
--name model01 \
--content-type application/json \
--schema '{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "GetStartedLambdaIntegrationInputModel",
  "type": "object",
  "properties": {
    "callerName": { "type": "string" }
  }
}'


-- 8. リソースにメソッドを作成する

 

aws apigateway put-method \
--rest-api-id 1111111111 \
--resource-id 333333 \
--http-method ANY \
--authorization-type NONE \
--no-api-key-required \
--request-parameters '{
        "method.request.path.city": true,
        "method.request.querystring.time": true
    }' \
--request-models '{
        "application/json": "model01"
    }'


aws apigateway put-method-response \
--rest-api-id 1111111111 \
--resource-id 333333 \
--http-method ANY \
--status-code 200 \
--response-models '{"application/json": "Empty"}'


vim a.json
{
  "application/json": "#set($inputRoot = $input.path('$'))\r\n{\r\n  \"city\": \"$input.params('city')\",\r\n  \"time\": \"$input.params('time')\",\r\n  \"day\":  \"$input.params('day')\",\r\n  \"name\": \"$inputRoot.callerName\"\r\n}"
}

 

aws apigateway put-integration \
--rest-api-id 1111111111 \
--resource-id 333333 \
--http-method ANY \
--type AWS \
--integration-http-method POST \
--content-handling CONVERT_TO_TEXT \
--uri "arn:aws:apigateway:ap-northeast-1:lambda:path/2015-03-31/functions/arn:aws:lambda:ap-northeast-1:999999999999:function:func01/invocations" \
--passthrough-behavior "WHEN_NO_TEMPLATES" \
--request-templates file://a.json

 

aws apigateway put-integration-response \
--rest-api-id 1111111111 \
--resource-id 333333 \
--http-method ANY \
--status-code 200 \
--response-templates '{"application/json": ""}'

 

aws apigateway get-method \
--rest-api-id 1111111111 \
--resource-id 333333 \
--http-method ANY

 

 

-- 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 をテストする

aws apigateway test-invoke-method \
--rest-api-id 1111111111 \
--resource-id 333333 \
--http-method POST \
--path-with-query-string '/Seattle?time=morning' \
--body '{"callerName": "John"}' \
--headers 'day=Wednesday'

 

 

-- 11. API をデプロイする


aws apigateway get-deployments \
--rest-api-id 1111111111

aws apigateway get-stages \
--rest-api-id 1111111111


aws apigateway create-deployment \
--rest-api-id 1111111111

aws apigateway create-stage \
--rest-api-id 1111111111 \
--stage-name stage01 \
--deployment-id 444444

 

-- 12. デプロイ後にAPI をテストする

curl -v -X POST \
  'https://1111111111.execute-api.ap-northeast-1.amazonaws.com/stage01/America?time=morning' \
  -H 'content-type: application/json' \
  -H 'day: Sunday' \
  -H 'x-amz-docs-region: ap-northeast-1' \
  -d '{
     "callerName": "Ken"
}'


-- 13. クリーンアップ


-- API削除

aws apigateway get-rest-apis

aws apigateway delete-rest-api \
--rest-api-id 1111111111

 

-- Lambda関数の削除

aws lambda get-function --function-name func01
aws lambda delete-function --function-name func01


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

aws iam detach-role-policy \
--role-name role01 \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

aws iam delete-role --role-name role01