Up and running with Micorsoft Azure Functions HTTP Triggers v3

Hamza Jeljeli
10 min readDec 2, 2020

Hello there ! my name is Hamza Jeljeli, I’am a Microsoft Certified Trainer (MCT), Microsoft Certified Associate — Azure Developer & Microsoft Certified Associate — Azure Security Engineer. In this article, i will share with you a quick guide about building restful APIs using Azure Functions.

What is Azure Functions ?

Azure Functions is a serverless compute service available in the Microsoft Azure Cloud Platform that lets you run event-triggered code (Http triggers, Queue triggers, etc.) without having to provision or manage infrastructure.

In this article, we will be covering only Azure Functions HTTP Trigger.

Before we start …

Before we start, You will need to have Microsoft Visual Studio 2019 or higher (With Azure Developement component) installed. You will need also a Microsoft Azure subscription to deploy the App (if you don’t have a subscription, you can get a Visual Studio Dev Essentials subscription and activate $200 free credit to use them with Microsoft Azure.

If you are not familiar with Microsoft Azure Fundamental Concepts (Like Resource groups, Subscription, etc.) I invite you to read this article before proceeding.

1) Creating a new Azure Functions with HTTP Triggers Project

To create a new Azure Functions with HTTP Triggers Project, Open Visual Studio and Click on “Create a new project”.

From the Language’s drop box, Choose C# and From the Platform’s drop box, Choose Azure, click on Azure Functions and then click Next.

At this point, you need to choose a name for your project. In this example, we will go for FunctionAppDemo. When finished, click on Create.

At this point, we need to configure some parameters. First, we need to select Azure Functions v3 (.NET Core) from the version’s dropbox, Configure the Storage Account to None (since we will be not using any storage), set the Authorization Level to Anonymous and the most import thing, Choose Http trigger in the templates list.

Note : Further information about Authorization Levels can be found here.

When finished, Click on Create.

When Visual Studio loads the project, you must end up with a fresh Azure Functions Project with a sample Http Trigger function named Function1.

Notice Line 16, 17 and 18 :

[FunctionName("Function1")]public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,ILogger log)
  • FunctionName(“Function1”) : Which indicates the name of your Azure Function, This name, along with the C# Function name, must be unique.
  • “get”,”post” : Indicates that the function can accept GET and POST requests. you can also add other values such as “put”, “delete”, etc ..
  • Route = null : Indicates that the function doesn’t have a custom route associated to it. We will be talking about this later.

Now, let’s take a closer look at the code of the Azure Function :

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);
  • log.LogInformation() : This function will allow you to log information which can be visible later in the debugging console and/or Azure Log Analytics.
  • req.Query[“name”] : The program will attempt to read a parameter named name passed as GET parameter.
  • await new StreamReader(req.Body).ReadToEndAsync() : this function will allow you to read the body of the request as a String.
  • new OkObjectResult(responseMessage) : Will return an HTTP 200 response with a content passed in parameter.

2) Running the project

To run your Azure Functions project, go to the menu bar and click on Debug, then click on Start Debugging (F5) or you can click on the green play button .

Once the application has started, you will end up with a console that contains several debug informations regarding the execution of the Functions App.

Let’s try to perform few requests 😁

Results when performing GET requests using parameters and without using parameters
Results when performing POST requests using a body request and without using a body request
When performing each request, Logs are generated too !

To stop debugging, simply exit the logs window.

3) Deploying the Functions App

To perform this action, you must have an Azure Subscription as explained earlier.

To deploy the Azure Functions, from the Solution Explorer, right click on the Project Name and click on Publish.

In the Publish wizard, choose Azure as a Target and click on Next.

In the next screen, the wizard will allow you to deploy your application under Windows or Linux (App Containers is not the subject of our article today, but you can learn more about it here). Personally, I’ll go for Windows. Click on Next when you choosed your specific target.

