Assuming that you are already aware of the concept of serverless computing and have some basic understanding of Azure Functions.

As the name suggests Azure Function HTTP Trigger can be invoked using the HTTP request and send the response back accordingly.

Types of Triggers in Microsoft Azure Function

Azure functions are event-based triggered so in order to execute them we need to have some kind of trigger defined. Here you go the list of triggers supported by the Microsoft Azure function.

In today’s post, we will be focusing mainly on HTTP Trigger binding and will try to explore as much as information we can grab regarding this binding.

Create HTTP Trigger Azure Function using Visual Studio Code

Visual Studio comes with inbuilt templates to generate the HTTP triggered-based azure function.

Select Azure Function Template
Select Azure Function Template

Select Azure Function template and Click Next.

Project name and directory information on visual studio
Project name and directory information on visual studio

Provide the project name and directory information and click on Create project. The next screen will list down all the supported binding types on the azure function.

How to Create HTTP Trigger Azure Function With Diffrent Authorization Level | 2022 1
Select binding types in the azure function

Select the listed options to continue with our demo project.

  • .Net Core 3 as Framework
  • HTTP Trigger as azure function binding
  • Authorization level as a function
  • Storage Emulator as the storage account

Before we continue with our project, lets understand these options in detail.

Storage Emulator in Http trigger azure function

Azure function required storage to keep the required information while executing each request and maintaining the states and number of instances as required, also to distribute the workload and log the information.

Microsoft Storage Emulator is an open-source tool to provide the runtime requirement for azure functions. So, you don’t have to connect to the actual storage account and bear the cost of azure infrastructure.

Azure Function Authorization Level

As per the enum provided in the .Net Framework. There are four types of azure function authorization levels supported in HTTP-triggered azure functions. Let’s discuss each one in detail.

Anonymous

Anonymous means no authentication is required.  Any valid HTTP request passes.

User

User-level authorization is required when you want to invoke the function using an authentication token.

If the request does not contain a valid authentication token, the request will be denied even if it has a valid host key or master key.

Function

Function level authorization is the easiest way to perform the authorization, it just requires the function key generated while hosting the azure function on the portal.

Two types of keys will be generated while hosting function on the Azure portal.

  • Host Key
  • Master Key

A key can be passed to an Azure Function HTTP request in the URL as the code query string.  Alternatively, it can be included in the x-functions-key HTTP header.  Only the key value, not its name, is passed.

Function authorization level requires a key for authorization.  Both the function and host key will work. In that sense, it is a less restrictive key-based authorization level.

System

The system authorization level requires the master key of a function app for authorization.

Passing a function key or a host key will fail authorization and return an HTTP 401 – Unauthorized error code.

Admin

Admin authorization level requires a host key for authorization.

Passing a function key will fail authorization and return an HTTP 401 – Unauthorized error code.

Let’s continue with our demo project

Since the trigger point for the azure function is an HTTP request, there is a need of authorizing it before it starts executing the actual logic implemented under the azure function.

We can navigate to the Authorization enum to find all supported types of authorization.

Authorization level enum in Http Triggered Azure Function
Azure Function Authorization level enum in Http Triggered
Authorization level enum
Authorization level enum
Project structure in visual studio for azure function
Project structure in visual studio for azure function

Once done with the project creation. The structure will look like the above image. There are important files that we need to discuss in detail.

  • host.json
  • local.settings.json

host.json vs local.settings.json file in Azure function

host.json and local.setting.json both files are used for storing the configuration for azure function.

The key difference between these files is that host.json is used by azure functions hosted under the azure portal, on the other hand, local.settings.json is used to keep the configuration of the local environment or while running on a local machine.

Function1 as Http Trigged function

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace HttpTriggered.Demo
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] 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);
        }
    }
}

So, We have Function1 as Http Triggered Azure function. Which is configured to allow get and post requests and authorization at the function level.

Also, Function1 has HttpRequest as one of the parameters which will be null in case of getting a request and will have the request body if requested using the post method.

Dependency of ILogger will be resolved automatically, we don’t have to configure anything additional.

But, the Route parameter is null by default. And, can be configured as per the requirements.

Update Route Parameter in the HTTP Triggered Azure Function

Assume, I want to call my function using these route images then we have to just update the route parameter and the complete URL will look like this.

Azure function endpoint
Azure function endpoint

As you can see in the above window /api prefix has been added by default. In case if we want to update that. That can be also done using the host.json file just open the file and paste these lines at the end.

  "extensions": {"http": {"routePrefix": "apiv2"}}

routePrefix you can change the name as per the naming convention you follow in your project. After updating the host.json, it should look like this.

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensions": {"http": {"routePrefix": "apiv2"}}
}

And the URL of the function must be changed with a custom route prefix.

Http Trigger Azure Function With Custom Route
Http Trigger Azure Function With Custom Route

Invoke Get Of Http Trigger Azure Function using Curl

Let’s execute the azure function get using the curl command in cmd. Pass the default parameter called name and lets wait for the response.

Invoke Http Trigger Azure Function using curl command
Invoke Http Trigger Azure Function using the curl command

Invoke Post Of Http Trigger Azure Function using Postman Client

I assume you have used the postman app API development. If not go ahead and start learning that. One of the best tools I have ever used for testing is the APIS.

Invoke Http Azure function post method using postman
Invoke Http Azure function post method using postman

As we see in the above image, we are passing json as the request body in the post method. Which will return the response in the string format.

This is one of the simple requests and responses you can have. However, it can be changed and extended based on the requirement of the individual.

Publish Azure Function to Azure Portal

Assuming we have the active Azure subscription. If not go through this article to create one with free credit.

In the left-side navigation bar, you will have an option to create a new resource.

Create Resource Option in Azure Portal
Create Resource Option in Azure Portal

Search for a function app to start creating the function.

Search function app for creating in Azure portal
Search function app for creating in Azure portal

Select the Function App and Click on Create to start creating the function app.

Function App Creation Required fields
Function App Creation Required fields

Provide the required field for creating a function app.

  • Resource group name, Create a new one if does not exist
  • Provide the function name, and keep changing the name until you find the one which is available.
  • Publish option as code, We are not using Docker as of now.
  • Runtime stack, in our demo we are using.Net.
  • Azure function version, for this demo it is 3.1
  • The region, Not all the regions are available if you are using the free subscription of azure.
  • Operating system, you can select anyone .net core is supported in Linux as well in windows environment.
  • In the final step, Click on Review and Create

It might take some time to deploy the function app. Once the app is ready go to the app and download the Publish profile template from the overview section.

Get Publish Profile from Azure function
Get Publish Profile from Azure function

Click on the GetPublish profile link and download the profile. Once you have the downloaded profile.

Go to the visual studio a right-click on the project you will an option from the context menu to publish the project.

Publish profile on azure function
Publish profile on azure function

Import the downloaded profile for publishing the azure function. Click on the Import profile option and select the imported file & Click Finish.

Publish using the Import Profile Option in Visual Studio
Publish using the Import Profile Option in Visual Studio
Select Imported profile for publishing the azure function
Select Imported profile for publishing the azure function

After completing these steps. You should have a screen like this.

How to Create HTTP Trigger Azure Function With Diffrent Authorization Level | 2022 2
Publish profile options

Once we are done with the above stage. It is just a matter of clicking the publish button and the function will be deployed to the Azure portal.

Lets start publishing the project and wait for it. If all goes well then you should receive the success notification else you will have some errors on the console log.

Publish Azure function using visual studio with success
Publish Azure function using visual studio with success

As we see on the screen publishing the azure function was successful. Now let’s go to the Azure portal and validate the same.

A hosted version of HTTP triggered the azure function
A hosted version of HTTP triggered the azure function

A function is up and running and should be able to take the request and send the response back.

One Function App can hold multiple azure functions inside it. So to get to our Http triggered function just navigate to the left side pan, there is an option called functions, which can tell you the exact URL and type of authentication accepted by the azure function.

Azure Functions inside the Function App
Azure Functions inside the Function App

Click on Function1 which is the HttpTriggered azure function. You will have detailed information about the azure function like URL, authentication, and monitors.

Detailed page of Azure Function
Detailed page of Azure Function

Invoke Function hosted on Azure

Http Triggered functions can be invoked easily by hitting the provided endpoint and passing the function key or host key as a query parameter in the URL.

How to find Http trigger azure function URL

Got to the azure function inside the function app and Click on the GetFunction URL button on top of the page.

Get Function URL of Http triggered azure function
Get Function URL of Http triggered azure function

ASA you click on the Get Function Url link. you will have an option to select the function key which will be appended after the function URL. And, Will be used for authentication purposes.

If you remember the initial stage of our azure function, we have selected the function as AuthorizationLevel. So we can invoke the function using either the host key or master key. Select the appropriate option in the Get Function Url dropdown and copy the URL.

https://httptriggerdemobeetechnical.azurewebsites.net/apiv2/images?code=rfHaDc0pBoTugnkGUWSIKAUVKTx5KO/KCaj7ZaeYHZZ0xHtd2m6kHQ==

I got the above URL to invoke the HTTP function.

Call Http Trigged Function Using HttpClient

Just copy the above URL on the browser and you should be able to see the response sent by the azure function.

Call Http triggered azure function get using a browser
Call Http triggered azure function get using a browser

As we see in the response. We got a successful response from the function.

We can use PostMan my favorite API testing tool to hit the azure function with a post request.

Post call using postman and HTTP triggered azure function
Post call using postman and HTTP triggered azure function

Conclusion

So far we have seen how easy is to create HTTP trigger azure function on the local environment using visual studio and how we can take them to the production environment in just one click.

We have covered the following topics in this article.

  • How to Create Http Trigger Function Locally
  • Diffrent types of authorization available for HTTP triggered function
  • Publish Azure function using visual studio and publish profile
  • Invoke Function using host and master key

What is Azure Publish Profile?

Import publish profile

A publish profile is a file that contains information and settings that Visual Studio uses to deploy applications and services to Azure.

Diffrent types of Azure Function Authorization Level?

AuthorizationLevel Azure Functions

Anonymous
User
Function
System
Admin

86 / 100