ほんじゃらねっと

ダイエット中プログラマのブログ

bit.lyのAPI経由で自分のBitlink履歴を取得するGroovyスクリプト

HTTP BuilderのRESTClientを使うと、Web APIとの連携が簡単にできるようだ。

bit.lyに記録したブックマークを分析したかったので、API経由でbitlinkを ダウンロードするスクリプトを書いてみた。 他にエクスポート機能が見当たらなかったのだけど、 API経由で取得するしかないのだろうか。

bit.lyのAPIAPIキーを取得し、OAuth認証Access Tokenを取得して 利用するのが通常なのだけど、自分のデータだけを利用するならば settings > Advanced > OAuth Applications > Generic Access Token で作成したAccess Tokenを使って簡単にアクセスできる。 (外部に漏れないように注意)

read_bitly_links.groovy

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7')

import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.*

// generated at settings page
def ACCESS_TOKEN='<Access Token>'

def ENDPOINT_BASE = 'https://api-ssl.bitly.com/'

def bitly = new RESTClient(ENDPOINT_BASE)

try {
    def response = bitly.get(
        path: 'v3/user/link_history',
        query: [
            'access_token': ACCESS_TOKEN
        ]   
    )   

    response.data.data.link_history.each {history ->
        println '---------'
        println 'long_url: ${history.long_url}'
        println 'title: ${history.title}'
        println 'created_at: ${history.created_at}'
        println 'client_id: ${history.client_id}'
    }

} catch (ex) {
    println ex
    println ex.message
    println ex.cause
    println ex.suppressed
    println ex.response.data
    println ex.response.statusLine
    println ex.response.allHeaders
}

Webを支える技術 -HTTP、URI、HTML、そしてREST (WEB+DB PRESS plus)

Webを支える技術 -HTTP、URI、HTML、そしてREST (WEB+DB PRESS plus)