Ad Code

✨🎆 JOIN MERN, JAVA, PYTHON, AI, DEVOPS, SALESFORCE Courses 🎆✨

Get 100% Placement Oriented Program CLICK to new more info click

Azure Functions

Azure Functions Tutorial for Beginners | Serverless Computing in Azure

In this tutorial, we will learn Azure Functions in Microsoft Azure with practical examples.

This tutorial is specially designed for beginners, students and developers who want to learn Serverless Computing in Azure Cloud.


What is Azure Function?

Azure Function is a Serverless Computing Service provided by Microsoft Azure.

It allows developers to run small pieces of code without managing servers or infrastructure.

Simple Definition

Azure Functions allow you to execute code on-demand whenever an event occurs.


Real Life Example

Suppose:

  • User uploads an image
  • Azure Function automatically resizes the image
  • Email notification is sent

All this happens automatically without managing any server.


Advantages of Azure Functions

  • No Server Management
  • Automatic Scaling
  • Pay Only When Code Runs
  • Easy Integration with Azure Services
  • Supports Multiple Programming Languages

Supported Languages

  • C# .NET
  • JavaScript
  • Python
  • Java
  • PowerShell

Types of Azure Function Triggers

Trigger Type Description
HTTP Trigger Runs when API URL is called
Timer Trigger Runs on scheduled time
Blob Trigger Runs when file uploaded in Blob Storage
Queue Trigger Runs when message added in Queue
Event Hub Trigger Runs when event received

Azure Function Architecture

User Request
      |
      ↓
Azure Function Trigger
      |
      ↓
Function Executes
      |
      ↓
Response Returned

Step-by-Step Azure Function Practical

Step 1: Open Azure Portal

  1. Login to Azure Portal
  2. Search "Function App"
  3. Click Create

Step 2: Create Function App

Fill the following details:

  • Subscription
  • Resource Group
  • Function App Name
  • Runtime Stack → .NET
  • Region

Click Review + Create.


Step 3: Create Function

  1. Open Function App
  2. Go to Functions
  3. Click Create
  4. Select HTTP Trigger
  5. Choose Authorization Level

First Azure Function Example

HTTP Trigger Function in C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

public static class DemoFunction
{
    [FunctionName("DemoFunction")]
    public static IActionResult Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")]
        HttpRequest req,
        ILogger log)
    {
        return new OkObjectResult("Hello Azure Function");
    }
}

[Function("GetExternalServiceURL")] public IActionResult GetExternalServiceURL([HttpTrigger(AuthorizationLevel.Function, "get", Route = "externalservice/getexternalserviceurl")] HttpRequest req) { var externalServiceUrl = Environment.GetEnvironmentVariable("SomeExternalService"); return new OkObjectResult(externalServiceUrl); } [Function("WorkWithSqlDBConnectionString")] public IActionResult WorkWithSqlDBConnectionString([HttpTrigger(AuthorizationLevel.Function, "get", Route = "connectionstring/getsqlconnectionstring")] HttpRequest req) { var sqlConnectionString = _configuration.GetConnectionString("SqlConnectionString"); return new OkObjectResult(sqlConnectionString); }
{ "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "UseDevelopmentStorage=true", "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated", "SomeSetting": "SomeValue", "SomeExternalService": "SomeExternalServiceURL" }, "ConnectionStrings": { "SqlConnectionString": "This is sql connection string" } }

How to Test Azure Function?

  1. Open Azure Function
  2. Click Get Function URL
  3. Copy URL
  4. Paste in Browser or Postman

Output:

Hello Azure Function

Azure Timer Trigger Example

Timer Trigger executes automatically at scheduled time.

Example:

  • Send daily email
  • Create automatic backup
  • Generate reports

What is Authorization Level

In Azure Functions, the Authorization Level determines who can access an HTTP-triggered function.

Authorization Levels

LevelDescription
AnonymousAnyone can call the function without a key.
FunctionRequires a function key to access.
AdminRequires the host (master) key. Full access.

1. Anonymous

No authentication is required.

[Function("HelloWorld")]
public HttpResponseData Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get")]
HttpRequestData req)
{
// Anyone can access
}

URL:

https://yourapp.azurewebsites.net/api/HelloWorld

2. Function

Requires a function key.

[Function("GetUsers")]
public HttpResponseData Run(
[HttpTrigger(AuthorizationLevel.Function, "get")]
HttpRequestData req)
{
// Requires function key
}

URL:

https://yourapp.azurewebsites.net/api/GetUsers?code=FUNCTION_KEY

3. Admin

Requires the host (master) key.

[Function("AdminTask")]
public HttpResponseData Run(
[HttpTrigger(AuthorizationLevel.Admin, "post")]
HttpRequestData req)
{
// Requires host key
}

