Sunday, 26 May 2024

Azure Functions: Simple Explanation with Examples

Azure Functions: Simple Explanation with Examples


This article covers how Azure Functions work and how you can leverage them for your projects. Whether you're new to serverless computing or an experienced developer looking to expand your knowledge, this article will guide you through the process of getting started with Azure Functions.

  • Azure Functions simplifies development by removing the need for infrastructure management, allowing developers to focus solely on writing code.
  • Common triggers in Azure Functions include HTTP triggers, timer triggers, blob storage triggers, and queue triggers.
  • Monitoring and logging, including integration with Application Insights, are crucial for tracking the performance and health of Azure Functions.

What is Azure Functions?

Azure Functions is a serverless computing service offered by Microsoft Azure. It enables the execution of small units of code, called functions, without the need to manage servers. These functions are triggered by specific events or inputs, allowing developers to respond to events in real time. By utilizing Azure Functions, developers can focus solely on writing code and not worry about infrastructure management.

Benefits of Using Azure Functions

Below are some of the benefits of using Azure Functions:

  • Serverless Simplicity: Azure Functions allows you to focus solely on writing your code without the need to worry about managing servers. This means you can concentrate on building the functionality of your application without getting caught up in the complexities of infrastructure setup.
  • Language Flexibility: Azure Functions supports popular programming languages such as C#, JavaScript, Python, and PowerShell. This flexibility allows you to use a language you're comfortable with or one that aligns with the requirements of your project.
  • Cost and Performance Optimization: With Azure Functions, you only pay for the actual resources consumed during the execution of your functions. This pay-as-you-go model ensures cost efficiency as you're not charged for idle resources. Additionally, Azure Functions automatically scales based on demand, ensuring that your application can handle varying workloads without sacrificing performance.
  • Streamlined Development and Deployment: Azure Functions simplifies the development and deployment processes. You can focus on writing individual functions that perform specific tasks rather than dealing with the complexities of managing the entire application infrastructure. This streamlined approach speeds up development time and allows you to quickly iterate on your ideas.

Getting Started with Azure Functions

Let's dive into the essentials of Azure Functions before guiding you through the process of creating your first function app.

Azure Functions Essentials

Triggers: Triggers define the events that invoke functions. They can be HTTP requests, timers, storage changes, or messages from queues.

Bindings: Bindings connect functions to external resources or services like Azure Storage or Cosmos DB. They enable seamless integration and data exchange.

Creating an Azure Functions App

To begin your Azure Functions journey, follow these steps:

  • Sign in to Azure: Log in to the Azure portal using your Azure account.
  • Create a Function App: Click on "Create a resource" and search for "Function App" in the Azure Marketplace. Click on "Create" to begin the process.
Fig: Azure Apps portal
  • Configure App Settings: Choose or create a new resource group, provide a unique name for your Function App, and choose your preferred subscription, runtime stack, and hosting plan. The hosting plan includes options like "Consumption Plan" (serverless) or dedicated plans with different pricing models.
Fig: Create a new function app
  • Review and Create: Double-check your configurations and click on "Create" to create the Function App.

Creating Your First Azure Function

Now that you have your Function App set up, it's time to create your first function. We'll create a simple HTTP-triggered function using C#:

  • Open the Function App: Navigate to your newly created Function App in the Azure portal.
  • Add a Function: Click on the "+ New function" button to add a new function.
Fig: Adding a new function in Function App
  • Choose a Trigger: Select "HTTP trigger" as the trigger type. Give your function a name and choose the appropriate authorization level (Function or Anonymous, depending on whether authentication is required), then click on "Create".
Fig: Selecting a trigger
  • Function Code: Navigate to the code + test section to customize the function code to perform the desired task. For example, for an HTTP trigger, the code might look like this:
#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    string responseMessage = string.IsNullOrEmpty(name)
        ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
}

HTTP trigger function code

Testing the Function

  • Get the Function URL: In the code + test section, locate "Get Function URL". Copy the function URL to the clipboard.
Fig: Getting the Function URL
  • Send HTTP Requests: Open a new tab in your web browser. Paste the function URL into the address bar of the new tab. Hit Enter. The function will be invoked, and the response from the function will be displayed in the browser window.
Fig: Test response
  • View Results: Select the "Monitor" tab in the left-hand menu. In the "Monitor" tab, you will be able to access information about your recent HTTP invocations, execution details, and any logged output or errors.