Finally, the wizard will ask you to create your new Azure Function, to do this, please click on + Create a new Azure Function.

In the create Function App window, Choose the name of your Azure Function along with other details such as Plan Type and Location.

Please note that if you don’t have a Resource group and/or Azure Storage created, you can create them from this screen using the New… link.

When completed, please click on Create.

When the creation process is completed, Click on Finish.

Now, you will simply need to click on the Publish button.

4) Testing your published Function App

Now, to the fun part ! We will be watching in action our First Azure Function running 🎉🎉🎉 !

First, we need to browse to the Azure Portal and go to your Function App Resources and click on the name of the function that you have deployed earlier.

In my case, the name of the Function App which i deployed earlier is MyNewAzureFUnction.

When you click on Functions, You will see all the functions which are declared inside your project. Currently, we only have Function1 but we will add other ones later. Click on Function1.

In the Overview page, click on Get Function Url.

And voila ! To check the result, simply can copy/paste the Function URL to a new tab in your browser for example or use Postman !.

5) Adding new Functions

In this section we will be adding some new functions, Those functions are :

  • SayHello : Will Simply return Hello there ! as a static message.
  • SayHelloNamed : Will take a name variable as a GET Parameter (John for example) and return Hello name ! (Hello John ! for example).
  • Calculate : Will take two integer variables as GET parameters and returns their sum.
  • PostCalculate : Same as calculate, but the request will be performed as POST request.

So, let’s start 🤩 !

a) SayHello

To implement this function, copy/paste code below inside the main Azure Functions project class.

[FunctionName("SayHello")]public static async Task<IActionResult> SayHello([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, ILogger log){return new OkObjectResult("Hello there !");}

As shown earlier in this tutorial, This method will return a static text when called using http://localhost:7071/api/SayHello (Or it’s URI when published to Azure).

b) SayHelloNamed

To implement this function, copy/paste code below inside the main Azure Functions project class.

[FunctionName("SayHelloNamed")]public static async Task<IActionResult> SayHelloNamed([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "SayHello/{name}")] HttpRequest req, String name, ILogger log){return new OkObjectResult("Hello " + name + " !");}

Notice the Route = “SayHello/{name}” here and the String name function parameter, Azure Functions will map the {name} GET variable with the name parameter. As a result when you call, for example, http://localhost:7071/api/SayHello/John (Or it’s URI when published to Azure) you will receive Hello John ! as a response.

c) Calculate

To implement this function, copy/paste code below inside the main Azure Functions project class.

[FunctionName("Calculate")]public static async Task<IActionResult> Calculate([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "Add/{N1}/{N2}")] HttpRequest req, int N1, int N2, ILogger log){return new OkObjectResult("Result is : " + (N1 + N2));}

Notice the Route = “Add/{N1}/{N2}” here and int N1, int N2 parameters. Azure Functions will map the {N1} and {N2} GET variables with the N1 and N2 integer parameters. As a result when you call, for example, http://localhost:7071/api/Add/12/5 (Or it’s URI when published to Azure) you will receive Result is : 17 as a response.

d) PostCalculate

To implement this function, First create a class named PostCalculateBody then copy/paste code below inside the PostCalculateBody.cs file.

public class PostCalculateBody{[Required]public int Num1 { get; set; }[Required]public int Num2 { get; set; }public int calculate(){return this.Num1 + this.Num2;}}

Then, copy/paste code below inside the main Azure Functions project class.

[FunctionName("PostCalculate")]public static async Task<IActionResult> PostCalculate([HttpTrigger(AuthorizationLevel.Anonymous, "Post", Route = "Add")][RequestBodyType(typeof(PostCalculateBody), "PostCalculateBody")] HttpRequest req, ILogger log){using (var reader = new StreamReader(req.Body,encoding: Encoding.UTF8,detectEncodingFromByteOrderMarks: false)){String bodyString = await reader.ReadToEndAsync();PostCalculateBody postCalculateBody = JsonConvert.DeserializeObject<PostCalculateBody>(bodyString);return new OkObjectResult(postCalculateBody.calculate());}}

