Shortening URLs with bit.ly’s API in .NET
I previously wrote about shortening URLs with TinyURL’s API but my new favorite URL shortener is http://bit.ly and it also has a great API that you can use from within your .net code. I just recently used in my twitter contest website – tweetastica.
The code is also very simple. I didn’t add all the extra options that the API makes available and just wrote enough for me to shorten a URL. Here it is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<span style="color: #0000ff">public</span> <span style="color: #0000ff">static class</span> BitlyApi { <span style="color: #0000ff">private</span> <span style="color: #0000ff">const</span> <span style="color: #0000ff">string</span> apiKey = <span style="color: #006080">"[add api key here]"</span>; <span style="color: #0000ff">private</span> <span style="color: #0000ff">const</span> <span style="color: #0000ff">string</span> login = <span style="color: #006080">"[add login name here]"</span>; <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> BitlyResults ShortenUrl(<span style="color: #0000ff">string</span> longUrl) { var url = <span style="color: #0000ff">string</span>.Format(<span style="color: #006080">"http://api.bit.ly/shorten?format=xml&version=2.0.1&longUrl={0}&login={1}&apiKey={2}"</span>, HttpUtility.UrlEncode(longUrl), login, apiKey); var resultXml = XDocument.Load(url); var x = (from result <span style="color: #0000ff">in</span> resultXml.Descendants(<span style="color: #006080">"nodeKeyVal"</span>) select <span style="color: #0000ff">new</span> BitlyResults { UserHash = result.Element(<span style="color: #006080">"userHash"</span>).Value, ShortUrl = result.Element(<span style="color: #006080">"shortUrl"</span>).Value } ); <span style="color: #0000ff">return</span> x.Single(); } } <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> BitlyResults { <span style="color: #0000ff">public</span> <span style="color: #0000ff">string</span> UserHash { get; set; } <span style="color: #0000ff">public</span> <span style="color: #0000ff">string</span> ShortUrl { get; set; } } |
Using this code is very straight forward.
1 |
var shortUrl = BitlyApi.ShortenUrl(<span style="color: #006080">"http://www.verylongUrl.com"</span>).ShortUrl; |
bit.ly has tons of features and a great API. You can even see stats of any bit.ly generate url using /info. for example: http://bit.ly/info/S0vRy shows you stats for http://bit.ly/S0vRy
Another feature I really like is their bookmarklet which you can keep on your browser’s bookmark bar and click it to shrink the site you are at… It even pops this side bar with a bunch of useful info.
The API is pretty well documented at http://code.google.com/p/bitly-api/wiki/ApiDocumentation
Don’t forget to follow me on twitter.