Azure Function 101: A Step-by-Step Guide for Beginners

Ipshita
11 min readJul 7, 2023
Photo by Tomas Sobek on Unsplash

What are API’s?

An API (Application Programming Interface) is a set of rules and protocols that allow two or more applications to communicate with each other. APIs are used to make it easier for developers to access data and functionality from other applications and services. With APIs, developers can create amazing applications that can interact with other services, allowing users to access data and functionality from a variety of sources.

APIs are important because they allow developers to create applications that can interact with other services, providing users with access to data and functionality from a variety of sources. APIs also make it easier for developers to build applications that use existing data and functionality, allowing them to save time and money. Finally, APIs make it easier for developers to create applications that can be used across multiple platforms, making them more accessible to users.

From a data scientist point-of-view APIs are particularly important as they enable data scientists to access data from a variety of sources and to quickly develop data-driven applications. APIs allow data scientists to easily access data from multiple sources and to process it in an efficient manner. Furthermore, APIs enable data scientists to quickly develop applications that can interact with other services and to leverage machine learning algorithms to make predictions and decisions.

But this article is about Azure Functions?

Azure functions are event-driven, server-less compute services that allow developers to run code without worrying about provisioning or managing infrastructure. They are important in making API’s because they provide developers with an easy and cost-effective way to run code without having to set up and maintain servers, making it easier to create and deploy API’s quickly. Azure functions also provide scalability, as they can automatically scale up or down based on demand. This helps reduce costs by only running code when needed.

Azure Functions allows developers to natively develop applications in languages including Python, Java, JavaScript, PowerShell, and C#, and enables custom handler development. For added efficiency, Visual Studio offers seamless integration with Azure Functions. Debugging is effortless thanks to Application Insights integration. Plus, the Cross-Origin Resource Sharing (CORS) feature grants additional security by enabling developers to determine which domains are authorized to run the API. For more information, please refer to the custom handler documentation.

Codes can be found here.

V1 and V2 Programming model

The newly released v2 programming model in Azure function is an upgrade to the previous version, allowing developers to create multiple functions with one python file, while being far more lightweight compared to its predecessor. The main distinguishing difference from the v1 model lies in its triggers and bindings, which are declared as decorators; moreover, its simplified folder structure and comprehensive documentation make the v2 model more accessible for users. Although structural changes would need to be taken into consideration, functions created using the v2 model can be monitored, debugged and deployed similarly to it’s predecessor.

Creating Azure Functions

Prerequisites

Prior to beginning development, we need to install essential core tools to enable development of Azure Functions from Visual Studio. MSI (Microsoft Software Installer) can be used to facilitate easy download of such tools. Find the link here.

Creating a Function App:

Regardless of the python model, we will have to create a :

To create an Azure Function, head to portal.azure.com and select the “Azure Function” option. It is advised to review the costing beforehand.

Search for “function app” from the search bar

Navigate to the Functions App and select “Create”.

Select Create from the top left corner

When creating a function app, we must provide detailed parameters, first and foremost, we need to provide the subscription and resource group where the function app should be created.

Selecting the resource group and subscription

Next, we need to specify the technical details of the function app, including name of the instance, the language (e.g. Python), version (e.g. 3.8), and operating system (Linux only due to Python’s OS compatibility) and the region where we want it to be set. Choose the type of hosting that best meets your needs.

Selecting technical details about instance

It is recommended to keep storage, networking and deployment in their default states. To facilitate easy searching, it is also advisable to add appropriate Tags. Gaining useful insights into debugging processes can be facilitated by enabling the Application Insights feature from the Monitoring tab. One thing to keep in mind is, Application Insight is not available in all regions, please check for the availability before proceeding.

Enable Application Insights

Review the function app and click create:

Now, after the Function App has been created, it’s time to get back to our geeky screens in VSCode and create the function for our function app. We can create several functions inside a function app. First, let’s look at how to create a “v1” type function.

Creating v1 type function:

  • Initialize the function app — To get started on your function, simply run the command “func init”. This will create a new directory with the necessary files and boilerplate code to get started. You will then be prompted to select the language of your choice as well as other options such as the name of the function. After that, the initial set up will be complete and you can begin developing your function.
Prompted for language after func init
  • Create new function — We then create a new function by choosing an HTTP trigger. From the 16 different types of functions available, we select this one for our demo. An HTTP Trigger function in Azure is a type of cloud compute service that executes a custom user-defined code in response to an HTTP request. This is a great type of function to use if your application requires an action to be taken when an HTTP request is received.
On selecting the type of function, it will then ask for the name. And write down the boilerplate files.
The two files that were written are function.json and __init__.py
  • Code the function — The next step is to put the function into action. To do this, I will create a simple program which will take two inputs and call the function to add them together. The result of that will then be returned by the API. This way, I will be able to use this function for our purpose and understand how it works.