Well here, we have to understand few things before we proceed 😜 :

  • Route = “Add” : Indicates that the route to this function will be Add.
  • [RequestBodyType(typeof(PostCalculateBody), “PostCalculateBody”)] : Indicates that the Request Body type is PostCalculateBody. This attribute is useful when you will be adding Swagger to your Azure Functions Project.
  • using (var reader = new StreamReader(req.Body,encoding: Encoding.UTF8,detectEncodingFromByteOrderMarks: false)) : This line will initialize a StreamReader Object to allow us to read the body of the request. Notice also for the encoding, we are using UTF8. You can also use ASCII or Unicode too !
  • String bodyString = await reader.ReadToEndAsync() : This line will allow us to read the content of the request body and store it inside a string variable named bodyString.
  • PostCalculateBody postCalculateBody = JsonConvert.DeserializeObject<PostCalculateBody>(bodyString) : This line will Deserialize the bodyString to a new Object of type PostCalculateBody.

As a result when you call, for example, http://localhost:7071/api/Add (Or it’s URI when published to Azure) with the following body request :

{"num1": 12,"num2": 5}

You will receive 17 as a response.

6) Bonus : Adding Swagger to Azure Functions ? Is it even possible ?

Well .. Yes ! The implementation is a bit tricky but i’m here to help 😁 ! Such a thing can be done using AzureExtensions.Swashbuckle !

You are probably asking yourself now, what is Swagger 🤔 ? What can i use it for ? Well, Swagger is an Interface Description Language for describing RESTful APIs expressed using JSON. its is used ,along with a set of open-source software tools, to design, build, document, and use RESTful web services. You can learn more by visting https://swagger.io/ !

The implementation is not very complicated. you simply need to Install the AzureExtensions.Swashbuckle NuGet package to your Azure Functions Project using the Packet Manager CLI :

Package Manager : Install-Package AzureExtensions.Swashbuckle

Then, Add a startup class (named SwashBuckleStartup.cs in this example) to your Azure Functions project.

[assembly: WebJobsStartup(typeof(SwashBuckleStartup))]
namespace SomeAppNamespace
{
internal class SwashBuckleStartup : IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder)
{
//This line will register the SwashBuckle extension
builder.AddSwashBuckle(Assembly.GetExecutingAssembly());

}
}
}

When finished, return back to the main Azure Functions project class (MainFunctions.cs) and copy/paste the following code :

[SwaggerIgnore][FunctionName("Swagger")]public static async Task<HttpResponseMessage> Swagger([HttpTrigger(AuthorizationLevel.Function, "get", Route = "Swagger/json")] HttpRequestMessage req,[SwashBuckleClient] ISwashBuckleClient swashBuckleClient){return swashBuckleClient.CreateSwaggerDocumentResponse(req);}[SwaggerIgnore][FunctionName("SwaggerUi")]public static async Task<HttpResponseMessage> SwaggerUi([HttpTrigger(AuthorizationLevel.Function, "get", Route = "Swagger/ui")] HttpRequestMessage req,[SwashBuckleClient] ISwashBuckleClient swashBuckleClient){return swashBuckleClient.CreateSwaggerUIResponse(req, "swagger/json");}

The previous code will add to you two functions, one named Swagger which will generate a JSON Schema for your API, and the other is named SwaggerUi which will allow you to visualize and interact with the API’s resources.

To check if everything is all right, run the project and you must see the following functions listed.

And when you navigate to http://localhost:7071/api/Swagger/ui, You must end up with a result similar to this.

Final words …

  • In this article, we learned how we can Create, run and Host an Azure Functions to Microsoft Azure.
  • We learned how we can add routing to an Azure Function.
  • We learned how we can add Swagger to an Azure Functions project.
  • This project can be downloaded from GitHub !

--

--