I was playing around with some updates I was making to Community Megaphone to add some simple features like a link to share each event via twitter, and one of the things I was trying out was dynamically turning the full URL for a given event’s details page into a bit.ly link, both to save characters when folks tweet it, but also to provide the ability to track how many clicks a given link is getting.

Using the bit.ly API is very straightforward, and it’s very easy to use the WebClient class in .NET to make a text request to the bit.ly API and return a string with the shortened URL (the result can also be returned as JSON and XML):

   1:  Public Shared Function ShrinkIt(ByVal Url As String) _
   2:     As String
   3:     Dim CT As HttpContext = HttpContext.Current
   4:   
   5:     ShrinkIt = ""
   6:     Dim WC As New System.Net.WebClient()
   7:     Dim bitLyUrl As String
   8:     bitLyUrl = "http://api.bit.ly/v3/shorten"
   9:     bitLyUrl &= "?login=yourusername&apiKey=yourApiKey&uri="
  10:   
  11:     ShrinkIt = WC.DownloadString(bitLyUrl & _
  12:        CT.Server.UrlEncode(Url) & "&format=txt")
  13:     Return CT.Server.HtmlEncode(ShrinkIt)
  14:  End Function

(note that I broke some of the code up a bit to fit the formatting of the blog, but the code above should still work, if you supply your account info)

Making things easier, when you sign up for an account, bit.ly supplies you with an API key to go along with your username, so you don’t have to share or embed your account password in your code. Good practice.

One thing I didn’t count on, however, is that the API expects to see the username in lowercase. So even if you signed up for an account with mixed case letters, you need to embed it in the request URL as lowercase. Otherwise you end up with a nice fat 500 error staring you in the face. I’ve highlighted the username portion of the API call in bold above.

Thankfully, it only took me a few minutes to figure out that was the problem, but in case anyone else ran into this, I thought it might be worthwhile to highlight it in a blog post. A good reminder to always be aware of whether the environment you’re working in cares about casing or not.

One other thing to consider…anytime you’re calling out to an external service, there’s a cost associated with that call. I ultimately ended up not using the method above because I don’t currently have time to implement it properly by either storing or caching the shortened URL returned from the API call. Without storing or caching the result, I would’ve ended up making up to 10 calls to the bit.ly API every time the home page was requested. Probably not the best idea performance-wise, wouldn’t you agree?