web 2.0

Building a Url Shortener with the bit.ly API

It seems like url shorteners have become very popular these days. Especially with applications like twitter who limit your messages to only 140 characters. The cool thing is that most of the URL shorteners have API's that you can use if you want to integrate them into your application. If you are interested in test driving the bit.ly engine then here are the steps:

Go to the bit.ly website and create a free account. Once registered you will receive a username and an API key. You will need these later on when we write the code so make sure you keep these values handy. Since I am using jQuery for this project you will need to add a reference to the jQuery library. I like to use the Google CDN servers when possible but you can always download your own copy of jQuery.

<SCRIPT type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></SCRIPT>

Now we can create the HTML that will allow the user to enter a long url, click the "Shorten" button and get the bit.ly version:

<table>
    <tr>
        <th>Long Url:</th>
        <td>
            <input id="longUrl" style="width: 250px;" value="http://www.codecapers.com" type="text">
            <input id="btn" value="Shorten" type="button">
        </td>
    </tr><tr>
        <th>Short Url:</th>
        <td><input id="shortUrl" style="width: 150px;" type="text"></td>
    </tr>
</table>

Now, we need to write the jquery code to invoke the bit.ly shorten method. Replace the variables username and key with the values you received from creating your bit.ly account.

$(document).ready( function() {
    var username = "<your username>";
    var key = "<your api key>";        
    
    $("#btn").click( function() {          
        var longUrl = $("#longUrl").val();                
        $.post( "http://api.bit.ly/shorten", { version : "2.0.1", longUrl : longUrl, login : username, apiKey : key }, 
        function( data ) {            
            if( data == "" ) {
                alert( "failed to shorten url. No data returned" );
                return;
            }
                
            eval( "var info = " + data );                
            $("#json").html( data );                    
            if( info.statusCode == "OK" ) {                                    
                $("#shortUrl").val( info.results[longUrl].shortUrl );                                                                                            
            }
            else {
                alert( info.errorMessage );
            }
        }); 
    });
});


Here is the breakdown: In the jQuery document.ready event we wire an event that gets fired when the user click on the button. When the button is clicked an Ajax call is made to http://bit.ly/shorten. The shortenmethod takes a series of parameters which are passed in as an object array in the secondary parameter of the post method. When the event is returned, the anonymous function is called and we inspect the variable naned data to see if we got a response. If the response is not empty we use the eval function to serialize the string into a object. Once we deserialize the string we can check to see if a valid status code was returned. If the status code is "OK" we know the url was shortened and we can display the value in the shortUrl textbox, otherwise an error message is shown.

Just for informational purposes, here is a sample result of the shorten method:

{ "errorCode": 0, "errorMessage": "", "results": { "http://www.cnn.com": { "hash": "4qzXdz", "shortCNAMEUrl": "http://bit.ly/aPTRhZ", "shortKeywordUrl": "", "shortUrl": "http://bit.ly/aPTRhZ", "userHash": "aPTRhZ" } }, "statusCode": "OK" }

Pretty cool for a couple lines of html and a little jQuery!

Comments

DotNetKicks.com , on 1/31/2010 1:03:26 PM Said:

trackback

Building a Url Shortener with the bit.ly API

You've been kicked (a good thing) - Trackback from DotNetKicks.com

uberVU - social comments , on 1/31/2010 8:43:11 PM Said:

trackback

Social comments and analytics for this post

This post was mentioned on Twitter by mikeceranski: blogged:  Building a Url Shortener with the bit.ly API http://goo.gl/fb/DoIo #jquery #programming

Andrea United Kingdom, on 3/16/2010 6:14:06 AM Said:

Andrea

I am new to using jquery but I had added your code word for word but it is not working and throws up the error 'failed to shorten url. No data returned'

code looks like this
<SCRIPT type=text/javascript src="jquery.js"></SCRIPT>
<SCRIPT type=text/javascript src="shorturl.js"></SCRIPT> - this contains the text below

$(document).ready( function() {
    var username = "myusername";
    var key = "mykey";      
    $("#btn").click( function() {        
        var longUrl = $("#longUrl").val();              
        $.post( "http://api.bit.ly/shorten", { version : "2.0.1", longUrl : longUrl, login : username, apiKey : key },
        function( longUrl ) {          
            if( longUrl == "" ) {
               alert( "failed to shorten url. No data returned" );
                return;
            }
                
            eval( "var info = " + longUrl );              
            $("#json").html( longUrl );                  
            if( info.statusCode == "OK" ) {                                  
                $("#shortUrl").val( info.results[longUrl].shortUrl );                                                                                          
            }
            else {
                alert( info.errorMessage );
            }
        });
    });

});
and then the  form

<table>
    <tr>
        <th>Long Url:</th>
        <td>
            <input id="longUrl" style="width: 250px;" value="http://www.codecapers.com" type="text">
            <input id="btn" value="Shorten" type="button">
        </td>
    </tr><tr>
        <th>Short Url:</th>
        <td><input id="shortUrl" style="width: 150px;" type="text"></td>
    </tr>
</table>

Any help will be appreciated.

Thanks
Andrea

mikeceranski United States, on 3/16/2010 11:27:32 PM Said:

mikeceranski

Andrea,
   Try testing your login and key by entering this in a browser window:

api.bit.ly/shorten?version=2.0.1&longUrl=http://cnn.com&login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07

If that works then it has to be a syntax error. I you have IE8 you can set a breakpoint in your javascript code and step through the lines. Then you will get a better understanding of where the error is.

- Mike

Comments are closed