Let us first examine the function.json file. The first line specifies that the code for the function is located in the __init__.py file. Then, we can observe two bindings, which are used to connect input and output data to the function. Through the bindings, one can define how the function will interact with other services and resources.

The first binding that the function will be triggered by states that it will accept both GET and POST HTTP requests, and will require authorization to be handled at the function level, rather than at the app level; in simpler terms, an API key specifically for this function will be required for access. The second binding specifies that the function will return an HTTP response and will be stored in the “$return” variable.

“In” and “out” refer to the direction of data flow. In this case, “direction”: “in” means that the “req” binding is an input binding that will receive data from the HTTP request, and the function will use this data to generate a response. Conversely, “direction”: “out” indicates that the “$return” binding is an output binding that will send the generated response back to the client that made the HTTP request.

{
"scriptFile": "__init__.py",
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "$return"
}
]
}

The below code defines a function called “main”, which receives a single parameter named “req”. This parameter is an instance of the “HttpRequest” class, defined in the “func” module. By looking at the json file above, we can see that we are defining req in the binding. The “-> func.HttpResponse” indicates that the function will return an instance of the “HttpResponse” class, also found in the “func” module. Thus, this function will take an HTTP request as input, process it, and output an HTTP response.

In the function, we take values for num1 and num2 by extracting the ‘first_number’ and ‘second_number’ parameter respectively from the query string of an HTTP request that triggers an Azure Function. After we add the numbers, we return the output in the form of an HTTP response.

import logging
import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')

num1 = req.params.get('first_number')
if not num1:
try:
req_body = req.get_json()
except ValueError:
pass
else:
num1 = req_body.get('first_number')

num2 = req.params.get('second_number')
if not num2:
try:
req_body = req.get_json()
except ValueError:
pass
else:
num2 = req_body.get('second_number')

sum = int(num1) + int(num2)

if sum:
return func.HttpResponse(str(sum))
else:
return func.HttpResponse(
"Please pass two numbers to get the sum.",
status_code=200)
  • Deploy and debug locally

To deploy the function, we go back to our terminal, type “func start” and run the command. After the function starts, we will get the following link.

Copy the link and open Postman. Start by picking whether you’re using GET or POST for your function — as we’ve specified both in our function.json file, either one works. Paste the link you got from the terminal into Postman and then add the parameters that your function needs. We needed two of them for our function, and made sure to include each parameter with the same name as specified in the script file (__init__.py). After everything is in place, hit Send and if all goes well you’ll get the response you’re looking for.

  • Publish to function app

Once we’ve tested the function, we’re ready to publish! To publish, we go back to the portal, and navigate to the function app where we want to add the function. Next, go to Functions, then click Create. When we click ‘Create’, a blade opens up — from the dropdown, select “Any editor + Core Tools.” Scroll down and find the command for publishing the function: “func azure functionapp publish <name of function app>”. Take this command and run it in your local terminal.

V2 Model

Azure Function V2 model is a significant upgrade that allows development of function apps in .NET Core, instead of the .NET framework used in Azure Function V1. This advancement provides better performance and allows cross-platform development with support for various popular languages such as JavaScript, C#, and Python. Additionally, it introduces a new extensions model, making it leaner by moving Azure specific bindings out of the runtime.

To create a V2 model function app in VSCode, we need to use the command palette.

  1. Click on Create Function App in Azure

2. Choose your subscription

3. Give a name to your function app

4. Select a runtime stack (language in which you will write the code)

5. Select the location (Region)

6. After your function app is created, we need to create the functions

7. Select the folder which which is going to have your function app

8. Select a language

9. Select a virtual environment (I will skip this)

10. Select which type of function you want and give a name

11. Select the authorization type

The function created has the following framework. Notice how we have only one script named function_app, in contrast to individual folders that were created in v1 model type.

In code:

Inside the function_app script, notice how different routes are created for different function, this functionality makes the function app light weight.

import azure.functions as func
import logging

app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)

@app.route(route="summation_app")
def summation_app(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')

name = req.params.get('name')
if not name:
try:
req_body = req.get_json()
except ValueError:
pass
else:
name = req_body.get('name')

if name:
return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
else:
return func.HttpResponse(
"This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
status_code=200
)

After we have created the function we can deploy the function from the command palette.

Conclusion

To wrap up, mastering Azure Functions, whether it’s V1 or V2, provides an excellent setup for effective and efficient server-less computing. The comprehensive nature of Azure Functions allows you to create, debug, and deploy your projects with ease. Its vast support for different languages and integration with other Azure services makes it a versatile tool for any developer. The step by step guide provided in this blog post equips beginners with the basic knowledge to kick-start their journey in server-less architecture. Keep exploring and innovating, as Azure Functions have a lot more to offer than meets the eye!

--

--