Blog Safely consume an Azure Function through Microsoft Flow RSS Feed

Safely consume an Azure Function through Microsoft Flow

Aug 12, 2019

Azure Functions

Azure Functions is a server less, event-driven compute service that allows you to easily run code or script written in language of your choice in response to various events while scaling on demand and paying only for the duration your code runs. Using Azure Functions, you are not required to worry about provisioning whole application or managing infrastructure. It makes developers more productive by allowing them to use their preferred language such as Node.js, Java, C#, F# or PHP. Azure Functions extend the capabilities of Azure Web Jobs and are actually built on top of Azure WebJobs with some enhancements in the underlying infrastructure.

Features of Azure Functions

Below are some of the key features of Azure Functions:

Feature Description
Language Choice Program functions using your preferred choice of language, JavaScript, C# or F#
Pay-per-use pricing plan Pay only for the duration till your code executes
Use your own dependencies/assemblies Consume your preferred libraries as Functions support NuGet and NPM
Integrated security Secure HTTP-triggered functions using OAuth providers such as Microsoft, Google, Facebook, Google and Azure Active Directory account
Simplified Integration Utilize Azure services and software-as-a-service (SaaS) utilities
Adaptable development Easily setup integrations and code deployments through Azure DevOps services and GitHub
Open-source Functions runtime is open-source and can be accessed through GitHub

Microsoft Flow is the top choice to do any mechanized task in Office 365. It is an online workflow service that automates tasks over the most generally perceived apps and services. It is routinely used to automate work processes between your favored applications and services, synchronize records, get notifications, assemble data, and altogether more for a better SharePoint development.  When you sign up, you can interface with more than 220 services and can organize data either in the on-premises or in cloud sources like SharePoint, Microsoft SQL Server and many more as the list of applications you can use with the Microsoft Flow grows continuously.

Microsoft Flow

For example, you can automate beneath type of tasks: 

  • Instantly respond to high-need warnings or messages. 
  • Capture, track, and catch up with new sales clients. 
  • Copy all email attachments to your OneDrive Business account. 
  • Collect data about your business and share that data information to your team. 
  • Automate an approval workflow.

Refer our beneath online journals related to MS Flow:

Microsoft Flow with Artificial Intelligence

Let’s start with calling an Azure Function through MS Flow. But before that, one must have an active Azure and Office 365 subscriptions.

Call Azure function through Microsoft Flow

You can utilize Azure Functions to leverage the use of Microsoft Flow, which makes it easy for you to automate business processes between Azure services and apps. We will create an Azure function which will calculate the cost of the wind turbine repair based on the provided number of hours and turbine capacity, and the revenue generated through turbine in 24-hour period. The function also results in whether it is feasible to undergo wind turbine maintenance or repair criteria or not. After this function, we will configure a flow, based on wind turbines maintenance or repair criteria. If the turbine repair is feasible and non-expensive, then the flow will trigger an email to the respective email address that a repair is recommended.

Use Azure API Management to create an OpenAPI definition to leverage Azure function

Let’s create a function that checks whether an emergency repair on a wind turbine is feasible and non-expensive.

Add a function app

A function app enables you to host a collection of functions as logical units for scaling, deployment, easy resource sharing, and deployment.

  • Navigate to the Azure portal. Click Create a resource link on the top-left corner of the portal page, choose Compute > Function App.

Create a resource

  • Pass Function App settings as mentioned below and click on Create to provision and create a new Function App.

Function App

Setting Suggested value Description
App name Globally unique name: turbineCostMgmt Logical name to identify your function app. Characters valid: a-z, 0-9 and –
Subscription Your subscription Azure subscription under which resource is created
Resource Group Name for your resource group: turbineCostMgmtResourceGroup Resource group name under which your function app resides
OS Windows Linux hosting is in preview currently
Hosting Plan Consumption plan Determines plan to allocate resources to your function app
Location Region of Azure resources: West Europe Select a region near you or your Azure resources
Runtime stack Choice of your language: .NET Core A runtime supporting your preferred programming language e.g .NET for C#
Storage Use default created globally unique name Storage account for your function app
Application Insights Default Adds Application Insights resource, same as your app name
  • After creating Function App, access Notification icon in the top-right corner of the portal and verify Deployment succeeded message.