Fig: Azure functions monitor

Common Azure Function Triggers

Azure Functions offer various triggers to handle different types of events. Let's explore some of the most commonly used triggers:

HTTP Trigger

HTTP triggers enable functions to be invoked by HTTP requests. They provide a straightforward way to build API endpoints and handle incoming HTTP requests.

Use Cases: Azure Functions with HTTP triggers can be used to create lightweight and scalable RESTful APIs. They are ideal for processing incoming webhooks from various services and taking appropriate actions.

Timer Trigger

Timer triggers allow functions to be executed on a schedule, such as every hour, day, or week. They are useful for tasks like data synchronization or periodic cleanup.

Use Cases: Time-triggered functions enable the automated execution of tasks like generating reports, aggregating data, or sending regular notifications based on specific time intervals.

Azure Blob Storage Trigger

Azure Blob Storage Trigger allows functions to respond to changes, such as new file additions, modifications, or deletions in the Azure Blob storage.

Use Cases: The Azure Blob Storage Trigger automates actions and initiates functions in response to specific events within a Blob storage container, including file uploads, modifications, or deletions.

Azure Queue Triggers

Queue triggers allow functions to process messages from Azure Storage queues or Azure Service Bus queues. They enable asynchronous and reliable message processing. This means that messages can be processed concurrently and independently without being restricted to a specific sequence or order.

Use Cases: Queue-triggered functions can be used to process incoming orders, validate data, or trigger downstream operations asynchronously, making them ideal for handling messages.

Azure Event Grid Trigger

Azure Event Grid provides a centralized event routing service that simplifies building event-driven applications. It allows you to subscribe to events from various Azure services and custom publishers.

Use Cases: Azure Functions can process events from various Azure services like Cosmos DB, Azure Storage, or Azure Service Bus and react to document inserts, file uploads, or other events from these services.

Monitoring and Logging Azure Functions

Monitoring and logging are crucial for understanding the performance and health of your Azure Functions. Fortunately, Azure Functions offers built-in monitoring capabilities to track function execution, performance metrics, and health. However, by integrating application insights, you gain advanced monitoring capabilities and robust logging functionality. This allows you to capture and analyze logs from your Azure Functions alongside other telemetry data, providing a comprehensive view of your application's performance.

Azure Functions Best Practices

For anyone looking to utilize Azure Functions, understanding and implementing the best practices is vital for building reliable serverless applications. These practices serve as guiding principles to optimize performance, maintain application stability, and ensure a seamless user experience. Let's take a closer look at each best practice and why they matter:

  1. Setting up alerts for critical metrics: As previously mentioned, monitoring the performance of your Azure Functions is crucial. By setting up alerts for key metrics like response times and resource utilization, you can be promptly notified of any issues that may arise. This proactive approach allows you to take immediate action, reducing potential downtimes and maintaining a smooth user experience.
  2. Optimizing deployment strategy: Simplifying the deployment process is vital for efficient application management. Adopting the "run from package" approach reduces deployment errors and enhances application stability. Consider continuous deployment to streamline integration with your source control solution.
  3. Leveraging Application Insights: Gaining insights into your function execution and user interactions is essential for optimizing performance. Integrating Azure Application Insights provides valuable monitoring and diagnostics capabilities, helping you identify performance bottlenecks and improve overall application efficiency.
  4. Designing for concurrency and scalability: Preparing your application for varying workloads and potential increases in demand is essential. Utilize triggers like Azure Event Grid and implement a retry pattern to ensure your application remains responsive under heavy loads.
  5. Prioritizing security in development and deployment: Security is a top priority for any application. Follow secure coding practices such as storing sensitive data in Azure Key Vault and applying role-based access control (RBAC) and managed identities to safeguard your Azure Functions from potential threats.

 

Azure Functions Tutorial

 

Azure Functions Tutorial

1. Goto the search bar and search for function App and open it

search bar

2. Click on create to create a new function app.

new function app

3. Fill in the details and proceed to click on Review + Create

create a new function

4. If you are satisfied with the review, click on Create at the bottom

review

5. Wait for a minute or two until the function app gets created. You can check the status by clicking on the notification icon (bell icon).

notification icon

6. Once the status turns to green, that is, a tick mark as shown, click on the go-to resource to proceed. This will take us inside the function app.

function app

