Click here to Skip to main content
14,084,501 members
Click here to Skip to main content
Add your own
alternative version

Stats

7.6K views
11 bookmarked
Posted 28 Apr 2019
Licenced CPOL

Play and Test Your First Serverless Azure Function

, 1 May 2019
Rate this:
Please Sign up or sign in to vote.
How to create and test a Serverless Function app using Microsoft Azure

Contents

Scenario

Here is a scenario; you oversee an Oven Temperature Data Logger for a Pizzeria company. You monitor this data to help determine when oven maintenance is required.

Your company receives sensor data from several pizzeria factories and from different oven models. You are tasked to develop a reusable service that can process your temperature data from all these factories.

You decided the best and most cost-effective way to handle this task is to use serverless computing. For this project, you are going to use Azure Functions. With this in mind, we are going to play with Azure Functions to learn how it works immediately.

What Is Serverless Computing

With serverless computing, your cloud provider manages the provisioning and maintenance of the infrastructure letting you focus on building the app logic. It enables you to run pieces of code or functions, written in the programming language of your choice, in the cloud. In other words, Function as a service (FaaS), or a microservice that is hosted on a cloud. Your function app is automatically scaled up or down depending on load.

Here Are Some Benefits of Serverless Computing

  • Write your own business logic in the language code of your choice
  • You do not need to manage any servers hardware or resources
  • You are charged based on what is used and not on reserved time
  • You can avoid over-allocation of your infrastructure - by scaling up or down automatically
  • It provides stateless logic - function instances are created and destroyed on demand
  • Functions are event-driven - they run only in response to a trigger or in other words to an event
  • The function app can be moved to a traditional compute environment - should the needs of your app change, you can move and deploy it in a non-serverless environment

What are Azure Functions

Azure Functions is a serverless application platform provided by Microsoft. This allows developers to host business logic with the benefits of serverless computing. Azure Functions provides the scalability that it is needed and will charge only for the resources used. You can write your function app code in the language of your choice, like C#, F#, or JavaScript. It supports NuGet and NPM so you can use your favorite library in your business logic.

Ready to Play

Note: Make sure you have an Azure account. If not, click here to create a free one.

Let Us Create a Function App

  1. Sign into the Azure portal.
  2. Select the Create a resource button found on the upper left-hand corner of the portal.
  3. Select the Get started button and click the Function App link.

    Function App Dialog

  4. Enter a unique App name; this will also serve as the service base URL, i.e., you can name it pizza-functions-xxxxxxx, where the x's can be replaced with your initials and your birth year.
  5. Select a Subscription that you would like the app to be hosted.
  6. Under Resource Group, select Create new - the name will match the App name. Leave the name as it is.
  7. For the OS, select Windows.
  8. For the Hosting Plan, select the Consumption Plan to provide the serverless computing benefits.
  9. Under Location, select the geographical location closest to you.
  10. For the Runtime Stack, we are going to select JavaScript from the dropdown.
  11. Under Storage select the Create new and use the one that was automatically created.
  12. Leave the Application Insights name as it is.
  13. Click the Create button. The deployment will take a few minutes and you will receive a notification when complete.

    Notification

Now that you have created your very own function app, let us execute an actual function. First, a few terms and concepts to know.

Triggers

These are event objects that define how a function is invoked. You must configure a function with one event trigger. Functions are event-driven and it requires a trigger to run.

Bindings

These are the connection to data within your function. You do not have to write code in your function to connect to your data sources and to manage the connections because it takes care of the complexity for you. Each function can have none or more bindings to manage the input and output of data.

There Are Two Kinds of Binding

  • Input binding - A connection to a data source. Your function can read data from these inputs.
  • Output binding - A connection to a data destination. Your function can write data to these destinations.

Azure provides a large list of bindings to connect to different storage and messaging services.

Verify Your Function App Was Created

  1. Click the Resource groups button on the left-hand menu of the portal.
  2. Click the resource group name link that matches the function app name that you previously created.
  3. You should see a list like this:

    Function App Icon

    Note: The one with the lightning bolt icon is your function app.

  4. Click the function app name link.

    Function App URL

    Note: You will notice you have a public URL assigned to it.

    Function App Web Pagel

    If you click on the URL, you should get a default web page indicating the function app is running.

    Now, we are going to add an actual function with a logic template to the function app.

  5. Click the + New function button on the app dashboard.

    New Function

  6. Select the In-portal box and click the Continue button at the bottom.
  7. Select the More templates… box and click Finish and view templates button.
  8. Select the HTTP trigger box from the list.
  9. In the New Function dialog box, enter OvenTemperatureService in the Name field and leave the Authorization level as Function.
  10. Click the Create button. After a few seconds, the code editor will open an index.js file with the template code contents.

Test Your Template Function

  1. From the index.js code editor, click the </> Get function URL to get the endpoint.

    </> Get function URL

  2. From the Get function URL dialog, copy the URL and close the dialog box.
    Note: This URL has your Function Key. This allows you to protect access to your HTTP triggered functions by means of the authorization key.
  3. Paste the URL in a safe place like Notepad for later use.
  4. On the left-hand side, expand your function app and expand Functions and click the Manage button.
  5. Download and install Postman to test the function app. Postman is a tool app for testing web services.
  6. Create a new request with Postman:
  7. Use a POST request and paste the URL from your Get function URL dialog you copied.
  8. Under the Params tab, add the following key-value pair:
    • For the Key enter name and for the Value enter Azure Function.
  9. Under the Headers tab, add the following key-value pair:
    • for the Key enter Content-Type and for the Value enter application/json.
  10. Click the Send button and Postman will get the response back with the text Hello Azure Function.

    Yay! It works, you are able to communicate with the function app through HTTP.

Now, let's add our own logic to the function to meet the requirements for the Pizzeria company.

Requirements for Your Function

  • A pizza cooking temperature between 0 to 300 degrees F should be flagged as COLD.
  • A pizza cooking temperature between 400 to 500 degrees F should be flagged as GREAT.
  • A pizza cooking temperature between 600 to 700 degrees F should be flagged as BURNT

Add Your Code to the Function

  1. Open the Azure portal.
  2. In the index.js file, replace the template code with the following code:
    module.exports = function(context, req) {
    	context.log('OvenTemperature Service triggered');
    	if (req.body && req.body.readings) {
    		req.body.readings.forEach(function(reading) {
    			let dateTime = new Date(reading.timestamp * 1000);
    			dateTime.toLocaleString('en-US');
    			if (reading.temperature <= 300) {
    				reading.status = 'COLD';
    			} else if (reading.temperature <= 500) {
    				reading.status = 'GREAT';
    			} else {
    				reading.status = 'BURNT';
    			}
    			context.log(
    				`The Pizza Oven Temperature Reading is ${
    					reading.status
    				} at ${dateTime}
                    for Oven at ${reading.factory}`
    			);
    		});
    
    		context.res = {
    			// status: 200, /* Defaults to 200 */
    			body: {
    				readings: req.body.readings,
    			},
    		};
    	} else {
    		context.res = {
    			status: 400,
    			body:
    				'Please send an array of temperature readings in the request body',
    		};
    	}
    	context.done();
    };
  3. Click the Save button at the top of the code editor.

    This is a simple logic that iterates over the array of readings and checks through the fields and outputs the status of the oven, the date time and factory name.

Let Us Test Our Own Logic

  1. Open the Postman tool app.
  2. Create a new request with Postman:
  3. Use a POST request and paste the URL from your Get function URL dialog you copied before.
  4. Under the Headers tab, add the following key-value pair:
    • Under the Key, enter Content-Type and for the Value enter application/json.
  5. Click the Send button and Postman will get the response back with the text Please send an array of temperature readings in the request body. This means we need some data.
  6. Now, we are going to add some data. Under the Body tab, select the raw radio button and select JSON (application/json) from the dropdown.
    • Paste the following JSON snippet sample readings request into the request body text box:
      {
          "readings": [
              {
                  "factory": "Waterbury Pizza Pizza Factory",
                  "temperatureId": 1,
                  "timestamp": 1554391200,
                  "temperature": 203
              },
              {
                  "factory": "Harford DiGeorgio Factory",
                  "temperatureId": 3,
                  "timestamp": 1554391800,
                  "temperature": 400
              },
              {
                  "factory": "New York Migrante Factory",
                  "temperatureId": 3,
                  "timestamp": 1554390800,
                  "temperature": 298
              },
              {
                  "factory": "Orlando Raton Pizza Factory",
                  "temperatureId": 18,
                  "timestamp": 1554392100,
                  "temperature": 658
              }
          ]
      }
  7. Click the Send button and Postman will get the response back of the JSON.
  8. Go back to the Azure portal and the index.js code editor.
  9. Open the Logs tab in the bottom flyout of the page. The following screenshot shows an example response in the messages in the Logs pane.

    Logs

    You can see that our status field has been correctly added to each of the readings along with the date time and factory name.

  10. If you navigate to the Monitor dashboard, you'll see that the request has been logged to Application Insights.

    Application Insights

    Pat yourself in the back! It works, your serverless function app is able to receive several sample readings through HTTP. These readings will give you the status of each oven at each pizzeria factory oven.

You are on your way to provide the reusable service that the Pizzeria company needs.

Summary

You did it! You played and tested a serverless function app. You have learned how to create and host a Function app with business logic in the cloud. A great way to add serverless hosted services to your solution that can scale and grow.

Azure, in this case, manages the infrastructure and you focus on the code. You can also integrate with other services, like GitHub, Twilio, etc. to create complex Serverless workflows quickly and easily. The Pizzeria Company can now determine the best time to schedule maintenance for each of the pizzeria factories.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Javier Carrion
Tester / Quality Assurance
United States United States
A QA analyst & aspiring developer with years of tech experience that began with making & repairing PCs to currently talking & commanding PCs. An introvert trying to be a social butterfly @seetechnologic. ❤️ art & #tech! Fun fact: Met my bodybuilder Angel on spring break & never left FL.

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionExcellent stuff. Pin
David Pierson6-May-19 15:07
memberDavid Pierson6-May-19 15:07 
AnswerRe: Excellent stuff. Pin
Javier Carrion7-May-19 1:43
memberJavier Carrion7-May-19 1:43 
GeneralMy vote of 5 Pin
David Pierson6-May-19 15:06
memberDavid Pierson6-May-19 15:06 
GeneralMy vote of 5 Pin
Florian Rappl30-Apr-19 11:47
professionalFlorian Rappl30-Apr-19 11:47 
GeneralRe: My vote of 5 Pin
Javier Carrion30-Apr-19 12:41
memberJavier Carrion30-Apr-19 12:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190518.1 | Last Updated 1 May 2019
Article Copyright 2019 by Javier Carrion
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid