Azure Functions HTTP Triggers

Azure Functions HTTP triggers give us the ability to extend our applications in many ways. We can use them as webhooks and just make a call or we we can get responses. With Azure Functions added flexibility we can extend our applications in a number of directions.

In this post we will cover creating a HTTP trigger function and Serialize the request body into an object.

Azure Functions - HTTP Trigger

From the Templates select "HTTP Trigger - C#"

Azure Function HTTP Trigger

Right away we have a working HTTP function. If you hit Run it will test and return Hello Azure. Change the value in the test and we can see it working.

But we want to do more than just send in "name" we have a website that someone signs up on. We want to call a webhook and pass the information of the new signup to it. We will also use Newtonsoft Json to serialize our request body into an object.

First up lets add a Nuget package. Create a new file called "project.json"

Azure Functions add project.json


{
 "frameworks": 
 {  
  "net46":
  { 
   "dependencies":
   {
     "Newtonsoft.Json": "10.0.3"
   }
  }
}
}

And add the above code and click save, for more on Nuget packages and functions check out my earlier post Azure Functions nuget and dot net framework

When we click save on the project.json we will see the Nuget packages restored to our function. Go back to our run.csx


using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    // parse query parameter
    string name = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
        .Value;

    // Get request body
    dynamic data = await req.Content.ReadAsAsync<object>();

    // Set name to query string or body data
    name = name ?? data?.name;

    return name == null
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
        : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
}


We're going to rewrite our function to this


using System.Net;
using Newtonsoft.Json;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    string name = "";

    
    dynamic requestBody = await req.Content.ReadAsStringAsync();
    var _person = JsonConvert.DeserializeObject<Person>(requestBody as string);

    name = _person.firstname + " " + _person.lastname;

    return name == " "
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
        : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
}

public class Person{
    public string firstname {get;set;}
    public string lastname {get;set;}
}

We'll break down this code now.

using Newtonsoft.Json

will bring in our nuget package.

We add a class to our function for our person.


public class Person{
    public string firstname {get;set;}
    public string lastname {get;set;}
}

Then we replace the code in the template function


    // parse query parameter
    string name = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
        .Value;

    // Get request body
    dynamic data = await req.Content.ReadAsAsync<object>();

    // Set name to query string or body data
    name = name ?? data?.name;


We replace that code with the following



    string name = "";

    
    dynamic body = await req.Content.ReadAsStringAsync();
    var e = JsonConvert.DeserializeObject<Person>(body as string);

    name = e.firstname + " " + e.lastname;


What we do here is take the req.Content and using JsonConvert we deserialize it into an object e

We then create our name from the e.firstname + " " + e.lastname

I also change the if statement instead of if name = null I ask if name = " " the space is important because we add a space between firstname and last name so no name will mean it's a space.

Now we can test it. Get the Function URL from the portal

Azure Function URL

Open post man API Testing with Postman

Create a new test and paste the url into the address,

  • Change the method to POST
  • Under body set "application/json" as the contenttype.
    Select raw and create your request object

{
    "firstname": "James",
    "lastname": "Serversncode"
}

Azure Function Test

Then run the test.

We should get back "Hello " - what we enter for firstname / lastname.

There is a HTTP Trigger that can process a request body, turn it into an object and let you loose on it. With the ability to add nuget packages we can bring functions into our application workflows in alot of ways.

Azure Functions HTTP triggers give us the ability to extend our applications in many ways. We can use them as webhooks and just make a call or we we can get responses. With Azure Functions added flexibility we can extend our applications in a number of directions. In this post…

Read More

Azure Functions - Service Bus Queue Trigger

Azure functions allow have a service bus queue trigger, which will execute the code in the function each time a message is added to the service bus.

Create Service Bus trigger

In Azure functions create a new function, From the template options select "ServiceBusQueueTrigger - C#"

Azure Functions Service Bus Queue Trigger

Select the ServiceBus Connection you want to use, you can also select the access key you want to use. In the above I've selected my contentappMessage bus and my root key.

Select the Queue name and then create

This will create an Azure function that will run when ever a message is added to the service bus Queue you have selected.

For more on Azure Service bus check out my blog post Getting Started with Azure Service Bus

public static void Run(string myQueueItem, TraceWriter log)
{
    log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
}

Each time you add a message to the service bus queue this function will execute and log the item.

But there is an issue with the trigger. string myQueueItem isn't really useful not if you have used a brokered message and added other information you want to use in the function.

So lets change it.

