March 4, 2017

Serverless Computing with Azure Functions Part-1

Introduction to Azure Functions

You might be wondering after reading the title what the heck! what’s going to happen to all those servers, where are we going now!!!? don’t be misled.

Serverless Computing” means that you don’t access, provision or care about server infrastructure to run code. In other words, you configure/run your code via an interface (like a web browser) and everything else that happens behind the scene is managed by Azure, simple! (but it still runs on some server in the end though).

But why run my functions in the cloud? can’t I just run it on my regular VM on the cloud?. Well, there are several reasons why you would want to run your code in Azure Functions, the most important ones are scalability and availability, Azure Functions would autoscale depending on the workload that your particular function is demanding without you having to worry about provisioning resources. also, you don’t have to worry about your server health as Azure will take care of this for you and keep things running with minimum to no downtime.

From WIKIPEDIA

Serverless computing, also known as function as a service (FaaS), is a cloud computing code execution model in which the cloud provider fully manages starting and stopping of a function’s container platform as a service (PaaS) as necessary to serve requests, and requests are billed by an abstract measure of the resources required to satisfy the request, rather than per virtual machine, per hour.

Creating a simple HTTP Triggered Function

So without further ado, let’s look at how we can create a function written in C# that converts Celsius to Fahrenheit as an Azure function. First things first you need to have an Azure account to run through the tutorial, so please create one if you haven’t done already.

Once you are logged on to the Azure portal, search the Marketplace for “Function App” and select it from the results and hit create.

You will be asked for the App name, etc. (See screenshot and fill in appropriately) note that the app name will eventually become the domain prefix for azurewebsites.net where your service endpoint will be located. for example, if you have typed in fahrenheit-to-celsius as the App name then your endpoint URL would look something like fahrenheit-to-celsius.azurewebsites.net…, After you click create you will have to wait a few minutes until Azure deploys the Function App in the cloud and notifies you the status at this point.

Now we have an Azure Function App configured for us to start coding. We need to skip the premade function selection screen that comes up initially (We don’t want that as we are creating a Web API style function that works over HTTP)

Click New Function from the left action pane and select the HttpTriggerCSharp as the template. Accept the defaults and then click create, after which you should be taken to the code editor, this is where you can save, run and test your Azure functions.

Notice that what you created earlier is your Function App which serves as a container for your Azure Functions and yes you can create multiple functions within the same app that can work together to solve a complex programming problem.

Now let’s change the example code provided by Azure and update it with the following code in the code editor, we will need to do a few more tweaks before we can successfully run this. I will not be explaining the below code snippet line by line as it is pretty much self-explanatory, In summary, what it does is to read a value from the HTTP request and parse/convert it to Fahrenheit then return the output as an HTTP response.

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 celsius = req.GetQueryNameValuePairs().FirstOrDefault(q => string.Compare(q.Key, "celsius", true) == 0).Value;
    
    // Get request body
    dynamic data = await req.Content.ReadAsAsync<object>();
    
    // Set name to query string or body data
    var fahrenheit = (decimal.Parse(celsius) * 9 / 5) + 32;
    
    return celsius == null ? 
    req.CreateResponse(HttpStatusCode.BadRequest, "Please pass in a Celsius value on the query string or in the request body") : 
    req.CreateResponse(HttpStatusCode.OK, $"{celsius} Celsius is {fahrenheit} Fahrenheit");
}

You can now run the code by hitting the run button, but before that, notice that you need to add the query string parameter celsius and a value for the same (e.g 32.5) for you to run a Test execution successfully. (see above screenshot)

Now copy the live URL for your function from the “Get function URL” link provided on the top right corner of the code editor. Copy this and run it on any web browser, make sure that you append the celsius query parameter with a value in the URL (e.g [function-url]&celsius=32.6) to see a valid output.

So there it is, a simple Azure function that converts Celsius to Fahrenheit. This example is intentionally oversimplified so that you can get started with Azure functions, but the possibilities of what you can do with it are pretty much endless if you think about it. you can write a complex application that consumes these functions and never worry about server infrastructure. (Keeping us developers focused on what we love to do best, code!)

Related posts: