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
- Sign into the Azure portal.
- Select the Create a resource button found on the upper left-hand corner of the portal.
- Select the Get started button and click the Function App link.
- 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.
- Select a Subscription that you would like the app to be hosted.
- Under Resource Group, select Create new - the name will match the App name. Leave the name as it is.
- For the OS, select Windows.
- For the Hosting Plan, select the Consumption Plan to provide the serverless computing benefits.
- Under Location, select the geographical location closest to you.
- For the Runtime Stack, we are going to select JavaScript from the dropdown.
- Under Storage select the Create new and use the one that was automatically created.
- Leave the Application Insights name as it is.
- Click the Create button. The deployment will take a few minutes and you will receive a notification when complete.
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
- Click the Resource groups button on the left-hand menu of the portal.
- Click the resource group name link that matches the function app name that you previously created.
- You should see a list like this:
Note: The one with the lightning bolt icon is your function app.
-
Click the function app name link.
Note: You will notice you have a public URL assigned to it.
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.
-
Click the + New function button on the app dashboard.
- Select the In-portal box and click the Continue button at the bottom.
- Select the More templates… box and click Finish and view templates button.
- Select the HTTP trigger box from the list.
- In the New Function dialog box, enter OvenTemperatureService in the Name field and leave the Authorization level as Function.
- 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
- From the index.js code editor, click the </> Get function URL to get the endpoint.
- 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. - Paste the URL in a safe place like Notepad for later use.
- On the left-hand side, expand your function app and expand Functions and click the Manage button.
- Download and install Postman to test the function app. Postman is a tool app for testing web services.
- Create a new request with Postman:
- Use a POST request and paste the URL from your Get function URL dialog you copied.
- Under the Params tab, add the following key-value pair:
- For the Key enter
name
and for the Value enter Azure Function
.
- Under the Headers tab, add the following key-value pair:
- for the Key enter
Content-Type
and for the Value enter application/json
.
- 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
- Open the Azure portal.
- 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 = {
body: {
readings: req.body.readings,
},
};
} else {
context.res = {
status: 400,
body:
'Please send an array of temperature readings in the request body',
};
}
context.done();
};
- 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
- Open the Postman tool app.
- Create a new request with Postman:
- Use a POST request and paste the URL from your Get function URL dialog you copied before.
- Under the Headers tab, add the following key-value pair:
- Under the Key, enter
Content-Type
and for the Value enter application/json
.
- 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. - 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
}
]
}
- Click the Send button and Postman will get the response back of the JSON.
- Go back to the Azure portal and the index.js code editor.
- 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.
You can see that our status field has been correctly added to each of the readings along with the date time and factory name.
- If you navigate to the Monitor dashboard, you'll see that the request has been logged to 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.