LoginSignup
205

More than 5 years have passed since last update.

Amazon API Gateway + Lambda + CloudSearchで検索APIサービスを作ってみる

Last updated at Posted at 2015-07-15

概要

Amazon API Gatewayが発表されましたね!
個人的にAPI系のサービスは大好きなので早速試してみました。

今回は掲題の通りAmazon CloudSearchの検索結果をLambda通してAPIとして提供する仕組みを作ってみました。

Lambda

var aws = require('aws-sdk');

var cloudsearchdomain = new aws.CloudSearchDomain({
  endpoint: '<CloudSearchのエンドポイント>'
});

exports.handler = function(event, context) {
    var params = {
                    query:event.q
                };
    cloudsearchdomain.search(params, function(err, data) {
        if (err) {
            console.log("error  " + err);
        } else {
            if (data.hits.found > 0) {
                console.log(data.hits.hit[0]);
                context.done(null,  data.hits.hit[0]);
            } else {
                console.log('not found');
                context.done(null, 'error');
            }
        }
    });
};

Lambdaファンクションを作成します。event.qにてAPIから検索文字列を渡してもらって、それをそのままCloudSerch側へ投げ、結果をjsonで出力するというコードになっています。

CloudSearch

スクリーンショット 2015-07-16 7.22.58.png
CloudSearch側には検索用のドメインを新規に作成して、
こんな感じの簡易な検索用のCSVをアップすることにします。

API経由でこのデータに対してアクセスを行い、検索データを取得する流れです。

Amazon API Gateway

スクリーンショット 2015-07-16 7.32.54.png
こういったAPIを作成しました。GETメソッドでqというクエリストリングを受け取り、Lambdaからの返り値を返します。

クエリストリングの設定

スクリーンショット 2015-07-16 7.36.15.png
Method Reauestにてクエリストリングが必要となる設定を行います。

スクリーンショット 2015-07-16 7.37.11.png
Integration Requestでも渡ってきたクエリストリングがLambdaに渡せるように上記設定を行います。

APIキーの設定

API Gateway.png
また、検索サービスを想定してAPIキーを作って認証の仕組みも作ってあげます。
API KeysでAPIキーを作って、Method ReauestからAPI Key Requiredをtrueに設定しましょう。

APIのテストからデプロイ

スクリーンショット 2015-07-16 7.43.48.png
準備が整ったので、APIのテストを実行します。クエリストリングに「banana」を入力すると正しく結果が返ってきました。問題ないので「Deploy API」からAPIを公開します。

API Gateway.png
これで「Invoke URL」にAPI用のエンドポイントが公開されました。

実行

curl --header 'x-api-key:<APIキー>' https://<APIエンドポイント>/prod?q=banana
としてリクエストを送ります。

スクリーンショット 2015-07-16 7.54.19.png
はい、こんな感じで正しく結果が返ってきました。

まとめ

APIサービスがEC2無しで数時間でつくれちゃうのはすごいなと実感しました。
実際にAPIを作るときに面倒なのが認証の仕組みやAPIキーの管理ってとこだと思いますが、それもAPI Gatewayの中で管理してくれるのはすごくありがたいですね!

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
205