7. This is how the created function app will look. Check the left column for Functions and click to proceed.

click to proceed

8. After this, click on add, to create a new function.

click on add

9. Choose the Develop in portal option and choose the HTTP trigger as the template and click on add below.

HTTP trigger

10. Wait for the function to be created and click on Code + Test.

Code + Test

11. After this, click on the Get function URL.

function URL

12. Paste the URL on the browser and check if it is loading. If not, recheck the process.

Paste the URL

13. It asks to pass a name as a string.

At the end of the URL, type &name=”AbC”

AbC is just an example name, anything can be used in place of that.

Like it can be seen in the given picture, the name gets reflected on the page. This is done by the HTTP trigger function which we created.

HTTP trigger function

Introduction To Azure Functions App| Features| Implementing Azure Function App

 Introduction To Azure Functions App| Features| Implementing Azure Function App


Azure Functions App

Azure Functions App is the serverless computing service hosted on the Microsoft Azure public cloud. Azure Functions App, and serverless computing, in general, are designed to accelerate and simplify application development.

Traditional application development demands a consideration of the underlying IT infrastructure. For cloud computing, an IT team must create, monitor, and pay for cloud computing instances — regardless of how much work that instance actually does for the business.

The idea behind serverless computing, also known as function as a service, is to eliminate those infrastructure considerations for the user. With serverless, a user can simply create and upload code, and then define the triggers or events that will execute the code. Triggers can come from a wide range of sources, including another user’s application or other cloud services, such as databases and event and notification hubs.

Once a trigger or event occurs, it is the cloud provider’s responsibility to load the code into a suitable execution environment, run the code and then release the compute resources. There are still servers involved, but the user no longer needs to provision or manage compute instances. In addition, rather than pay for those compute instances and other associated resources each month, users pay for serverless computing based on the amount of time a function runs in a given billing cycle.

Features Of Azure Functions App

1. Multiple Language Support: Azure Functions support many languages. You can write the functions in different languages of your choice like C#, Python, Java,Javascript,PHP,Node.js, etc.

2. Serverless applications support: With serverless, we can simply create and upload the code for the application, and then we just need to define the triggers or events that will execute the function. It reduces the developer’s time and the unnecessary headache to worry about the infrastructure as a developer.

3. Pay as you use pricing model: Azure functions provide the pay as you use a pricing model that helps to save a lot of costs. You just need to pay for the time the code is run.

4. Easy integration with Azure services and other 3rd-party services: Another cool feature of Azure Function is, You can easily integrate the Azure Function with different Azure services and Along with that, you can also easily integrate with different 3rd-party services like Azure DevOps services, Github, Azure CosmosDB, Azure Event Grid, etc.
5. Continuous Deployment and Integration support: Azure Function supports  Continuous deployment and integration because Developers still need them along with GitHub, Microsoft Visual Studio Team Services, Eclipse, etc.

Implementing Azure Functions App

1. In the Azure portal, click on Create a resource. (Please make sure you have a subscription before doing all this. If you created a free account for the first time, you’ll already have a FREE TRIAL subscription for 1 month).

2.  Now, click on the Azure Function App option to create one.

function app

3. Now, fill in all the details such as resource group, name of the function app, publishing option, runtime stack which is the language, version of the runtime stack, and the region to deploy the app. Then click on Next: hosting.

function appfunction app
hosting
4. Then click on Next: Monitoring if you don’t want to make any changes in the service plan. Then click on Review + create.

monitoring
5. Now, click on Create.

create function app
6. Now, click on Go to the resource. Then click on the Functions option in the Overview of your Functions App.

deploying function app
7. Then click on the Add option present there. After that, a window will open on the right, and select the HTTP trigger option present there.

8. Then in the new window give a new name to your function if you want and then change the authorization level to anonymous for this demo.

new function
new function9. Then click on Create Function. After that, a new HTTP trigger will be created. Select the option of Get File URL and then click on the copy to clipboard button to copy the URL.

10. Then paste the URL that you copied in a new tab and pass a parameter in that by adding “name=Your_Name” at the end of the URL as shown below. Then hit Enter. You’ll be treated with a message saying that the HTTP trigger function is executed successfully.

 

11. Now, if you go back to the previous tab where your HTTP trigger function was created and click on Code+Test and then Logs. Then, there you’ll be able to see that your trigger function executed successfully.