First lets add the nuget package for Azure Service Bus into our function. (see here for more)

In View Files add "project.json"

Azure Functions Add Project.json

In project.json add the following code


{
  "frameworks": 
    {  
      "net46":
      { 
        "dependencies":
        {
          "WindowsAzure.ServiceBus": "4.1.2"
        }
      }
    }
}

And save, watching the logs panel you will see it restoring the nuget package

Azure Functions logs

Back into our Run.csx and we want to make some changes


using System;
using System.Threading.Tasks;
using Microsoft.ServiceBus.Messaging;

public static void Run(BrokeredMessage myMessage, TraceWriter log)
{
    log.Info($"C# ServiceBus queue trigger function processed message");

    string sMessage = myMessage.Properties["Message"].ToString();
    string sID = myMessage.Properties["ID"].ToString();


    log.Info($"message - " + sMessage + " Id " + sID);
}
 

We add the

Using Microsoft.ServiceBus.Messaging

We then change

string myQueueItem

to be

BrokeredMessage myMessage

Then Replace the log lines as this will fail. But also we add in two strings reading from our message in the service bus queue.

Lastly we need to change the binding in the function. Open Function.json in the View Files.


{
  "bindings": [
    {
      "name": "myQueueItem",
      "type": "serviceBusTrigger",
      "direction": "in",
      "queueName": "serversncodedemo",
      "connection": "contentappmessage_XXXXXXXXXXXXXXXXX",
      "accessRights": "Manage"
    }
  ],
  "disabled": false
}

This is the binding that will trigger the function to execute.

Change the "Name": "myQueueItem" to


"name": "myMessage"

Now save and in the logs it should now read Compilation succeeded.

Azure functions allow have a service bus queue trigger, which will execute the code in the function each time a message is added to the service bus. Create Service Bus trigger In Azure functions create a new function, From the template options select "ServiceBusQueueTrigger - C#" Select the…

Read More

Azure Functions Nuget Packages and the dot Net Framework

Using Nuget and the .NET Framework in our Azure Functions is easy and straight forward. We can give our Azure functions alot of power and functionality.

Using the .NET Framework

For framework assemblies, add references by using the #r "AssemblyName" directive.

For example if we want to use System.Data.SqlClient we would need to add a #r directive to the top of our code like this


#r "System.Data"

using System.Data.SqlClient;

This will allow us to use the SQLClient libarary of the .net framework.

Adding Nuget

If you are wondering where to get started check out our Azure Functions Getting Started

In our Function we need to add a "project.json" file. Go to View Files and add a new file and name it project.json

Azure Function Add Project json

In our Project.json we want to add the following


{
  "frameworks": 
    {  
      "net46":
      { 
        "dependencies":
        {
          "Newtonsoft.Json": "10.0.3"
        }
      }
    }
}


This will load the nuget package of Newtonsoft Json into our function.

Then in our code we just reference


using Newtonsoft.Json;

And now we can use our Nuget package in our Azure Function.

Using Nuget and the .NET Framework in our Azure Functions is easy and straight forward. We can give our Azure functions alot of power and functionality. Using the .NET Framework For framework assemblies, add references by using the #r "AssemblyName" directive. For example if we want to use…

Read More

Azure Functions Triggers

Azure Functions come with a number of triggers, from HTTP, Timers, service bus, blob and many more. In this post we go over the different types of triggers available out of the box for Azure Functions.

Last week I covered the creating of functions and getting up and running, Azure Functions Getting Started

Azure Function Triggers

Azure functions have a number of quick start templates for different triggers in C#, F# and Javascript. These are out of the box and have some default code.

Azure Function Triggers

  • HTTP Trigger

When a HTTP request is made to the function, the functions code will be executed. It provides a REST API endpoint that can be called with a HTTP post request.

  • Timer Trigger

This is a trigger that is based on a schedule. You can define the schedule and it will execute the code in the function.

To create a schedule you use the CRON Expression

A timer trigger is made up of

{second} {minute} {hour} {day} {month} {day-of-week}

Examples

Once every 5 minutes

0 */5 * * * *

Trigger once every two hours

0 0 */2 * * *

Trigger once every hour from 9 AM to 5 PM

0 0 9-17 * * *

Trigger At 9:30 AM every weekday

0 30 9 * * 1-5

  • Queue Trigger

This is a trigger that will execute the code whenever a message is added to a selected Azure Queue Storage

  • Blob Trigger

When an item is added to a specified Blob Storage container the code will be executed.

  • EventHub Trigger

