カタバミさんのプログラミングノート

日曜プログラマーがプログラミング関係のメモを記録するブログです。

Google APIs Client Library for JavaScriptからGoogle URL Shortener APIを使ってみる

はじめに

クライアントとしてGoogleの各種サービスを操作するAPIGoogle APIs Client Libraryの名前でJavaScriptを始めとした様々な言語に対して公開されています(for JavaScript含めて一部はベータ版)。ここではWindows上でJavaScript (AJAX)の為のライブラリGoogle APIs Client Library for JavaScriptを用いて短縮URLサービス(What is the URL Shortner API? - Google Developers)を利用してみます。

動作確認(デバッグ)の準備

Google APIs Client Library for JavaScriptを利用しようとGoogle ChromeおよびMicrosoft Internet Explorerで以下のページを開いたところ、どちらもURLのプロトコルが「file://」であることに起因するエラーが発生しました。これに関しては正当な解決策が存在するのかもしれませんが、ここではApache 2.2.1をインストールしてローカルホスト(http://localhost/http://127.0.0.1/)から実行することで一旦解決しました。

Apacheのインストールとlocalhost (127.0.0.1)の詳細に関しては多数のページが存在するので検索してみてください。

短縮URLを展開する(元のURLを取得する)

多くのAPIではClient ID等の作成が必要とされますが、短縮URLの展開に関してはそれらは必要とされません。HTML5で書いた具体的なコードは以下のようになります。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<script src="https://www.google.com/jsapi"></script>
<script>
google.load("jquery", 1);

function load() {
   gapi.client.load("urlshortener", "v1", function() {
       var request = gapi.client.urlshortener.url.get({
           shortUrl: "http://goo.gl/fbsS"       // (A)
           //shortUrl: "https://www.google.co.jp/"   // (B)
       });
       request.execute(function (response) {
           if (!response.error) {
               // 正常なGoogle短縮URLの場合(A)はこちら
               $(document.body).text(JSON.stringify(response));
           } else {
               // 不正なGoogle短縮URLの場合(B)はこちら
               $(document.body).text("Invalid URL? - " + JSON.stringify(response));
           }
       });
   });
}
</script>
<script src="https://apis.google.com/js/client.js?onload=load"></script>
</head>
<body>
</body>
</html>

実行結果(A)

{"kind":"urlshortener#url","id":"http://goo.gl/fbsS","longUrl":"http://www.google.com/","status":"OK","result":{"kind":"urlshortener#url","id":"http://goo.gl/fbsS","longUrl":"http://www.google.com/","status":"OK"}}

実行結果(B)

Invalid URL? - {"code":400,"message":"Invalid Value","data":[{"domain":"global","reason":"invalid","message":"Invalid Value","locationType":"parameter","location":"shortUrl"}],"error":{"code":400,"message":"Invalid Value","data":[{"domain":"global","reason":"invalid","message":"Invalid Value","locationType":"parameter","location":"shortUrl"}]}}

上のサンプルではGoogle AJAX APIs(旧式?)とGoogle Client Library for JavaScriptの2つのライブラリを使用しています。前者はjQueryの動的読み込み、後者はGoogle URL Shortner APIのために利用しています。

非同期処理の為に関数の引数に関数が多く指定されていますが、ここでは説明は省きます。