Consuming a Google URL Shortener API from C#

Many of us have faced issues while sharing a URL with others because it’s too long to be shared in its original form. Such long URLs affect the readability and flow of your message. URL shortening is a technique by which a Uniform Resource Locator (URL) is made substantially shorter in length, which is easily shareable and it redirects the user to the required page.

Google and many other Web sites have introduced APIs to solve this problem; the solution is this called a URL Shortener. It allows you to create a shorter version of a URL, which then gets expanded to the full original URL when accessed. Google provides a URL Shortener facility through its goo.gl Web site. It also provides a NuGet package for working with it. To shorten a URL manually, you can go to the goo.gl Web site and generate a short version of a URL. Google also provides an API for creating a shorter version of the URL from code. In this article, I will explain the Google URL Shortener API and demonstrate its use with examples.

Creating an API Key for Google API Web Requests

To use the Google URL shortener API, a developer needs an API key specific to your Google account. Navigate to the Google API console to get this API key. Click ‘GET A KEY,’ as shown in Figure 1.

Google API Console
Figure 1: Google API Console

Next, Select or Create a new project (see Figures 2 and 3).

Select/Create Project
Figure 2: Select/Create Project

Selected a Project
Figure 3: Selected a Project

Now, click “Enable API”. A key will be generated; in Figure 4, this has been obscured with a green line for security reasons. Copy that key. We need that key when calling the API.

Copy the API Key
Figure 4: Copy the API Key

Shortening a URL

The previously created created API key can be used in any ASP.NET project.

To demonstrate a URL Shortener with an example, I have created an ASP.NET MVC application in Visual Studio. After that, I have added MyURLShortener class.

The following MyURLShorten method is called from the main function to shorten a URL.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace GoogleURLShortener
{
   class MyURLShortener
   {
      private const string APIkey =
         "AIzaSyCZm9HvMq2NNOE3EPu56gbKFCFCK7qapKvC8";

      static void Main(string[] args)
      {

         var longUrl = "https://www.codeguru.com/csharp/.net/
            net_asp/mvc/best-practices-for-improving-web-
            application-performance.html/";
         Console.WriteLine($"Short URL:" +  MyURLShorten(longUrl));
         Console.ReadKey();

      }
      public static string MyURLShorten(string Longurl)
      {
         string post = "{\"longUrl\": \"" + Longurl + "\"}";
         string MyshortUrl = Longurl;
         HttpWebRequest Myrequest = (HttpWebRequest)WebRequest
            .Create("https://www.googleapis.com/urlshortener/v1/
            url?key=" + APIkey);

         try
         {
            Myrequest.ServicePoint.Expect100Continue = false;
            Myrequest.Method = "POST";
            Myrequest.ContentLength = post.Length;
            Myrequest.ContentType = "application/json";
            Myrequest.Headers.Add("Cache-Control", "no-cache");

            using (Stream requestStream =
               Myrequest.GetRequestStream())
            {
               byte[] postBuffer = Encoding.ASCII.GetBytes(post);
               requestStream.Write(postBuffer, 0,
                  postBuffer.Length);
            }

            using (HttpWebResponse response =
               (HttpWebResponse)Myrequest.GetResponse())
            {
               using (Stream responseStream =
                  response.GetResponseStream())
               {
                  using (StreamReader responseReader = new
                     StreamReader(responseStream))
                  {
                     string json = responseReader.ReadToEnd();
                     MyshortUrl = Regex.Match(json, @"""id"":
                        ?""(?<id>.+)""").Groups["id"].Value;
                  }
               }
            }
         }
         catch (Exception ex)
         {
            System.Diagnostics.Debug.WriteLine(ex.Message);
            System.Diagnostics.Debug.WriteLine(ex.StackTrace);
         }
         return MyshortUrl;
      }

   }
}

Unshortening a URL

The previous shortened URL could be converted to a long URL by using the Google-provided NuGet package that uses the Urlshortener API.

The prerequisites are:

  1. Create a public API key. (We have already created that in the previous step.)
  2. We have to add the Google.Apis.Urlshortener.v1 NuGet package in the project (already created).

Following is my sample code.

class MyURLShortener
{
   private const string APIkey =
      "AIzaSyCZm9HvMq2NNOE3EPu56gbKFCFCK7qapKvC8";

   static void Main(string[] args)
   {

      var longUrl = "https://www.codeguru.com/csharp/.net/net_asp/
         mvc/best-practices-for-improving-web-application-
         performance.html/";
      var Shorturl = MyURLShorten(longUrl);
      Console.WriteLine($"Short URL: " + Shorturl);
      Console.ReadKey();
      Console.WriteLine($"Long URL: " + MyURLUnShorten(Shorturl));

   }
   public static string MyURLUnShorten(string ShortUrl)
   {
      UrlshortenerService Myservice = new UrlshortenerService(new
         BaseClientService.Initializer());
      Myservice.ApiKey = APIkey;
      Myservice.ApplicationName = "MyCoolProject";
      return Myservice.Url.Get(ShortUrl).Execute().LongUrl;

   }
}

Other Alternatives

  • Bit.ly: Bit.ly is the most popular URL shortener. You can create a short link easily by clicking the ‘Bitlink’ button after pasting your long URL into the interface.
  • TinyURL: A free URL shortener, the TinyURL tool is heavily used by developers. TinyURL can suggest a shorter URL for you, or you can customize the result. Tinyit.cc also provides an easy-to-use Web API through which a user can create short links and get a number of hits for a short link.
  • URL Shortener by Zapier: You can use Owly to automatically shorten a link every time you schedule a social media update to post.

Conclusion

Hopefully, the preceding information related with Google’s URL shortener is useful for developers. That’s all for today. Keep reading my posts!

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read