Notification icon

  • Click Go to resource button shown in the above image to navigate to your newly created Function App. You can also choose Pin to dashboard to quickly access the Function App from your Azure portal dashboard.

Add a function

We will use HTTP triggered function having two parameters:

  • Time (in hours) estimation for turbine repair or maintenance.
  • Capacity (in kilowatts) of the turbine.

The function will calculate the turbine repair cost, and the revenue made through the turbine in a 24-hour period.

Follow the below steps to create HTTP triggered function using the Azure portal:

  • In your function app, click + icon next to Functions. Select In-portal and then Continue at the bottom.

Azure Functions for .net

  • Choose More Templates… and then Finish and view templates.

More Templates

  • .Choose HTTP Trigger.

HTTP Trigger

  • Provide function Name as “TurbineRepair” and select Authorization level as “Function”. Click the Create.

New Function

  • Replace the default code inside run.csx script with the below code.
#r "Newtonsoft.Json"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
const double revenuePerkW = 0.12;
const double technicianCost = 250;
const double turbineCost = 100;
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
    // Get query strings if they exist
    int tempVal;
    int? hours = Int32.TryParse(req.Query["hours"], out tempVal) ? tempVal : (int?)null;
    int? capacity = Int32.TryParse(req.Query["capacity"], out tempVal) ? tempVal : (int?)null;
    // Get request body
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    // Use request body if a query was not sent
    capacity = capacity ?? data?.capacity;
    hours = hours ?? data?.hours;
     // Return bad request if capacity or hours are not passed in
    if (capacity == null || hours == null){
        return new BadRequestObjectResult("Please pass capacity and hours on the query string or in the request body");
    // Formulas to calculate revenue and cost
    double? revenueOpportunity = capacity * revenuePerkW * 24;  
    double? costToFix = (hours * technicianCost) +  turbineCost;
    string repairTurbine;
    if (revenueOpportunity > costToFix){
        repairTurbine = "Yes";
    else {
        repairTurbine = "No";
    return (ActionResult)new OkObjectResult(new{
        message = repairTurbine,
        revenueOpportunity = "$"+ revenueOpportunity,
        costToFix = "$"+ costToFix

The above code returns Yes or No to determine whether an emergency turbine repair or maintenance is cost-effective, the revenue opportunity generated by the turbine in one day, and the expense or cost to repair the turbine.

  • Click the Save button.


  • Expend test tab at the far right of the function app and select Test to verify the function. Pass below value inside the Request body, and then select Run.
run.csx -> Test -> Request body
    "hours": "6",
    "capacity": "2500"

Request body

  • You can see below the value returned inside response body Output.
Output JSON

Finally, you have a function that indicates the feasibility and cost-effectiveness of emergency turbine maintenance and repairs. Now, you’re ready to create an OpenAPI definition for above the Function App. 

Generate OpenAPI definition

  • In your function app, under Platform features, select API Management.

API Management

  • Click Create new link on API Management page.

Create new link

  • Pass API Management service settings as mentioned in the below table. Click Create to generate the API Management instance.

API Management service

Setting Suggested value Description
Name Globally unique name: turbineCostMgmt-apim Auto generated name depending on your function app.
Subscription Azure subscription Azure subscription under which new resource is generated
Resource Group Name of your resource group: turbineCostMgmtResourceGroup Resource group specified while creating your function
Location Region of Azure resources: West Europe Select a region near you or your Azure resources
Organization name Your organization name: TatvaSoft Name used in Azure portal and for email notifications
Administrator email Your email address Email ID that receives API Management notifications
Pricing tier Your pricing plan Azure pricing plan

The API Management instance provisioning may take a few minutes. After provisioning is completed, a message as shown below will be displayed.

API Management instance

  • Select Enable Application Insights to view logs inside the function application, accept the defaults and then click Link API.

Enable Application Insights

  • Click Select on Import Azure Functions dialog, where TurbineRepair function is highlighted.

Import Azure Functions

  • Accept the defaults on the Create from Function App page and click Create to register API for the function.

Create from Function App


Test the API

You need to check whether the API works before you utilize OpenAPI definition.

  • Click POST operation on the Test tab of “turbineCostMgmt” function.

POST operation

  • Provide values for hours and capacity in JSON format. Click Send.
JSON Request body
    "hours": "6",
    "capacity": "2500"

Provide values for hours

  • Observe the HTTP response.

HTTP response

Download OpenAPI definition

You can download your OpenAPI definition turbinecostmgmt.json file if your API works properly

  • Click Download OpenAPI definition at the top of API Management page.

Download OpenAPI definition

  • Observe OpenAPI definition in the downloaded JSON file.
  "swagger": "2.0",
  "info": {
    "title": "turbineCostMgmt",
    "version": "1.0",
    "description": "Import from \"turbineCostMgmt\" Function App"
  "host": "",
  "basePath": "/turbineCostMgmt",
  "schemes": [
  "securityDefinitions": {
    "apiKeyHeader": {
      "type": "apiKey",
      "name": "Ocp-Apim-Subscription-Key",
      "in": "header"
    "apiKeyQuery": {
      "type": "apiKey",
      "name": "subscription-key",
      "in": "query"
  "security": [
      "apiKeyHeader": []
      "apiKeyQuery": []
  "paths": {
    "/TurbineRepair": {
      "get": {
        "operationId": "get-turbinerepair",
        "summary": "TurbineRepair",
        "responses": {}
      "post": {
        "operationId": "post-turbinerepair",
        "summary": "TurbineRepair",
        "responses": {}
  "tags": []


  • Microsoft Flow account having same authentication credentials as Azure account.
  • Consumption Plan, as it requires limited utilization of resources and only pay for the time the function is executed.

Note: The selection of Consumption Plan or App Service Plan depends on your needs.

  • SharePoint, to be used as a data source.

Provision a SharePoint list

Create a SharePoint list Turbines that you will use as a data source for the flow.

Create a SharePoint list

The list will have the below columns:

List Column Data Type Description
Title Single line of text Name of the turbine
LastServiceDate Date
MaxOutput Number Output of the turbine, in KwH
ServiceRequired Yes/No
EstimatedEffort Number Estimated time for the repair, in hours


When you’re done with the creation of list columns, the default list view should look like the one below:


Get Azure function URL

You will require Azure Function URL in the flow later.

  • Under TurbineRepair function, click </> Get function URL link.

Get function URL

  • Copy function URL which is displayed by clicking Copy link.

Copy function URL

Configure a flow to call Azure function

Once you’ve got the Azure Function URL and a SharePoint list, you can configure a flow.

  • Browse to, select My flows and click New > Instant-from blank

My Flows

  • Add When an item is created SharePoint trigger. Select Site Address as your SharePoint site name and required List Name as “Turbines” that contains the turbine data.

Sharepoint Trigger

  • Specify a condition to execute the next set of actions. Insert a new step and add a new Condition control, which will add two branches: If yes and If no.

Choose an action

If yes and If no

  • You can specify a condition to match a criterion and add steps/actions to one or both the branches based on the condition. Select the first box on the Condition card and choose ServiceRequired under Dynamic Content dialog returned through When an item is created trigger.


  • Add true for the condition i.e triggerBody()?[‘ServiceRequired’] is equal to true.

Add true for the condition

SharePoint list displays the value as Yes or No, but it is stored in Boolean form, either True or False. The above condition checks if ServiceRequired field value is set to Yes in the Turbines list. If it is, the flow executes If yes branch else the If no branch.

  • Click Add an action in the If yes branch and add a step (action) – HTTP-HTTP. Rename the action to Calculate costs.

Click Add an action

  • Change Method to "POST" and add Function URL copied earlier as URI to call the Turbine Repair Azure function. Add Body as shown below. You can also select a Dynamic Content dialog box to pass the Estimated Effort (for hours) and MaxOutput (for capacity) list item values.
Action: Calculate costs -> Body
      "hours": "triggerBody()?['EstimatedEffort']",
      "capacity": "triggerBody()?['MaxOutput']"

Calculate cost

  • Provide flow name as Turbine Repair Approval and Save the flow.

Flow name

  • At this point of time, check the Flow run by adding a new item or row in the Turbines list.

Adding a new item

  • Navigate to Turbine Repair Approval flow and click on the Flow start date. You can observe that the flow is succeeded.


  • You can observe the output Body that the flow action returns: message > “Yes”, as well as revenueOpportunity (potential revenue) > “$7200” and costToFix (cost of repair) > “$2600” values from TurbineRepair Azure function it calls.

Observe the output Body

  • Add a Compose action at the bottom of If yes branch to the store value of Message returned from Calculate costs action.
Compose -> Inputs 

Compose action

  • Add another condition at the bottom of If yes branch below Compose operation.

Compose operation

  • Select the first box in Condition 2 card and add Output of Compose operation under Dynamic content tab.

Dynamic content

  • Add Yes for the condition i.e outputs(‘Compose’) is equal to Yes. The flow executes next If yes or If no branch based on if Message value returned by Azure function is yes (repair required) or no (repair not recommended).


  • Add two Compose operations, one each to store repair cost and potential revenue returned by Calculate Costs action. We will be using these values later while sending an email.
Compose 2 -> Inputs
Compose 3 -> Inputs

Two Compose operations

  • Add an action Office 365 Outlook – Send an email at the bottom of If yes branch of the second condition to notify respective person regarding turbine repair as well as costs and potential revenue.

Note: You can carry out number of operations based on your requirement such as updating a SharePoint list or starting an approval process.    

Search for Office 365 Outlook and select the required action based on your email system.

Search for Office 365 Outlook

  • Pass a valid email address of the user in your organization in To field, add email Subject and compose email inside Body. Fetch the value of Title token for SharePoint list under Dynamic content tab and CostToFix and RevenueOpportunity from the above Compose 2 and Compose 3 operations respectively.
Send an email -> Subject
Recommended repair for triggerBody()?['Title']
Send an email -> Body
Based on our calculations, the cost to fix triggerBody()?['Title'] is outputs('Compose_2') and the revenue opportunity is outputs('Compose_3'). Please arrange for the repair to be made.

Send an email

  • Save the flow. The completed flow should look like the one below:

Save the flow


  • Once flow configuration is completed, add a new item or row inside the Turbines list.

Add New Item

  • Adding a new item triggers the Turbine Repair Approval flow. On the flow page, check the Flow run.

Check the Flow run

  • If your flow ran successfully, you can observe flow operations by expanding various actions.

Observe flow operations

  • Verify the email account (Outlook) inbox for the person you passed in the To field of Send email action. The received email should look like the one below.

Verify the email account

You can observe that the tokens have been replaced with the actual values from the SharePoint list and the TurbineRepair Azure function.


Give a hit to this approach of consuming an Azure Function in MS Flow. Here, in MS Flow, one can collate data from various services like Dynamics 365, Salesforce, OneDrive, Dropbox, etc. and manage data in them. MS Flow can consume the data returned from an Azure function into any service or vice-versa. Being a superset of Azure WebJob, Azure Function is also very cost effective from business perspectives.

Cite on our blog identified with the call of an Azure WebJob through the MS Flow.


Leave a Reply

Your email address will not be published. Required fields are marked *

About Tatvasoft

TatvaSoft is a CMMi Level 3 and Microsoft Gold Certified Software Development Company offering custom software development services on diverse technology platforms, like Microsoft, SharePoint, Biztalk, Java, PHP, Open Source, BI, Big Data and Mobile.

Follow Us