Reader small image

You're reading from  Azure Serverless Computing Cookbook. - Third Edition

Product typeBook
Published inJun 2020
PublisherPackt
ISBN-139781800206601
Edition3rd Edition
Concepts
Right arrow
Author (1)
Praveen Kumar Sreeram
Praveen Kumar Sreeram
author image
Praveen Kumar Sreeram

Praveen Kumar Sreeram is an author, Microsoft Certified Trainer, and certified Azure Solutions Architect. He has over 15 years of experience in the field of development, analysis, design, and the delivery of applications of various technologies. His projects range from custom web development using ASP.NET and MVC to building mobile apps using the cross-platform Xamarin technology for domains such as insurance, telecom, and wireless expense management. He has been given the Most Valuable Professional award twice by one of the leading social community websites, CSharpCorner, for his contributions to the Microsoft Azure community through his articles. Praveen is highly focused on learning about technology, and blogs about his learning regularly. You can also follow him on Twitter at @PrawinSreeram. Currently, his focus is on analyzing business problems and providing technical solutions for various projects related to Microsoft Azure and .NET Core.
Read more about Praveen Kumar Sreeram

Right arrow

Building a back-end web API using HTTP triggers

In this recipe, we'll use Azure's serverless architecture to build a web API using HTTP triggers. These HTTP triggers could be consumed by any front-end application that is capable of making HTTP calls.

Getting ready

Let's start our journey of understanding Azure serverless computing using Azure Functions by creating a basic back-end web API that responds to HTTP requests:

How to do it…

Perform the following steps to build a web API using HTTP triggers:

  1. Navigate to the Function App listing page by clicking on the Function Apps menu, which is available on the left-hand side.
  2. Create a new function by clicking on the + icon:
    Adding a new function
    Figure 1.2: Adding a new function
  3. You'll see the Azure Functions for .NET - getting started page, which prompts you to choose the type of tools based on your preference. For the initial few chapters, we'll use the In-portal option, which can quickly create Azure Functions right from the portal without making use of any tools. However, in the coming chapters, we'll make use of Visual Studio and Azure Functions Core Tools to create these functions:
    The Azure portal enables you to choose the development environment. Choose In-Portal to develop from within the Azure portal

    Figure 1.3: Choosing the development environment
  4. In the next step, select More templates… and click on Finish and view templates, as shown in Figure 1.4:
    Choosing More templates… and clicking Finish to view templates
    Figure 1.4: Choosing More templates… and clicking Finish and view templates
  5. In the Choose a template below or go to the quickstart section, choose HTTP trigger to create a new HTTP trigger function:
    Choosing the HTTP Trigger template to create a new function
    Figure 1.5: The HTTP trigger template
  6. Provide a meaningful name. For this example, I have used RegisterUser as the name of the Azure function.
  7. In the Authorization level drop-down menu, choose the Anonymous option. You'll learn more about all the authorization levels in Chapter 9, Configuring security for Azure Functions:
    Selecting the Anonymous option in the Authorization Level
    Figure 1.6: Selecting the authorization level
  8. Click on the Create button to create the HTTP trigger function.
  9. Along with the function, all the required code and configuration files will be created automatically and the run.csx file with editable code will get opened. Remove the default code and replace it with the following code. In the following example, we'll add two parameters (firstname and lastname), which will be displayed in the output as a result of triggering the HTTP trigger:
    #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)
    #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 firstname=null,lastname = null; 
        string requestBody = await new 
        StreamReader(req.Body).ReadToEndAsync();
        dynamic inputJson = JsonConvert.DeserializeObject(requestBody); 
        firstname =    firstname ?? inputJson?.firstname;
        lastname = inputJson?.lastname;
        return (lastname + firstname) != null
        ? (ActionResult)new OkObjectResult($"Hello, {firstname + " " + lastname}")
        : new BadRequestObjectResult("Please pass a name on the query" + "string or in the request body");
    }
  10. Save the changes by clicking on the Save button available just above the code editor.
  11. Let's try testing the RegisterUser function using the test console. Click on the Test tab to open the test console:
    Testing the HTTP Trigger
    Figure 1.7: Testing the HTTP trigger
  12. Enter the values for firstname and lastname in the Request body section:
    Testing the HTTP Trigger with input data
    Figure 1.8: Testing the HTTP trigger with input data
  13. Make sure that you select POST in the HTTP method drop-down box.
  14. After reviewing the input parameters, click on the Run button available at the bottom of the test console:
    HTTP Trigger execution and output
    Figure 1.9: HTTP trigger execution and output
  15. If the input request workload is passed correctly with all the required parameters, you'll see Status: 200 OK, and the output in the output window will be as shown in Figure 1.9.
  16. Let's discuss how it works next.

How it works…

You have created your first Azure function using HTTP triggers and have made a few modifications to the default code. The code accepts the firstname and lastname parameters and prints the name of the end user with a Hello {firstname} {lastname} message as a response. You also learned how to test the HTTP trigger function right from the Azure Management portal.

Note

For the sake of simplicity, validation of the input parameters is not executed in this exercise. Be sure to validate all input parameters in applications running in a production environment.

See also

  • The Enabling authorization for function apps recipe in Chapter 9, Configuring security for Azure Functions.

In the next recipe, you'll learn about persisting employee details.

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Azure Serverless Computing Cookbook. - Third Edition
Published in: Jun 2020Publisher: PacktISBN-13: 9781800206601

Author (1)

author image
Praveen Kumar Sreeram

Praveen Kumar Sreeram is an author, Microsoft Certified Trainer, and certified Azure Solutions Architect. He has over 15 years of experience in the field of development, analysis, design, and the delivery of applications of various technologies. His projects range from custom web development using ASP.NET and MVC to building mobile apps using the cross-platform Xamarin technology for domains such as insurance, telecom, and wireless expense management. He has been given the Most Valuable Professional award twice by one of the leading social community websites, CSharpCorner, for his contributions to the Microsoft Azure community through his articles. Praveen is highly focused on learning about technology, and blogs about his learning regularly. You can also follow him on Twitter at @PrawinSreeram. Currently, his focus is on analyzing business problems and providing technical solutions for various projects related to Microsoft Azure and .NET Core.
Read more about Praveen Kumar Sreeram