Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Introduction to Azure Functions

DZone 's Guide to

Introduction to Azure Functions

Take a look at this tutorial that introduces you to Azure Functions and provides a brief tutorial of how to create a simple function.

· Cloud Zone ·
Free Resource

Azure Functions

As part of Microsoft's offer in the Platform-as-a-Service model, Azure Functions is one of Azure's Serverless alternatives. Launched in late 2016, currently, it has two versions of runtimes available, although the version 2.x is still in preview mode. This new version is adding Java as a programming language to those supported by version 1.x — C#, JavaScript, and F#.

Azure Functions is the on-demand execution of functions or small fragments of code based on events. As the cost is associated with the execution, if the function is not executed, there are no charges to pay. And if the event that triggers the execution occurs faster than the function, the platform executes the code in multiple threads without obstacles.

Azure Functions allows splitting an API into several independent functions following a microservice architecture

In concept, the code of each function has to be simple and conceived on a totally decoupled model. Azure sets a limit of maximum execution time for a function. Initially, it was 5 minutes, although this value is currently only the default value and can be extended by configuration to 10 minutes.

Tiggers & Bindings

Two of the main concepts of Azure Functions are the triggers and bindings that allow defining the different events that trigger the execution of the functions and which sources of data and services are going to be connected to exchange information.

For example, a function can not only be triggered from an HTTP invocation or a webhook, but also by events in other Azure services such as the Azure Cosmos DB database and the Azure Queue Storage message service. The complete list is in the documentation.

Creating Our Azure Account

To begin with, we must first create our Azure account. The great thing about Azure Functions is within the free services included when we created our account.

To start the creation of the account, we can go to the Azure site and select the option to create a free account. Since I had my Live.com account connected, it automatically took me to the identity validation options. The first step is identification by a telephone number, and you can ask to send a text message or call.

Then a credit card is needed, Visa or Mastercard. And the subscription process is complete. In my case, I already had an account created so we can directly create the first function.

Our First Azure Function App

When accessing the Azure portal, we go to the Create a resource option, which displays the menu of services that we can create. In the Azure Marketplace options, we chose Compute. And there we will see the different options that we can choose. In our case, we are going to select the Function App option.

We can also use the search engine at the top of the menu but you have to be careful because there is another service called almost the same — Function Bot.

After selecting Function App, it shows us the configuration options, such as the name — App Name — if it is going to be executed in Windows or Linux (in preview currently), in which geographical location Azure will execute the function and the type of necessary storage — although the Azure Function service has a free tier so always keep in mind that storage is not included.

In this case, the name of the Function App is ejemploArt.

And Now the Function...

After creating the Function App, which acts as a Functions collection, we can go to the corresponding menu option and see the one we just created with three options below, Functions, Proxies and Slots (preview). Each option has an icon More (+) when we put the cursor on it.


When we choose to create a new function, Azure presents a screen where we can choose the type of scenario that we want to cover and which language we are going to use. In our case, the default options, Webhook + API & C#, are fine. Azure automatically creates a Hello function. It also has an online editor included where we can program and check our functions, without the need for any extra tools, although Visual Studio 2017 also allows you to develop and publish Azure Functions.

In our example, we are going to modify the function to receive a particular message and show it in the log. The code is simple.

using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
        dynamic data = await req.Content.ReadAsAsync<object>();

        string rtnStr = data?.lat + "," + data?.lon;
        log.Info("Response >> " + rtnStr);

    return data == null
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a location in the request body")
        : req.CreateResponse(HttpStatusCode.OK, "Your location is " + rtnStr);
}

When the function executes it expects two values in the invocation, lat and long. It shows these values in the execution log but a message could be created in a queue or an entry in a database.

Integrate

In addition to the online editor, each function has several options to configure its behavior. The first is Integrate, from where we can configure the HTTP methods it accepts and the authorization level. For this example, the only thing that changes is that the function only accepts HTTP POST.

Monitor

In the lower part of the editor we have access to log and if we want the result of previous executions, in the options of the function we can find the monitor. Each execution of the function is recorded in the monitor. With a click on one of the entries, we can access the details of the invocation.

One More Thing…

Now, we could execute the function from Azure or we can use a tool like Postman. To get the correct URL, in the editor, next to the Save and Run buttons, there is the "Get Function URL" option. This depends on the key you want to use, but the format is always similar, with three parameters that depend on our function.

https://<functionApp>.azurewebsites.net/api/<function>?code=<key>

But there are other ways to test. In this case, we are going to use the well-known IFTTT tool — "If This, Then That" — that allows us to create an Applet that invokes the function in case of an event.

We simply have to create a new Applet from a mobile device or from the web. In the first option, This, we choose the Button Widget. The only option is Button Press, with nothing more to configure. As a second option, That, we select WebHook. The only option we have is Make a Web Request, where we have to configure several attributes such as the URL, the HTTP method and the content type of our invocation.

Something that allows us to send data that IFTTT will capture at the time of running the Applet. In our case, the latitude and longitude of our position will go in the invocation HTTP body

After creating the Applet, we can run it or create a shortcut on our mobile device. When executing it, IFTTT will make the call to our Azure Function sending it our position.

Final Comments

The truth is that the example is very simple and only serves to see the basics, but the potential of Azure Functions in particular, and serverless in general is almost unlimited.

The idea of this article was to have a base to be able to use Azure Functions in other articles but as I as writing occurred to me if I had not thought before starting, like using IFTTT. This example uses the functionality of the button widget but there are other services such as notifications and location that are interesting for integrations, for example, the Internet of Things (IoT).

Topics:
cloud ,serverless ,paas ,azure functions ,azure ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}