Google URL Shortener API – Shorten URL – Dot Net – OAuth

By Anil Gupta, 0  Tech Tips

Use Google URL shortener API in .net with oAuth to generate short URLs with server to server communication. This is a complete step by step guide.


We are using the Google URL Shortener API to generate short URL’s for our Take home Salary India application.

Since, the application has been written in .Net, I found it a bit challenging to find the complete step by step documentation to make everything work in one shot for a web application.

I was finally able to put everything together and got it to work. Here is the crux of whole story.

Using Gogle URL hortener api in dot net

Using Gogle URL hortener api in dot net

Before you start

You can generate short URL’s with Google API without oAuth authentication as well.

But, in-case you want to track the short url click analytics, you would need to use the server to server communication using oAuth to generate the shortened versions. We wanted to see the analytics and hence used oAuth.

Here are the steps I followed:

1. Setting Up Google API

  1. Download .Net Library

    Download/Install the NuGet package in Visual Studio. The link is available here on Google.

  2. Create a Google application

    To use the Google API service, you need to create an application in their developer console first.Then go to this Google Help Page and follow the instructions to generate the API key.
    The steps are mentioned under heading ‘Authorizing requests with OAuth 2.0’. and ‘Acquiring and using an API key’.

  3. Switch ON the Google Shortener API service

    This is the most probable area of issues. Make sure that you have switched ON the Google Shortener API on developer console.

  4. Private key and JSON file

    You should now have the private key file and the JSON file that you must have download from your developer console. Save them in the root of your web application.

    Google URL shortener api - get client keys from developer console

    Google URL shortener api – get client keys from developer console

2. Dot Net code

  1. App settings

    I used app.config file to store all the API keys. You can hard code them or use the way I did. Replace the values in RED with your specific application’s details.
    <appSettings>
    <!--Get these values from https://console.developers.google.com/project/[YOUR PROJECT NAME]/apiui/credential -->
    <add key="IHSGoogleURLShortnerAppName" value="IHSIndia-url-shortner" />
    <!-- The actual json file is stored in application root-->
    <add key="IHSGoogleURLShortenerJSONFileName" value="client_secret_123456789.apps.googleusercontent.com.json" />
    <add key="IHSGoogleURLShortenerAPIKey" value="abcdefghijklmnopqrst-abcdefg0987hgf" />
    <add key="IHSGoogleURlShortenerPrivateKeyName" value="123456789abcdefghe1234567abcdefghe-privatekey.p12"/>
    <add key="IHSGoogleURlShortenerPrivateKeySecret" value="NOTASECRET"/>
    <add key="IHSGoogleURLShortenerServiceAcEmail" value="12345678912345-abcdefgheijklmnop@developer.gserviceaccount.com"/>
    </appSettings>

  2. Generate Short URL code
    Shorten URL function

    using System;
    using System.Collections.Generic;
    using System.Web;

    using System.Configuration;
    using System.Security.Cryptography.X509Certificates;
    using System.Threading;
    using System.Data;
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Urlshortener.v1;
    using Google.Apis.Urlshortener.v1.Data;
    using Google.Apis.Services;

    public static string shortenURL(string urlToShorten, string webSiteBasePath)
    {
    string shortURL = string.Empty;

    try
    {
    /********************************************************************/
    string AuthenticationToken = string.Empty;
    var certificate = new X509Certificate2(webSiteBasePath + "/" + ConfigurationManager.AppSettings["IHSGoogleURlShortenerPrivateKeyName"].ToString(),
    ConfigurationManager.AppSettings["IHSGoogleURlShortenerPrivateKeySecret"].ToString(),
    X509KeyStorageFlags.MachineKeySet |
    X509KeyStorageFlags.PersistKeySet |
    X509KeyStorageFlags.Exportable);

    String serviceAccountEmail = ConfigurationManager.AppSettings["IHSGoogleURLShortenerServiceAcEmail"].ToString();

    ServiceAccountCredential credential = new ServiceAccountCredential(
    new ServiceAccountCredential.Initializer(serviceAccountEmail)
    {
    Scopes = new[] { UrlshortenerService.Scope.Urlshortener }
    }.FromCertificate(certificate));

    if (credential.RequestAccessTokenAsync(CancellationToken.None).Result)
    {
    AuthenticationToken = credential.Token.AccessToken;
    }
    // Create the service.
    var service = new UrlshortenerService(new BaseClientService.Initializer()
    {
    HttpClientInitializer = credential,
    ApplicationName = ConfigurationManager.AppSettings["IHSGoogleURLShortnerAppName"].ToString(),
    });

    // Shorten URL
    Url toInsert = new Url { LongUrl = urlToShorten };

    toInsert = service.Url.Insert(toInsert).Execute();
    shortURL = toInsert.Id;
    }

    return (shortURL);
    }

    The code simply creates a server to server connection (from your web server to Google’s server) and gets an Authentication Token for the request. It then uses the token to generate the short URL with the long URL that you must pass in.

    You can call this function using the following code:
    String shortURL = ShortURL.shortenURL(url, Server.MapPath("~"));

Demo?

Head over to this Take home Salary India application and click on ‘Share’ button.
You will be presented with a short URL that we are generating using the above code.

In the next article, I would share the mechanism to read the short URL Analytics.