Skip to content

Instantly share code, notes, and snippets.

@takaaki
Created September 28, 2009 05:15
Show Gist options
  • Save takaaki/195177 to your computer and use it in GitHub Desktop.
Save takaaki/195177 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# Shorten a URL using bit.ly API
# http://code.google.com/p/bitly-api/wiki/ApiDocumentation
# Login name and API key are required. Available by singing up on the site.
# TODO: Accept more than one URL at a time.
# TODO: URL needs to be escaped. Is 'cgi' class already included in ActiveSupport?
# TODO: Invalid URL string should get an error.
# TODO: Make this into a Mac OS X service and a TextMate command
require 'net/http'
require 'uri'
require 'rubygems'
require 'active_support' # Using ActiveSupport because it comes with every Mac
LOGIN = ""
API_KEY = ""
BASE_API_URL = "http://api.bit.ly"
PATH = "/shorten"
url = "http://example.com"
# Plan to use STDIN.read when I convert this to a TextMate or service.
# url = STDIN.read
uri = URI.parse(BASE_API_URL)
uri.path=PATH
uri.query=("version=2.0.1&longUrl=#{url}&login=#{LOGIN}&apiKey=#{API_KEY}")
result = Net::HTTP.get(uri)
result = ActiveSupport::JSON.decode(result)
if result["errorCode"] == 0
puts result["results"][url]["shortUrl"]
else
puts "Something is wrong."
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment