Skip to main content

Simplest bit.ly API implementation possible?

Blog post   •   Jul 02, 2009 16:03 GMT

To use an URL shortener in your project, I would strongly recommend bit.ly. It let you set a custom URL (name) and track traffic, clicks and conversations on micro blogs. But best of all, it should be super-fast and super-stable, since Twitter recently chose bit.ly as their default URL shortening service.


Using the bit.ly REST API is also super-easy! Here is how you do it in Rails:



  1. Sign up to get your API username/password here.

  2. Get HTTParty if you don't already use it: sudo gem install httparty

  3. Copy the code:
    require 'httparty'
    
    class Bitly
        include HTTParty
        base_uri 'api.bit.ly'
        basic_auth 'username', 'password'
        format :json
        def self.shorten(url)
            response = get('/shorten', :query => required_params.merge(:longUrl => url))
            response['results'][url]['shortUrl']
        end		
        def self.required_params
            	{:version => "2.0.1"}
        end
      end


  4. Paste code into lib/bitly.rb. Usage: Bitly.shorten("longurl")


This is perfect for, as an example Tweeting your URL's. (I will get back to our Twitter API implementation at Newsdesk.)


The complete bit.ly API docs are here: http://code.google.com/p/bitly-api/wiki/ApiDocumentation


To extend and share this class - use my Gist: http://gist.github.com/112191

Comments (2)

    Works great!
    Thanks.

    - Pierre - Aug 06, 2009 20:50 GMT

    Hi!

    Thanks for such a knowledgeable post.

    - Kopi Hijau - Jun 09, 2016 03:56 GMT

Add comment

Comment