Getting started with Azure Functions and using them within Logic Apps

|  Posted: December 20, 2016  |  Categories: Microsoft Azure

In this blog post, we will discuss an Azure Service called Azure Functions and how we can use them within a Logic App. Azure Functions has gone GA (General Available) on 15th of November 2016 and provides a capability of running small pieces of code in Azure.

You develop Functions in a browser i.e. in the Azure Portal (Function App), test it and done. Moreover, recently, support for creating Functions in Visual Studio has been added (see Eldert’s post Writing Azure Functions for Logic Apps using Visual Studio). With Functions, you don’t have to deal that much with infrastructure, that’s the responsibility of Azure or an application (see Azure Functions Overview).

When creating Functions, you need to consider aspects like scalability, security, pricing and complexity. In this post, we discuss this together with how Functions can be used in Logic Apps and how Functions fit in a solution architecture.

You can download the entire article as a PDF document.
Getting started with Azure Functions and using them within Logic Apps.

Use case scenario

Let’s assume you want to build a cloud integration solution to support a system that handles order messages with constraint to certain date format. Hence, you want to channel all orders through a series of Logic Apps to have each order with the same date format. The Logic App will consolidate each order message to a standard type of message i.e. orderdate. The Logic App will be triggered by an incoming message followed by an action that will call a Function to parse the date to the correct format. Subsequently, the message will be sent to a queue.

use-case-scenario

In more detail the Function will get a request based upon a trigger, the Function code is executed and an output is returned to the caller; see Azure Functions HTTP and webhook bindings.

Building the Function

To implement this use case, we will need to build a Function that will deal with the date format. The Function can either be developed through the Azure Portal or with Visual Studio. With Visual Studio, you will need to have the appropriate Azure SDK and tools installed:

In this post, we will use Visual Studio to build the Function. An Azure Functions project will be created and the Function can be added to it i.e. we will use the Generic WebHook – C#.

Once the Function is added we get a default implementation, which we can refactor to what we need.

#r "Newtonsoft.Json"
#r "System.Globalization"using System;

using System.Globalization;
using System.Net;
using Newtonsoft.Json;

public static async Task<object> 
Run(HttpRequestMessage req, TraceWriter log)
{
  log.Info($"DateTimeWebhook was triggered!");
  string jsonContent = await req.Content.ReadAsStringAsync();

  dynamic data = JsonConvert.DeserializeObject(jsonContent);

  try
  {
    string dateString = data.orderdate;
    DateTime convertedDate = DateTime.ParseExact(dateString, 
                                          "dd/MM/yyyy", null);
    string newDate = convertedDate.ToString("yyyyMMdd", 
                                         DateTimeFormatInfo.InvariantInfo);
    data.orderdate = newDate;
    jsonContent = JsonConvert.SerializeObject(data);
  }
  catch (Exception ex)
  {
    log.Info($"DateTimeWebhook error message: {ex.Message}");
    return req.CreateResponse(HttpStatusCode.BadRequest, 
    new { error = "Illegal request"});
  }

  var response = req.CreateResponse(HttpStatusCode.OK);
  response.Content = new StringContent(jsonContent, 
                       System.Text.Encoding.UTF8, "application/json");

  return response;
}

The above is a simple representation of code that handles a date (dd/MM/yyyy) from the order, parses it and creates a new date using the desired format i.e. to year month date format (yyyyMMdd).

Testing the functions

With Visual Studio, you have to ability to debug your Function and test it if behaves as we expected. We can step through our code by setting a break point in at the beginning i.e. log info statement for instance. To support debugging, the Azure Function CLI tools are required which you be will notified for once you’ll try to debug a Function in Visual Studio the first time.

Since we use a HTTP WebHook to trigger the Function, we will use Postman to post an order message. By running an instance of the Function (Right clicking the Function, Debug to Start a new instance), a console will appear including the endpoint of the Webhook.

azure functions testing

In Postman, we can now post the order message to the endpoint (see picture above) and debug our Function. The result of the Function after invoking will appear in Postman and in the console you can see some execution details.

postman-view-of-azure functions

Deploying the Functions

Once we are happy with the result of the test, we have to deploy the function to our Azure subscription. The hosting environment (container) for Functions is the App Service. Therefore, right click the project and choose publish to start with the deployment. A dialog will appear and from this point on, you can either deploy to resource group that has a Service App available or you can create a new one. Once you have specified the App you can proceed to deploy it. Depending on what resource group you deploy it to, you can navigate to it in the portal and find the Function.

Building the Logic App

To call the Function from a Logic App in our scenario, we need to create one. Logic Apps can be created and implemented through the portal or Visual Studio. To be able to create them from Visual Studio you will need:

  • Azure 2.9.1 or greater
  • Visual Studio 2015
  • Azure PowerShell

You can also refer Microsoft docs Build and Deploy Logic Apps in Visual Studio.

To support our scenario, we will build the Logic App like visualized below.

azure functions logic-app

