URL短縮サービス j.mp のAPIを呼び出してみた

j.mpのアカウントをとるとAPI KeyがもらえてAPIでURLを短縮できるようになる。
ということで、短縮してみた。

require 'rubygems'
require 'net/http'
require 'json'
require 'uri'

class BitLy
  def initialize(login_id, api_key)
    @login_id = login_id
    @api_key = api_key
  end 

  def shorten(url)
    query = "version=2.0.1&longUrl=#{URI.escape(url)}&login=#{@login_id}&apiKey=#{@api_key}"
    result = JSON.parse(Net::HTTP.get("api.j.mp", "/shorten?#{query}"))
    result['results'][url]['shortUrl']
  end 
end

クラス名がBitLyなのはサービスを行っているのがbit.lyだから。Net::HTTP.get("api.j.mp", ... のところを Net::HTTP.get("api.bit.ly", ... に書き換えるとbit.lyで短縮できる。

使い方

bitly = BitLy.new(アカウント名, API Key)
short_url = bitly.shorten('http://www.example.com/long_long_url')
puts short_url

[追記]
URIエスケープが抜けていたので修正。