Building a URL shortener with Azure serverless functions and tables storage

Hello and welcome to another tutorial. This time we’ll learn how to build a URL-shortener with Azure serverless functions and tables storage but first: What is a URL shortener?

In the case you never heard about it, a URL shortener is a web service that allows to redirect users accessing a short URL to a longer one. This service is very useful in many scenarios.

Apart from shortening URLs, you can imagine having several short URLs redirecting to the same target URL and then give each of the short ones to different users, this might be helpful to know which of the users accessed the final URL. It might also be helpful when sharing web content in different social networks, you might use one short URL to share in Instagram, another different in Facebook and so on, all of them targeting the same destination URL helping you to get stats on where your shared content have more audience. These are only a few among the large advantages this services have.

Today i’ll show you how easy and quick it is to implement it using Azure Functions and tables storage but first let’s talk about some key concepts:

Azure Functions

Azure Functions is an event driven, compute-on-demand experience that extends the existing Azure application platform with capabilities to implement code triggered by events occurring in Azure or third party service as well as on-premises systems.

Azure tables storage

A NoSQL key-value store for rapid development using massive semi-structured datasets

Requirements

  1. You need to have an Azure account to follow this tutorial as we will create some resources on it.
  2. You will need Visual Studio 2019, even if this is not mandatory to create and deploy Azure Functions, the tutorial will be based on VS approach.

Hands on action

We need to create an Azure function that will be triggered by HTTP requests, taking an id from the URL parameters and redirecting requests to the corresponding final URLs by looking them up in an Azure storage table. The table which is a key/value storage will contain the URL ids and the corresponding target URLs.

  1. Open Visual Studio and create a new project. On “Project Templates” select “Azure Functions” and give a name to the project.
  2. Next you have to select how the function will be triggered. Select Http trigger since the function will respond to HTTP requests.
  3. In “Storage Account” dropdown select “Browse” and click on “+” to create a new storage account if you haven’t created one yet, give it a name and Select the location closest to you.
  4. Select your newly created storage account.
  5. Set the Authorization level to Anonymous and then click on Create.

Now if you go to Function1.cs you should have something similar to the following:

This is a simple function triggered by an HTTP call, the function will try to get a parameter “name” from the URL and will respond with a “Hello” message.

We need to install a nuget package: Azure.Data.Tables, at the time of writing this post this package is still in prerelease, so if you are using VisualStudio nuget package manager you need to check Include prerelease option or you can also use the package manager console and type:

Let’s create a new Entity class to map the table data:

We will use Url property to store the final URLs we want to redirect requests to. PartitionKey and RowKey are unique identifiers for every table entry. Azure tables use partitions to better index data when storing high volumes of information, in our case we will always use the same partition key, however it is straightforward to change the code if you want to make use of built-in partitioning. We will use RowKey as a unique ID to retrieve our URLs. Timestamp and ETag are properties contained in the contract of the ITableEntity interface, even if we’re not using them, we have to define them in out class.

Go to your Azure portal, retrieve the storage account connectionString and set it to a string constant. It should look similar to the following:

To do so, you should login to your azure account, click on All resources, then click your storage account name, then under Settings/Access Keys click on Show keys and copy the ConnectionString value.

Now let’s replace the function body with the following:

This function first tries to retrieve a parameter “id” from the URL, then creates a TableClient which will help to read the Azure table. Once we have the URL id and the table client we try to get a table entry with RowKey equals to the given id and then returns a redirection response targeting the destination URL.

Now let’s run the Function program in VisualStudio. It should log in the console the list of hosted functions. In a functions app you can host multiple Azure functions. By running the program you should be able to see something like:

Copy the given URL and paste it in your browser, add ‘?id=1234’ at the end of the URL like: “http://localhost:7071/api/Redirect?id=1234".
You should get a NotFound HTTP response with message “The requested URL was not found” which is normal since we haven’t created any URL mapping yet. However by doing this we will have our Azure table UrlMapping created.

We can verify it in the Azure portal by clicking in Storage Explorer in the storage account section. (i highly recommend using the desktop app, you can download it here: https://azure.microsoft.com/en-us/features/storage-explorer/)

Inserting some URL mappings

  1. click on UrlMapping table and then click on Add
  2. Fill PartitionKey with 0 and RowKey with 1234
  3. Click on “Add Property”, fill PropertyName with ‘Url’, Type with String and Value with some URL, for example: https://www.nandocontreras.net/
  4. Click on insert and ensure your program is still running. Go to the URL: http://localhost:7071/api/Redirect?id=1234

If you get redirected to the URL you inserted in the table you are successfully up and running with the URL shortener.

Let’s see some other interesting feature you can also use with URL redirects.

File sharing with Azure Blob storage

Blob storage is the cloud storage from Microsoft Azure, it allows you to store files in the cloud and share them with a public URL. Let’s take a pdf file and put it in a Blob Container.

  1. Again in the Storage Explorer right click on Blob Containers and then click on Create blob container
  2. Let’s fill the name with ‘files’ and Public access level with ‘Blob (anonymous read access for blobs only)’
  3. Click on files Blob container from the list and then click on Upload
  4. Select a pdf file and click Upload
  5. Right click on the just created file and then click on Properties
  6. Copy the Uri value and now create a new URL mapping in the storage table like you already did but this time with RowKey: ‘1111’ and the Url you just copied. Keep PartitionKey with 0
  7. Click on Insert and now go to http://localhost:7071/api/Redirect?id=1111

If everything went well so far, you should get access to your pdf file.

From now on you should be able to implement your own ideas from the code we just created. For example you could add a new column to keep a count of the times every URL was accessed, or you could create another function to insert new URLs. Am not covering those features in this post because it’s pretty straightforward and by now you should be able to try it yourself.

Am not covering this time deploying functions to Azure, but it’s pretty easy to do from VisualStudio publishing tool or even VSCode.

Thanks for reading and enjoy Azure features, they are exciting !

Originally published at https://www.nandocontreras.net.

Software Engineer & Machine Learning Engineer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store