In the Logic App designer, you can add a trigger. You can choose from various triggers like HTTP, recurrence, WebHook, etc (see Workflow Actions and Triggers). In our scenario, it’s the HTTP trigger, which we provide with a schema of the payload it can accept/expect. The schema can be generated using JsonSchema.net, a tool that automatically generates JSON schema from JSON according to the IETF JSON Schema Internet Draft Version 4. The JSON Schema will be automatically generated in three formats: editable, code view, and string. The generated schema can be pasted into the Request Body JSON Schema part of the HTTP Trigger. Note that the URL is generated after the Logic App has been saved for the first time.

Subsequently, under the trigger an action is added that selects an Azure Function available in our region, which is DateTimeWebHook that is available in the Function App. In this action, we specify what input we will provide to our function, which is of course the body of the received message. In the action, we placed below the Function Action, we specify it’s a Service Bus Action. This action will require a connection string to the Service Bus namespace we want to use, hence we specify it, in combination with what queue has to be used to send the message i.e. body (output) from the function.

You can download the entire article as a PDF document.
Getting started with Azure Functions and using them within Logic Apps.

Testing the solution

To test the solution, you can also use Postman to send a payload to the Logic App HTTP endpoint.

azure functions-testing-the-solution

With ServiceBus360, we can subsequently verify if the message lands into the inboundqueue queue.

azure functions-servicebus360-screen

And in the Azure Portal, you examine the run of the Logic App by going to Runs. We can click on the run that was initiated by Postman and look into each step of the Logic App.

azure functions-logic-app-run-view

Considerations

The Azure Function can be another solution building block in your toolbox. From a solution architecture perspective, you have a few similar building blocks available such as WebJob, Flow, and Logic Apps. All capable of solving integration problems and/or automate business processes. Fortunately there is guidance on what to choose: Choose between Flow, Logic Apps, Functions, and WebJobs. And in this blog, we have seen that Logic App can call a Function.

Pricing is another aspect of any Azure Service you use. With Functions, you can either opt for a consumption plan or regular pricing through an App Service Plan, see Function Pricing. You can use the calculator to have a better indication of price.

Depending on your requirements i.e. predominantly at what scale you want to run your Functions, see Scaling Azure Functions.

As it is a server less coding experience you can use a browser to build Azure Functions. However, as we have seen in this post, you also have the possibility of building Functions using Visual Studio 2015. Note that this is still in preview.

Another aspect with developing functions is complexity. The Function implementation is limited by code, i.e. you can implement a substantial amount of code to do various complex tasks. Therefore, you should maintain some best practices when it comes to creating Functions. These practices are:

  • Functions should do just one thing
  • Functions should finish as quickly as possible
  • Functions should be stateless
  • Functions should be idempotent

Moreover, you might want to create a strategy around the amount of Functions you think are useful can be put in a Function App for reuse towards Logic Apps. We saw a simple example of a Function that adheres to previous mentioned best practices which changes a date in a different format.

Other than re-usability, you need to consider some ALM type of aspects like versioning, operations and deployment. Functions can be created in a browser and/or in Visual Studio. And deployment can be regulated through Visual Studio and is fit for continues deployment.

Functions are secured by means of a code parameter that has to be supplied when calling the Function endpoint. Since we created a WebHook trigger in this post to directly call the Function endpoint we need to supply this code.

https://logicappfunctionsorders.azurewebsites.net/api/DateTimeWebHook?code=pu16vmDDdWalCaP8bm/N7w5/KZPzbjBqdtwnhwNmBTNIaNgCNnl2Cg==

These codes i.e. keys are managed through the Function App Manage tab. Here you can also enable/disable the Function, and manage the Function keys (see also Working with Keys). To further secure the solution itself the Logic App Http Endpoint needs to be secured for which you have several options:

  • API Management
  • Access Control (Restrict calls to triggers in this logic app to the provided IP ranges)
  • SAS Keys of the Logic App (access key can be regenerated to invalidate the Logic App’s SAS URLs).

In case you run into issues with Functions, you have several options:

Conclusion

Azure Functions can further extend the capabilities Logic Apps offer. Messages can be enriched or modified as we have seen in this blog post. The small pieces of custom logic in Functions can bring your Logic to the next level that can enable reuse through all Logic Apps or other Azure deployed solutions.

You can download the entire article as a PDF document.
Getting started with Azure Functions and using them within Logic Apps.
Author: Steef-Jan Wiggers

Steef-Jan Wiggers has over 15 years’ experience as a technical lead developer, application architect and consultant, specializing in custom applications, enterprise application integration (BizTalk), Web services and Windows Azure. Steef-Jan is very active in the BizTalk community as a blogger, Wiki author/editor, forum moderator, writer and public speaker in the Netherlands and Europe. For these efforts, Microsoft has recognized him a Microsoft MVP for the past 5 years.

One Platform Operations, Monitoring and Analytics Software
BizTalk360

microsoft biztalk

Learn more

Over 500 customers across 30+ countries depend on BizTalk360

ServiceBus360

Azure service bus

Learn more

Start managing your Azure Service Bus namespaces in minutes

One Platform - Operations, Monitoring and Analytics Software
BizTalk360

microsoft biztalk

Learn more

Over 500 customers across 30+ countries depend on BizTalk360

One Platform - Operations, Monitoring and Analytics Software
ServiceBus360

Azure service bus

Learn more

Start managing your Azure Service Bus namespaces in minutes

Back to Top