Azure Functions Routing

With azure functions we can customise the end point that our Azure function will respond to.

By default the HTTP trigger will use the name of the function as the URL. So if we want to customise that we have to create a route.

Last time out we created a HTTP function that took a JSON payload and responded for more see here Azure Functions HTTP Triggers

Azure Functions HTTP Routes

Our Default url looks like this.

http://<yourapp>.azurewebsites.net/api/<funcname>?code=<functionkey>

For a default httptrigger function. The function name is the default route "HTTPTriggerCSharp1" and not very useful

https://serversncodefunctiondemo.azurewebsites.net/api/HttpTriggerCSharp1?code=VZ75yCKFgPmMyBrfMQzQxrSu/BJwwKQzK7/yK0vQfG4fcMumwjrAuA==

We send a sample payload

{
    "firstname": "Azure",
    "lastname": "Functions"
}

We call this Function using a POST method and content type set to application/json

We get a response back of "Hello Azure Functions"

Our current route of is not very useful really.

https://serversncodefunctiondemo.azurewebsites.net/api/HttpTriggerCSharp1 

So lets look at changing that.

In our function open the "function.json" file

{
  "disabled": false,
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    }
  ]
}

function.json is the file that holds all the configuration information about our function.

The bindings section of the JSON holds the information on the type of trigger used in this case it's a "HttpTrigger" you can see from the "direction: in" that this is the trigger for the function. If we have a Service bus trigger we have information on the service bus here liks this

  "bindings": [
    {
      "name": "myMessage",
      "type": "serviceBusTrigger",
      "direction": "in",
      "queueName": "serversncodedemo",
      "connection": "contentappmessage_RootManageSharedAccessKey_SERVICEBUS",
      "accessRights": "Manage"
    }
  ]

That's a sample of the binding section from our Service bus demo.

With a HTTP trigger we have a response section to the binding aswell.

    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    }

For routing we're interested in the trigger part of the binding.

We want to add a "Route" attribute to the binding that will hold our new name.

So under the "Direction": "in" attribute we add our new route attribute.

"route": "demo"

So that our function.json looks something like this

{
  "disabled": false,
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "route": "demo"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    }
  ]
}

Now when we run our test. If we use the orginal URL we get no response

https://serversncodefunctiondemo.azurewebsites.net/api/HttpTriggerCSharp1?code=VZ75yCKFgPmMyBrfMQzQxrSu/BJwwKQzK7/yK0vQfG4fcMumwjrAuA==

But if we replace the name of our function with our new custom route we will get the response we are expecting.

https://serversncodefunctiondemo.azurewebsites.net/api/demo?code=VZ75yCKFgPmMyBrfMQzQxrSu/BJwwKQzK7/yK0vQfG4fcMumwjrAuA==

Azure function Key

The part of our URL on the ?code=XXXXXXXXXXXXX

This is our function key.

HTTP Triggers by default have Function keys turned on this is for security. The key applies only to the specific functions under which they are set. When used as an API key, these only allow access to that function.

The key can be included in a query string variable named code, as above, or it can be included in an x-functions-key HTTP header. The value of the key can be any function key defined for the function, or any host key.

Manage Keys

You can manage the keys from the manage option on the function.

managekeys

Here you can add new keys, revoke or change them.

You can choose to allow requests without keys or specify that the master key must be used by changing the authLevel property in the function.json in the trigger binding section.

{
  "disabled": false,
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "route": "demo"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    }
  ]
}

AuthLevel

The AuthLevel property determines what keys, if any, need to be present on the request in order to invoke the function. See Working with keys below. The value can be one of the following:

  • anonymous: No API key is required.
  • function: A function-specific API key is required. This is the default value if none is provided.
  • admin : The master key is required.

To turn off the requirement for a key we change the AuthLevel to "anonymous" like this

{
  "disabled": false,
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "route": "demo"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    }
  ]
}

Now when we call the function we use the URL

https://serversncodefunctiondemo.azurewebsites.net/api/demo

We have a route api/demo setup and no key required our function will respond on this url and return "hello ...."

With azure functions we can customise the end point that our Azure function will respond to. By default the HTTP trigger will use the name of the function as the URL. So if we want to customise that we have to create a route. Last time out we created a…

Read More

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