When an event is added to the selected event hub the code in the function will execute.

  • Servicebus Queue Trigger

When a message is added to a selected Service Bus queue, this function will be executed.

  • Servicebus Topic Trigger

When a message is added to a specified Service Bus topic, then this function will be triggered.

With these triggers we have alot of flexibility to create a very flexible application.

Azure Functions come with a number of triggers, from HTTP, Timers, service bus, blob and many more. In this post we go over the different types of triggers available out of the box for Azure Functions. Last week I covered the creating of functions and getting up and running, Azure…

Read More

Azure Functions Getting Started

Function as a Service or FAAS we do love our abbreviations. FAAS is a set of functions that are short lived and single responsibility and have the ability to scale well. The big part of Functions as a service is they are part of serverless, this doesn't mean there isn't a server it just means the server is not your problem.

Some of the properties of Function as a service are

  • Short lived functions - AWS Lambda has a timeout of 1 second.
  • Single Responsibility - A Function should only do 1 thing.
  • Event Driven - A function can respond to a HTTP Trigger like a Webhook, a schedule and timer or a Service bus message.
  • Scale easily with traffic spikes

This is the first post in a series on FAAS in general but starting with Azure Functions.

Azure Functions

Azure functions are Microsofts FAAS offering and what we will start to explore.

With Azure Functions you can write functions in C#, F#, Node.js, Python, PHP, Batch, Bash and an executable. Functions have full support for Nuget and NPM. Easily integrate to other Azure services.

Pricing

Azure functions have two price plans, app service plan so it would be tied to your existing plans or consumption and you only pay for what you use.

With Functions you pay per second X number of executions.

Getting Started

Lets get creating some azure functions. Open the Azure Portal

Click on New and in the market place type in Function App (it's filed under Compute in the marketplace if you just want to click it)

Getting Started with Azure Function App

Once you select this we can create our first function app. This isn't the functions it's a host for our functions. Think of it like setting up an Azure App Service.

Create Azure Function App

Now we create our function app. We give it a name, select the Resource Group and Subscription as we do with most things in Azure.

Hosting Plan we have two choices,

  • Consumption Plan
  • App Service Plan

With an App service plan our function is tied to the currently running app services.

Consumption plan is just what it sounds like you pay for what you use. Per Second per request. I won't go into the details here if you go to the Azure Pricing Calculator you can find out more.

All Azure functions need a storage account and they can be integrated to Application Insights.

Hit create and deploy our new Azure Function.

Next we need to add the menu item to the side bar on our portal. It's not there by default.

Click "More Services" on the bottom of the side bar

Azure More Services

Search for "Azure Functions" and click the Star to add it onto the side bar and then you can move it where you want.

Azure Function Apps sidebar option

Once our Function app has deployed we can start creating functions.

Azure Function App Ready

Let's create a quick function and see it all in action.

Along side functions Hit the plus to create a function

Azure Function New

For your first Function you will see the Azure Function quick start panel.

Azure Function Quick Start

We'll create a web hook Function, this is a HTTP Trigger function, I'll cover the triggers in another post.

Create this function.

Azure Function Code

Ok we now have a function, our screen in the portal is in 3 sections

  • We our editor which by default is loading the code for our function.
  • Below this we have our logging output.
  • Next to this on the left we have "Files" and "Test"

The file "run.csx" is our code. Azure functions are scripts. In this case I have a csharp script.

Select "Test" on the left side to open the test panel.

Test Azure Function

This makes a POST request and sends a request body with "Name": "Azure" this is the default test.

Below that you can select Run and the output will show "Hello Azure"

You can also test it from an API testing tool like postman (for more on postman and api testing check out my post API Testing with Postman)

Click on "</> Get Function URL"

Azure Function Get URL

Copy this url and open Postman or any API testing tool

Azure Function Test

Set the web method to POST and enter the URL from the function.

Select Body and go to RAW, set the application content type to "JSON(Application/json)"

And then enter the RAW body of

{
"name": "James"
}

Click send and then we will get a response of "Hello James"

That's it you have created your first function.

This is the first post in a series on FAAS, focusing at first on Azure Functions.

Over the course of these posts we will cover

  • Different triggers.
  • Passing more information.
  • Nuget Packages.
  • Working with Visual Studio.
  • Connecting to other services including SQL and Azure tables.

Function as a Service or FAAS we do love our abbreviations. FAAS is a set of functions that are short lived and single responsibility and have the ability to scale well. The big part of Functions as a service is they are part of serverless, this doesn't mean there isn't…

Read More