URL:

https://yourapp.azurewebsites.net/api/AdminTask?code=HOST_KEY

Where to Find Function Keys

In the Azure Portal:

  1. Open your Function App.
  2. Select the Function.
  3. Click Function Keys.
  4. Copy the generated key.

You can also create custom keys.

What is CRON expression?

It's used to schedule function.

CRON expression format:

{second} {min} {hr} {day} {month} {day-of-week}

Examples:

Every hour
= 0 0 * * * *
Every 5 mins
= 0 */5 * * * *
On 1st of every month
= 0 0 0 1 * *

CRON Expression in Azure Function

In Azure Functions, CRON expression is used with Timer Trigger to execute a function automatically at a specific time.

Example:

using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;

namespace TimerFunctionDemo
{
public class MyTimerFunction
{
private readonly ILogger _logger;

public MyTimerFunction(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<MyTimerFunction>();
}

[Function("MyTimerFunction")]
public void Run(
[TimerTrigger("0 */5 * * * *")] TimerInfo timer)
{
_logger.LogInformation(
$"Function executed at: {DateTime.Now}");
}
}
}

Timer Trigger Code

using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;

public static class TimerFunction
{
    [FunctionName("TimerFunction")]
    public static void Run(
        [TimerTrigger("0 */5 * * * *")] TimerInfo myTimer,
        ILogger log)
    {
        log.LogInformation("Timer Trigger Executed");
    }
}

This function runs every 5 minutes.


Azure Blob Trigger Example

Blob Trigger executes whenever a file is uploaded to Blob Storage.

Use Cases

  • Image Processing
  • PDF Processing
  • Video Compression

Blob Trigger Example

using System.IO;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;

public static class BlobFunction
{
    [FunctionName("BlobFunction")]
    public static void Run(
        [BlobTrigger("images/{name}")]
        Stream myBlob,
        string name,
        ILogger log)
    {
        log.LogInformation($"File Name: {name}");
    }
}

Azure Queue Trigger Example

Queue Trigger executes when a message is added in Azure Queue Storage.

Use Cases

  • Order Processing
  • Email Notifications
  • Background Jobs

Queue Trigger Example

using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;

public static class QueueFunction
{
    [FunctionName("QueueFunction")]
    public static void Run(
        [QueueTrigger("orders")] string message,
        ILogger log)
    {
        log.LogInformation($"Message: {message}");
    }
}

Azure Function Pricing

Consumption Plan

  • Pay only when function executes
  • Best for students and beginners
  • Very low cost

Premium Plan

  • High performance
  • Advanced scaling
  • Enterprise applications

Advantages of Serverless Computing

  • No Infrastructure Management
  • Automatic Scaling
  • Faster Development
  • Cost Effective
  • Easy Deployment

Real-Time Project Ideas

1. Email Notification System

  • Queue Trigger
  • Send automatic email

2. Image Processing System

  • Blob Trigger
  • Resize images automatically

3. Attendance Reminder System

  • Timer Trigger
  • Send reminder every morning

Important Interview Questions

  • What is Azure Function?
  • What is Serverless Computing?
  • Difference between Web App and Azure Function?
  • What are Triggers in Azure Functions?
  • What is Consumption Plan?
  • What is Cold Start in Azure Functions?

Difference Between Azure Function and Web API

Azure Function Web API
Serverless Requires Server Hosting
Event Driven Request Driven
Auto Scaling Manual Scaling
Pay Per Execution Fixed Hosting Cost

In Azure Functions, a Binding is a declarative way to connect your function to external services without writing a lot of integration code.

There are three types of bindings:

1. Trigger Binding (Input Event)

A trigger starts the function execution.

Examples:

  • HTTP Trigger
  • Timer Trigger
  • Blob Trigger
  • Queue Trigger
  • Service Bus Trigger
[Function("GetData")]
public HttpResponseData Run(
[HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequestData req)
{
// Function executes when HTTP request arrives
}

2. Input Binding

Input bindings provide data from an external source to your function.

Example: Read data from Azure Blob Storage.

[Function("ReadBlob")]
public void Run(
[BlobTrigger("input/{name}")] Stream blobData,
string name)
{
Console.WriteLine($"Processing {name}");
}

Other Input Bindings:

  • Azure Blob Storage
  • Azure Queue Storage
  • Azure Table Storage
  • Cosmos DB
  • Service Bus

3. Output Binding

Output bindings send data to an external service.

Example: Write message to Azure Queue.

[Function("SendMessage")]
[QueueOutput("orders")]
public static string Run(
[HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req)
{
return "New Order Created";
}

The returned string is automatically written to the orders queue.

Post a Comment

0 Comments