API のデータでGoogle Sheets を拡張
マクロ、カスタム関数、アドオンを使用してGoogle スプレッドシートからAPI のデータとやり取りします。CData API Server は、ADO.NET Provider for API(またはその他の250+ ADO.NET Providers)と組み合わせることで、Google Sheets のようなクラウドベースのモバイルアプリケーションからAPI のデータに接続できるようになります。API Server は、API およびCData ADO.NET Providers にサポートされるすべてのソースのOData サービスを生成する軽量のWeb アプリケーションです。
Google Apps Script(GAS)は、これらのOData サービスをJSON 形式で利用できます。この記事では、Google スプレッドシートにposts データを取り込み、変更を加えたときにAPI のデータの更新を実行するシンプルなアドオンを作成する方法を説明します。
API Server の設定
以下のリンクからAPI Server の無償トライアルをスタートしたら、セキュアなAPI OData サービスを作成していきましょう。
API への接続
GAS からAPI のデータを操作するには、まずyour API への接続を作成・設定します。
- API Server にログインして、「Connections」をクリック、さらに「接続を追加」をクリックします。
- 「接続を追加」をクリックして、データソースがAPI Server に事前にインストールされている場合は、一覧から「API」を選択します。
- 事前にインストールされていない場合は、コネクタを追加していきます。コネクタ追加の手順は以下の記事にまとめてありますので、ご確認ください。
CData コネクタの追加方法はこちら >> - それでは、API への接続設定を行っていきましょう!
-
To connect to your API, configure the following properties on the Global Settings page:
- In Authentication, select the Type and fill in the required properties
- In Headers, add the required HTTP headers for your API
- In Pagination, select the Type and fill in the required properties
After the configuring the global settings, navigate to the Tables to add tables. For each table you wish to add:
- Click "+ Add"
- Set the Name for the table
- Set Request URL to the API endpoint you wish to work with
- (Optional) In Parameters, add the required URL Parameters for your API endpoint
- (Optional) In Headers, add the required HTTP headers for the API endpoint
- In Table Data click " Configure"
- Review the response from the API and click "Next"
- Select which element to use as the Repeated Elements and which elements to use as Columns and click "Next"
- Preview the tabular model of the API response and click "Confirm"
- 接続情報の入力が完了したら、「保存およびテスト」をクリックします。
To connect to your API, configure the following properties on the Global Settings page:
- In Authentication, select the Type and fill in the required properties
- In Headers, add the required HTTP headers for your API
- In Pagination, select the Type and fill in the required properties
After the configuring the global settings, navigate to the Tables to add tables. For each table you wish to add:
- Click "+ Add"
- Set the Name for the table
- Set Request URL to the API endpoint you wish to work with
- (Optional) In Parameters, add the required URL Parameters for your API endpoint
- (Optional) In Headers, add the required HTTP headers for the API endpoint
- In Table Data click " Configure"
- Review the response from the API and click "Next"
- Select which element to use as the Repeated Elements and which elements to use as Columns and click "Next"
- Preview the tabular model of the API response and click "Confirm"
API Server のユーザー設定
次に、API Server 経由でAPI にアクセスするユーザーを作成します。「Users」ページでユーザーを追加・設定できます。やってみましょう。
- 「Users」ページで ユーザーを追加をクリックすると、「ユーザーを追加」ポップアップが開きます。
-
次に、「ロール」、「ユーザー名」、「権限」プロパティを設定し、「ユーザーを追加」をクリックします。
-
その後、ユーザーの認証トークンが生成されます。各ユーザーの認証トークンとその他の情報は「Users」ページで確認できます。
API 用のAPI エンドポイントの作成
ユーザーを作成したら、API のデータ用のAPI エンドポイントを作成していきます。
-
まず、「API」ページに移動し、
「 テーブルを追加」をクリックします。
-
アクセスしたい接続を選択し、次へをクリックします。
-
接続を選択した状態で、各テーブルを選択して確認をクリックすることでエンドポイントを作成します。
OData のエンドポイントを取得
以上でAPI への接続を設定してユーザーを作成し、API Server でAPI データのAPI を追加しました。これで、OData 形式のAPI データをREST API で利用できます。API Server の「API」ページから、API のエンドポイントを表示およびコピーできます。
API のデータを取得する
「Tools」->「Script Editor」とクリックして、スプレッドシートからScript Editor を開きます。Script Editor で次の機能を追加し、スプレッドシートにOData クエリの結果を入力します。
function retrieve(){
var url = "https://MyUrl/api.rsc/posts?select=Id,title,body,userId";
var response = UrlFetchApp.fetch(url,{
headers: {"Authorization":"Basic " + Utilities.base64Encode("MyUser:MyAuthtoken")}
});
var json = response.getContentText();
var sheet = SpreadsheetApp.getActiveSheet();
var a1 = sheet.getRange('a1');
var index=1;
var posts = JSON.parse(json).value;
var cols = [["Id","title","body","userId"]];
sheet.getRange(1,1,1,4).setValues(cols);
row=2;
for(var i in posts){
for (var j in posts[i]) {
switch (j) {
case "Id":
a1.offset(row,0).setValue(account[i][j]);
break;
case "title":
a1.offset(row,1).setValue(account[i][j]);
break;
case "body":
a1.offset(row,2).setValue(account[i][j]);
break;
case "userId":
a1.offset(row,3).setValue(account[i][j]);
break;
}
}
row++;
}
}
次のステップに従って、開いたタイミングでスプレッドシートに入力するインストール可能なトリガーを追加します。
- 「Resources」->「Current Project's Triggers」->「Add a New Trigger」とクリックします。
- 「Run」メニューで「retrieve」を選択します。
- 「From Spreadsheet」を選択します。
- 「On open」を選択します。
ダイアログを閉じると、アプリケーションへのアクセスを許可するように要求されます。
API のデータへの変更を追加する
以下の関数を追加し、セルへの変更をAPI Server に追加します。
function buildReq(e){
var sheet = SpreadsheetApp.getActiveSheet();
var changes = e.range;
var id = sheet.getRange(changes.getRow(),1).getValue();
var col = sheet.getRange(1,changes.getColumn()).getValue();
var url = "http://MyServer/api.rsc/posts("+id+")";
var putdata = "{\"@odata.type\" : \"CDataAPI.posts\", \""+col+"\": \""+changes.getValue()+"\"}";;
UrlFetchApp.fetch(url,{
method: "put",
contentType: "application/json",
payload: putdata,
headers: {"Authorization":"Basic " + Utilities.base64Encode("MyUser:MyAuthtoken")}
});
}
下記の手順に従って、アップデートトリガーを追加します。
- 「Resources」->「Current Project's Triggers」とクリックします。
- 「Run」メニューで「buildReqe」を選択します。
- 「From Spreadsheet」を選択します。
- 「On edit」を選択します。
「Publish」->「Test as Add-On」とクリックすることで、スクリプトを確認できます。バージョン、インストールタイプ、およびスプレッドシートを選択し、テストの構成を作成します。作成したら、選択して実行できます。
セルを変更すると、API Server はAPI のデータのアップデートを実行します。