{APIGateway}チュートリアル: Lambda プロキシ統合を使用した Hello World REST API の構築

https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.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';
console.log('Loading hello world function');
 
exports.handler = async (event) => {
    let name = "you";
    let city = 'World';
    let time = 'day';
    let day = '';
    let responseCode = 200;
    console.log("request: " + JSON.stringify(event));
    
    if (event.queryStringParameters && event.queryStringParameters.name) {
        console.log("Received name: " + event.queryStringParameters.name);
        name = event.queryStringParameters.name;
    }
    
    if (event.queryStringParameters && event.queryStringParameters.city) {
        console.log("Received city: " + event.queryStringParameters.city);
        city = event.queryStringParameters.city;
    }
    
    if (event.headers && event.headers['day']) {
        console.log("Received day: " + event.headers.day);
        day = event.headers.day;
    }
    
    if (event.body) {
        let body = JSON.parse(event.body)
        if (body.time) 
            time = body.time;
    }
 
    let greeting = `Good ${time}, ${name} of ${city}.`;
    if (day) greeting += ` Happy ${day}!`;

    let responseBody = {
        message: greeting,
        input: event
    };
    
    // The output from a Lambda proxy integration must be 
    // in the following JSON object. The 'headers' property 
    // is for custom response headers in addition to standard 
    // ones. The 'body' property  must be a JSON string. For 
    // base64-encoded payload, you must also set the 'isBase64Encoded'
    // property to 'true'.
    let response = {
        statusCode: responseCode,
        headers: {
            "x-custom-header" : "my custom header value"
        },
        body: JSON.stringify(responseBody)
    };
    console.log("response: " + JSON.stringify(response))
    return response;
};


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 xxxxxxxxxx

 

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

aws apigateway create-resource \
--rest-api-id xxxxxxxxxx \
--parent-id yyyyyyyyyy \
--path-part "helloworld"


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


aws apigateway get-method \
--rest-api-id xxxxxxxxxx \
--resource-id zzzzzz \
--http-method ANY

aws apigateway get-integration \
--rest-api-id xxxxxxxxxx \
--resource-id zzzzzz \
--http-method ANY

aws apigateway get-integration-response \
--rest-api-id xxxxxxxxxx \
--resource-id zzzzzz \
--http-method ANY \
--status-code 200

aws apigateway get-method-response \
--rest-api-id xxxxxxxxxx \
--resource-id zzzzzz \
--http-method ANY \
--status-code 200

 


aws apigateway put-method \
--rest-api-id xxxxxxxxxx \
--resource-id zzzzzz \
--http-method ANY \
--authorization-type NONE \
--no-api-key-required \
--request-parameters {}

aws apigateway put-integration \
--rest-api-id xxxxxxxxxx \
--resource-id zzzzzz \
--http-method ANY \
--type AWS_PROXY \
--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"

 


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


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

 


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


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

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


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

aws apigateway create-stage \
--rest-api-id xxxxxxxxxx \
--stage-name stage01 \
--deployment-id 000000 \

 

-- 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:xxxxxxxxxx/*/*/helloworld


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

 

 

-- 10. テストする

https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/stage01/helloworld?name=John&city=Seattle

 

curl -v -X POST \
'https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/stage01/helloworld?name=John&city=Seattle' \
-H 'content-type: application/json' \
-H 'day: Thursday' \
-d '{ "time": "evening" }'

curl -v -X GET \
'https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/stage01/helloworld?name=John&city=Seattle' \
-H 'content-type: application/json' \
-H 'day: Thursday'

 

-- 11. クリーンアップ

-- API削除

aws apigateway get-rest-apis

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

 

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