Alibaba Cloud API Gateway を使ってみる

今回は、API Gatewayを使ってみます。API Gatewayのバックエンドには、Function Computeを使ってみます。

# Function ComputeでバックエンドAPIの作成
API Gatewayのトリガーを利用するには、テンプレートを使用するのが便利です。

![01.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/87f6d2d3-4e58-d594-c523-2bedd5712d20.png)
![02.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/bc143d75-54ef-24c7-209d-141d4f8c84b4.png)
![03.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/4571d633-e772-763d-43d8-914427d880a8.png)
![04.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/3e595e09-caaa-07ed-8021-9ba2623b6161.png)
![05.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/46dee39b-f9f7-8285-636f-3f6c13060c6a.png)
![06.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/43aac8b1-f9e9-81c7-e84f-5ab7e91e0322.png)
![07.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/d563ba60-5950-9446-91d8-7e12d91df469.png)


自動生成されたコードは以下の通りです。
パラメータ "response" に "json" を指定するとJSONが返却されます。

``` index.js
'use strict';

var fs = require("fs")

exports.handler = function (event, context, callback) {

    console.log("request: " + JSON.stringify(event.toString()));
    // convert event to JSON object
    event = JSON.parse(event.toString());
    var query = event.queryParameters || {};
    var showResponse = query.response || 'html';

    switch (showResponse) {
    case "html":
        var htmlResponse = {
            isBase64Encoded: true,
            statusCode: 200,
            headers: {
                "Content-type": "text/html; charset=utf-8"
            },
            // base64 encode body so it can be safely returned as JSON value
            body: new Buffer("<html><h1>hello FunctionCompute</h1></html>").toString('base64')
        }
        callback(null, htmlResponse);
        break;
    case "json":
        var jsonResponse = {
            isBase64Encoded: true,
            statusCode: 200,
            headers: {
                "Content-type": "application/json"
            },
            // base64 encode body so it can be safely returned as JSON value
            body: new Buffer('{"hello": "FunctionCompute"}').toString('base64')
        }
        callback(null, jsonResponse);
        break;
    case "image":
        fs.readFile(process.env.FC_FUNC_CODE_PATH + "/fc.png", (err, data) => {
            if (err) {
                callback(null, err);
                return;
            }
            var imageResponse = {
                isBase64Encoded: true,
                statusCode: 200,
                headers: {
                    "Content-type": "image/png"
                },
                // base64 encode body so it can be safely returned as JSON value
                body: data.toString('base64')
            }
            callback(null, imageResponse);
            return;
        });
        break;
    default:
        var htmlResponse = {
            isBase64Encoded: true,
            statusCode: 200,
            headers: {
                "Content-type": "text/html; charset=utf-8"
            },
            // base64 encode body so it can be safely returned as JSON value
            body: new Buffer("<html>Please hit the url with response=html, reponse=json, or reponse=image</html>").toString('base64')
        }
        callback(null, htmlResponse);
    }
};
```

# API Gateway APIグループを作成する
API GatewayでAPIを公開するためには、まずAPIグループの作成を行います。

![10.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/30adab95-4d3b-d75c-0d16-c12a50e6691a.png)
![11.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/3aea5b8f-e46b-36a5-7abd-16c3d02464bc.png)
![12.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/7d9de3b4-d542-d82c-11c5-700a4216df6b.png)
![13.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/e6484a11-e6b1-bbda-c42d-37c4928f6148.png)
![14.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/fb33bf36-5e7b-3d9e-e806-735407b622d5.png)

## 認証なしのAPIを公開する
APIグループが作成できたので、公開APIを作成します。まずは、認証なしのAPIを作成してみます。

![20.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/0eb5c4c1-0fbe-edda-f3d5-a309744644a7.png)
![21.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/15f4a9da-6b63-5f15-e841-a1fa8fe43be4.png)
![22.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/dea2f5ff-9028-41c4-f372-77f341ad93ed.png)
![23.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/befb9a74-c6a8-e9c8-8851-15bd57ebe63e.png)
![24.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/a6c277ad-23e6-c203-a2c9-67e63f77e908.png)
![25.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/923518fd-2b0a-169f-9e4b-00b0dc25e3da.png)
![26.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/a103aee0-7459-da96-f7b3-a8939fb6d88b.png)
![27.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/97a4e5d5-29dc-aa35-21eb-ac0a39acfede.png)
![28.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/4782e573-a0fd-30e0-176b-d60dd2c043ba.png)
![29.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/4639c842-45d0-2787-35c1-88ec75e301d9.png)
![30.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/72fcaf66-12fe-2820-cc67-36508e1f6e4e.png)

### 動作確認
![31.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/18582/364130f1-a8c1-f0bf-5c4a-debee015cf8b.png)

``` apigw-sample.html
<!DOCTYPE html>
<html>

<head>
    <title>Image Search Add Sample</title>
    <meta charset="utf-8">
</head>

<body>
    <h1>API Gatewayサンプル</h1>
    <div>
        <input id="call-gw" type="button" value="データ取得">
    </div>

    <script>
        //イベントの登録
        document.addEventListener('DOMContentLoaded', () => {
            const callgw = document.getElementById('call-gw');
            const params = {"response" : "json"}
            const qs = new URLSearchParams(params);
            callgw.addEventListener('click',(e) => {
                fetch(`http://xxxxxxxxxxxxxxx-ap-northeast-1.alicloudapi.com/hello?${qs}`, {
                    method: 'GET',
                    headers: {
                        "Content-Type": "application/json; charset=utf-8"
                    },
                })
                    .then((response) => {
                        if (response.status === 200) {
                            return response.json()
                        } else {
                            console.log('Bad')
                        }
                    })
                    .then((obj) => {
                        console.log(JSON.stringify(obj, null, 4))
                    })
                    .catch((err) => {
                        console.log('Error Occurred')
                        console.log(err)
                    })
            })
        })

    </script>
</body>

</html>
```

# まとめ
今回は、API Gatewayを試してみました。今回はパススルーで設定してしまいましたが、パラメータやレスポンス設計はこちらでしっかりと行う必要だと思います。
また、今回は公開設定にしましたが、実際は認証処理は必要になると思います。次回は、セキュリティ認証方式の中で「Alibaba Cloudアプリ」を使ったものを紹介します。