LoginSignup
22
16

More than 5 years have passed since last update.

Node.js から API Gateway を簡単に使えるパッケージ作りました

Last updated at Posted at 2017-01-10

はじめに

AWS API Gateway は便利なサービスですが、Node.js から使おうとすると、自動で生成される JavaScript のSDKがブラウザ用しか用意されていなかったり、エンドポイントごとにメソッドが自動で生成されていて、APIのエンドポイントを変更するごとにSDKを生成し直さなければならなかったりと不便だったため、Node.js から API Gateway を簡単に使えるパッケージを作りました。

aws-api-gateway-client
https://github.com/kndt84/aws-api-gateway-client

参考:
API Gateway で生成した JavaScript SDK を使用する
IAM認証(AWS SignatureV4)でAPIGatewayをNode.jsから呼び出す

事前準備

APIを利用するためには、Cross-Origin Resource Sharing (CORS) を有効にする必要がありますので、下記のページを参考にCORSを有効にします。

API Gateway リソースの CORS を有効にする

インストール

npm コマンドでインストール可能です。

npm install aws-api-gateway-client

SDKの利用

モジュールのリクエスト

var apigClientFactory = require('aws-api-gateway-client')

クライアントの作成

config に invokeUrl を設定して、クライアントオブジェクトを生成します。ただし、config にはIAMもしくはAPIキーを追加で設定する必要があり、これらは下記で説明します。

config = {invokeUrl:'https://xxxxx.execute-api.us-east-1.amazonaws.com'}
var apigClient = apigClientFactory.newClient(config);

 IAM認証

AWSの認証情報を利用してアクセスする場合は、クライアントオブジェクトを生成する時点で、invokeUrl に加えて、アクセスキー、シークレットキー、セッションキーを下記の通り設定します。


var apigClient = apigClientFactory.newClient({
    accessKey: 'ACCESS_KEY',
    secretKey: 'SECRET_KEY',
    sessionToken: 'SESSION_TOKEN', //OPTIONAL: If you are using temporary credentials you must include the session token
    region: 'eu-west-1' // OPTIONAL: The region where the API is deployed, by default this parameter is set to us-east-1
});

 APIキー認証

APIキーを使う場合は、invokeUrl に加えて、下記の通りキーを設定します。

var apigClient = apigClientFactory.newClient({
    apiKey: 'API_KEY'
});

パラメータの設定

var params = {
    //This is where any header, path, or querystring request params go. The key is the parameter named as defined in the API
    userId: '1234',
};
// Template syntax follows url-template https://www.npmjs.com/package/url-template
var pathTemplate = '/users/{userID}/profile'
var method = 'GET';
var additionalParams = {
    //If there are any unmodeled query parameters or headers that need to be sent with the request you can add them here
    headers: {
        param0: '',
        param1: ''
    },
    queryParams: {
        param0: '',
        param1: ''
    }
};
var body = {
    //This is where you define the body of the request
};

APIのコール

上記で設定したパラメータを下記のように引数にとってAPI をコールします。API はプロミスオブジェクトを返し、成功または失敗のコールバック関数を呼びます。

apigClient.invokeApi(params, pathTemplate, method, additionalParams, body)
    .then(function(result){
        //This is where you would put a success callback
    }).catch( function(result){
        //This is where you would put an error callback
    });
22
16
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
22
16