Mach3.laBlog

goo.glがAPI公開されたらしいので試してみた

この記事は賞味期限切れです。(更新から1年が経過しています)

Overview – Google URL Shortener API – Google Code
Google製の短縮URLサービス「goo.gl」のAPIが公開されたそうなので、
試しに使ってみたメモ。

goo.glがAPI公開されたらしいので試してみた

  1. 必要なもの
  2. 短縮してみよう
  3. 展開してみよう
  4. めんどくさいのでクラスにしてみる
  5. (おまけ) JavaScriptで展開する

必要なもの

APIのURLを控えておく
https://www.googleapis.com/urlshortener/v1/url
APIキーを取得しておく
Google APIs Console
「URL Shortener API」をアクティブにしてAPIキーを控えて来る

今回は、PHP+cURLでやってみることに。
とりあえず持っている情報を変数につっこむ。

$api_url = "https://www.googleapis.com/urlshortener/v1/url";
$api_key = "[あなたのAPIキーを入れてください]";

短縮してみよう

URLの短縮は、APIに次のようなJSONPOSTで送りつけます。

{“longUrl”: “http://www.google.com/”}

$longUrl = "http://blog.mach3.jp/";

$curl = curl_init();
$curl_params = array(
    // APIのURLに ?key=[your-key]を足してやります
    CURLOPT_URL => $api_url . "?" . 
        http_build_query( array( "key" => $api_key ) ),
    // ヘッダをapplication/jsonに
    CURLOPT_HTTPHEADER => array( "Content-Type: application/json" ),
    // POSTで送ります
    CURLOPT_POST => true,
    // ロングURLの情報をJSONに加工して渡します
    CURLOPT_POSTFIELDS => json_encode( array( "longUrl" => $longUrl ) ),
    CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array( $curl, $curl_params );
$result = json_decode( curl_exec( $curl ) ); // 返り値はJSONなのでデコード
var_dump( $result );

レスポンスはJSONで返って来るので、json_decodeでオブジェクトにしてやります。
最終的に格納されている情報はこんな感じ。

object(stdClass)#1 (3) {
  ["kind"]=>
  string(16) "urlshortener#url"
  ["id"]=>
  string(19) "http://goo.gl/ZZKde"
  ["longUrl"]=>
  string(21) "http://blog.mach3.jp/"
}

展開してみよう

展開は簡単。パラメータくっつけてGETでとってくるだけです。
先ほど作った「http://goo.gl/ZZKde」を展開してみます。
こんなリクエストをおくって返事をもらってるだけ。
労力惜しむならfile_get_contents()でもよし。

https://www.googleapis.com/urlshortener/v1/url?key=[your_api_key]&shortUrl=[展開したいURL]

$shortUrl = "http://goo.gl/ZZKde";

$curl = curl_init();
$curl_params = array(
    CURLOPT_URL => $api_url . "?" .
        http_build_query( array(
            "key" => $api_key,
            "shortUrl" => $shortUrl
        )),
    CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array( $curl, $curl_params );
$result = json_decode( curl_exec( $curl ) );

こんな感じに帰ってきました。

object(stdClass)#2 (4) {
  ["kind"]=>
  string(16) "urlshortener#url"
  ["id"]=>
  string(19) "http://goo.gl/ZZKde"
  ["longUrl"]=>
  string(21) "http://blog.mach3.jp/"
  ["status"]=>
  string(2) "OK"
}

めんどくさいのでクラスにしてみた

GoogleUrl
gist: 69e4a0c19e4776924a21 – Shorten and expand urls using Google URL Shortener API- GitHub

使い方

// createメソッドで初期化。
// new GoogleUrl( $api_key ) でもいいです。
$gu = GoogleUrl::create( "[your-api-key]" );

try {
    // shortenメソッドで短縮
    $shorten = $gu->shorten( "http://www.mach3.jp" );
    var_dump( $shorten );

    // expandメソッドで展開
    $expand = $gu->expand( $shorten->id );
    var_dump( $expand );

} catch( Exception $e ){ die( $e->getMessage() ); }

(おまけ) JavaScriptで展開する

gist: d98215a9cae6ef22e741 – expand url using goo.gl shortener api- GitHub

jQuery使って展開してみました。
「callback」パラメータでJSONP出来るので、大変簡単。
つまりこんなリクエストをすることになります。

https://www.googleapis.com/urlshortener/v1/url?key=[your_api_key]&shortUrl=[展開するURL]&callbck=[コールバック関数名]

var expandGoogleUrl = function( url, key, callback ){
    $.ajax({
        url : "https://www.googleapis.com/urlshortener/v1/url",
        dataType : "jsonp",
        data : { shortUrl : url, key : key },
        success : function( data ){
            callback( data.error  ? false : data.longUrl );
        }
    });
};

// example
expandGoogleUrl (
    "http://goo.gl/fbsS",
    "[your api key]",
    function( url ){
        console.log( url );
    }
);

QRコードがそのまま作れたり( http://goo.gl/pvqxy.qr )、
アクセス解析出来たり( http://goo.gl/info/pvqxy )と結構便利なサービスです。
短縮したい際には使ってみようかな!

コメント

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

*

Google URL Shortener API のまとめ | zes10.comd41d8cd98f00b204e9800998ecf8427e
Tweets that mention goo.glがAPI公開されたらしいので試してみた | Mach3.laBlog -- Topsy.comd41d8cd98f00b204e9800998ecf8427e