ServerlessFrameworkでHTTP API (API Gateway + Lambda (Node.js) )を作成&デプロイする

やりたいこと

  • serverless frameworkを利用してHTTP APIを作成、デプロイする。
  • HTTP APIAWSのApiGateway + Lambdaの構成で作成する。

環境

serverless frameworkをインストールする

公式ページを参考にする。npmのグローバルインストールでいれる。

serverless.com

npm install -g serverless

インストールされたか確認

sls -version
1.26.1

AWSのアクセスキー、シークレットキーを作成する

AWSの管理コンソールからIAMを選択、サイドメニューのユーザーからユーザーの追加を押下 f:id:hkou:20180417224624p:plain

「AdministratorAccess」ポリシーを付加した任意のユーザーを作成する。
ユーザーを作成したら認証情報が記載されたCSVファイルがダウンロードできるので開いておく。

aws cliにアクセスキー、シークレットキーを登録する

docs.aws.amazon.com

$ aws configure
AWS Access Key ID [None]: アクセスキーを入力する
AWS Secret Access Key [None]: シークレットキーを入力する
Default region name [None]: ap-northeast-1 とりあえず東京リージョン
Default output format [None]: json

プロジェクトを作成する

Serverless Frameworkのcreateコマンドでサービスのテンプレートを作成する

sls create --template aws-nodejs --path test-service

カレントディレクトリにtest-serviceディレクトリが作成される。

handler.jsを編集する

先程のcreateコマンドでhandler.jsの雛形が作成されたので、これを開き編集していく。
作成するAPIは以下の2つ(内容に特に意味はない)

  • GETするとHelloWorldの文字列を返す簡単なAPI
  • 数値配列をPOSTすると合計値を返すAPI
'use strict';
module.exports.hello = (event, context, callback) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Hello World'
    }),
  };
  callback(null, response);
};
module.exports.add = (event, context, callback) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify({
      result: JSON.parse(event.body).reduce((acc, x) => acc + x)
    }),
  };
  callback(null, response);
};

serverless.ymlを編集する

先程のcreateコマンドでserverless.ymlの雛形が作成されたので、これを開き編集していく。

東京リージョンにデプロイしてほしいのでproviderの下にregion指定の記述をする。

provider:
  name: aws
  runtime: nodejs6.10
  region: ap-northeast-1

APIのエンドポイントを定義する。

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: api/hello
          method: get
  add:
    handler: handler.add
    events:
      - http:
          path: api/add
          method: post

デプロイする

以下のコマンドを実行する。
AWSにデプロイされ、エンドポイント情報が出力される。

sls deploy -v

(省略)

Serverless: Stack update finished...
Service Information
service: test-service
stage: dev
region: ap-northeast-1
stack: test-service-dev
api keys:
  None
endpoints:
  GET - https://(API Gatewayのパス).ap-northeast-1.amazonaws.com/dev/api/hello
  POST - https://(API Gatewayのパス).ap-northeast-1.amazonaws.com/dev/api/add
functions:
  hello: test-service-dev-hello
  add: test-service-dev-add

APIを呼び出してみる

GET /api/hello

f:id:hkou:20180417230326p:plain

POST /api/add

f:id:hkou:20180417230158p:plain