DEV Community

Cover image for Getting Started with Azure Functions: A Beginner's Guide
David Au Yeung
David Au Yeung

Posted on

Getting Started with Azure Functions: A Beginner's Guide

Introduction

Azure Functions is a powerful serverless compute service that allows you to execute event-triggered code without worrying about managing infrastructure. It's ideal for lightweight tasks, automation workflows, or building application components that are triggered on demand.

In this article, we will walk through creating your first Azure Function using an HTTP trigger written in C#. You'll also learn how to run the function locally, deploy it to Azure, and explore other trigger types to unlock the full potential of Azure Functions.

Example: Azure Function with HTTP Trigger (C#)

Goal

The goal is to create an Azure Function that responds to an HTTP request with a personalized message.

Prerequisites

Before you get started, ensure you have the following:

1) Azure account (sign up for a free trial on the Azure Portal if needed).
2) Azure Functions Core Tools (a CLI for local development).

To install Azure Functions Core Tools:

npm install -g azure-functions-core-tools@4 --unsafe-perm true
Enter fullscreen mode Exit fullscreen mode

3) Visual Studio Code or Visual Studio (optional, for code editing).
4) .NET SDK (required for C# development).

Step 1: Create a Function Project

1) Open your terminal and initialize a new Azure Functions project:

   func init MyHttpFunction --dotnet
Enter fullscreen mode Exit fullscreen mode

This creates a new project folder called MyHttpFunction.

2) Add a new HTTP-triggered function:

   cd MyHttpFunction
   func new --name HttpExample --template "Http trigger"
Enter fullscreen mode Exit fullscreen mode

When prompted, set the Authorization level to Anonymous for testing purposes.

Step 2: Code Your Function

Open the file HttpExample.cs in the MyHttpFunction folder. You'll see the following code:

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

namespace MyHttpFunction
{
    public static class HttpExample
    {
        [FunctionName("HttpExample")]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["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);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Key Features of This Function:

  • Accepts HTTP GET or POST requests.
  • Looks for a query parameter named name.
  • Returns a greeting message based on the input.

Step 3: Run Locally

To test your function locally:

1) Start the Azure Functions runtime:

   func start
Enter fullscreen mode Exit fullscreen mode

You'll see output similar to:

  Functions:
           HttpExample: [GET,POST] http://localhost:7071/api/HttpExample
   For detailed output, run func with --verbose flag.
Enter fullscreen mode Exit fullscreen mode

2) Open a browser or use a tool like Postman or curl to test the function:

   curl "http://localhost:7071/api/HttpExample?name=DEVTo"
Enter fullscreen mode Exit fullscreen mode

The response will be:

   Hello, DEVTo. This HTTP triggered function executed successfully.
Enter fullscreen mode Exit fullscreen mode

Step 4.1: Deploy to Azure (Optional 1: Azure CLI)

To install Azure CLI:

Invoke-WebRequest -Uri https://aka.ms/installazurecliwindows -OutFile .\AzureCLI.msi
Start-Process msiexec.exe -Wait -ArgumentList "/I AzureCLI.msi /quiet"
Remove-Item .\AzureCLI.msi
Enter fullscreen mode Exit fullscreen mode

or download here

1) Log in to Azure CLI:

   az login
Enter fullscreen mode Exit fullscreen mode

2) Create a resource group:

   az group create --name Testing1 --location canadacentral
Enter fullscreen mode Exit fullscreen mode

3) Create a Function App in Azure:

   az functionapp create \
     --resource-group Testing1 \
     --consumption-plan-location canadacentral \
     --runtime dotnet \
     --functions-version 4 \
     --name MyHttpFunction \
     --storage-account <your-azure-storage-account-name>
Enter fullscreen mode Exit fullscreen mode

Tip: You can create a storage account using az storage account create if needed.

4) Deploy your function to Azure:

   func azure functionapp publish MyHttpFunction
Enter fullscreen mode Exit fullscreen mode

After deployment, you'll get a URL like:

   https://myhttpfunction-dcgnazf2faa6back.canadacentral-01.azurewebsites.net/api/HttpExample?code=<FUNCTION_KEY>
Enter fullscreen mode Exit fullscreen mode

Test it with:

   curl "https://myhttpfunction-dcgnazf2faa6back.canadacentral-01.azurewebsites.net/api/HttpExample?name=DEVTo&code=<FUNCTION_KEY>"
Enter fullscreen mode Exit fullscreen mode

Step 4.2: Deploy to Azure (Optional 1: Azure Portal)

1) Go to Azure Portal.
2) Search for Function App and create one.

3) Navigate to the new create function MyHttpFunction.

3) Go to the Configuration and set SCM Basic Auth Publishing Credentials "ON".

4) Go back to Overview and click "Get publish profile" to download profile.

5) Publish your app via Visual Studio by "Import Profile".

6) Click "Publish".

7) You could find your site in profile, and test it with your app keys.


(⚠️⚠️⚠️ DON'T show your keys to others ⚠️⚠️⚠️)

Optional: Use a Timer Trigger

Want to schedule your function to run periodically? Use a Timer Trigger:

1) Create a new Timer-triggered function:

   func new --name TimerExample --template "Timer trigger"
Enter fullscreen mode Exit fullscreen mode

2) Modify the TimerExample.cs file:

   [FunctionName("TimerExample")]
   public static void Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, ILogger log)
   {
       log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
   }
Enter fullscreen mode Exit fullscreen mode

This function runs every 5 minutes based on the provided CRON expression.

Other Common Triggers

Azure Functions supports a variety of triggers beyond HTTP and Timer. Some examples include:

Trigger Type Description
HTTP Trigger Respond to web requests.
Timer Trigger Run on a schedule.
Blob Trigger Execute when a blob is uploaded to Azure Storage.
Queue Trigger Process messages in a queue.
Event Hub Trigger Respond to events published to an Event Hub.

Want More Use Cases?

Here are some advanced use cases to explore:

  • A Queue-triggered function to process queued messages.
  • A Blob-triggered function to analyze uploaded files.
  • A Durable Function for orchestrating long-running workflows.
  • A Query function to interact with a database or external APIs.

Conclusion

Azure Functions provides a flexible, scalable, and cost-efficient way to build event-driven applications. Whether responding to HTTP requests, processing storage events, or running scheduled tasks, Azure Functions can handle it all with ease.

Now that you've built and deployed your first Azure Function, explore the many possibilities it offers to take your applications to the next level!

References

  1. Azure Functions
  2. Resolving Unauthorized Error When Deploying an #Azure Function via #ZipDeploy

Love C# & Azure

Top comments (0)