Consuming a Google URL Shortener API from C#

by Tapas Pal
Consuming a Google URL Shortener API from C#

Explore the Google URL Shortener API and observe its use with the examples provided.


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 =

      static void Main(string[] args)

         var longUrl = "https://www.codeguru.com/csharp/.net/
         Console.WriteLine($"Short URL:" +  MyURLShorten(longUrl));

      public static string MyURLShorten(string Longurl)
         string post = "{\"longUrl\": \"" + Longurl + "\"}";
         string MyshortUrl = Longurl;
         HttpWebRequest Myrequest = (HttpWebRequest)WebRequest
            url?key=" + APIkey);

            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 =
               byte[] postBuffer = Encoding.ASCII.GetBytes(post);
               requestStream.Write(postBuffer, 0,

            using (HttpWebResponse response =
               using (Stream responseStream =
                  using (StreamReader responseReader = new
                     string json = responseReader.ReadToEnd();
                     MyshortUrl = Regex.Match(json, @"""id"":
         catch (Exception ex)
         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 =

   static void Main(string[] args)

      var longUrl = "https://www.codeguru.com/csharp/.net/net_asp/
      var Shorturl = MyURLShorten(longUrl);
      Console.WriteLine($"Short URL: " + Shorturl);
      Console.WriteLine($"Long URL: " + MyURLUnShorten(Shorturl));

   public static string MyURLUnShorten(string ShortUrl)
      UrlshortenerService Myservice = new UrlshortenerService(new
      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.


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

This article was originally published on Tuesday May 29th 2018
Mobile Site | Full Site