REST API with Azure function (serverless applications) – Part 1

Azure Functions is a serverless “Compute-on-demand” solution provided by Microsoft. Azure functions allow you to write a small code that can run on an Azure environment without worrying about infrastructure maintenance and saving you cost. Azure functions use trigger-based in a specific event. We will use a trigger event based on HTTP requests.

We will create a Rest API using C# in Visual studio 2019 and test API in the PostMan. You can use Visual studio code if you need to.

What do you need?

  1. Visual Studio 2019
  2. Azure account

What we will create:

  1. API to get the list of products
    • Get All Products (GetAllProducts)
  2. Test APIs via PostMan

So let’s start. Create a project in Visual Studio 2019, open a new project and search for Azure functions as shown in the image below.

Enter a project name “ProductRestAPI” and complete project configuration details as shown in the image below.

Select HTTP trigger and change Authorisation level to Anonymous as shown in the image below

Visual Studio automatically creates an Azure function named “Function1” with all the basic code. Your code should look like this.

[FunctionName("Function1")]
        public static async Task<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 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);
        }

Add Azure storage binding.

This step is not necessary, but if you want to add storage output binding to your API, add Microsoft.Azure.WebJobs.Extensions.Storage to your project using NuGet Package manager, as shown in the image below.

Add product model class.

Now add a model class, which has few properties, as shown in the code below. Create a new file named Product.cs at the root of your project and copy the below code.

using System;
using System.Collections.Generic;
using System.Text;

namespace ProductRestAPI
{
    public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public bool Published { get; set; }
        public bool Deleted { get; set; }
    }
}

Create GetAllProduct function

Now, let’s change the code in the file Function1.cs, which was created by visual studio. Change attribute name [FunctionName(“Function1”)] to [FunctionName(“GetAllProducts”)]. Change method name from run to GetAllProducts. This is the name that will appear when you access API via HTTP.

Replace the Run function with the code below in the file Function.cs.

[FunctionName("GetAllProducts")]
        public static async Task<IActionResult> GetAllProducts(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            var str = Environment.GetEnvironmentVariable("sqldb_connection");

            List<Product> listProduct = new List<Product>();
            try
            {
                using (SqlConnection con = new SqlConnection(str))
                {
                    con.Open();
                    var query = @"Select * from Products";
                    SqlCommand command = new SqlCommand(query, con);
                    var reader = await command.ExecuteReaderAsync();
                    while (reader.Read())
                    {
                        Product products = new Product()
                        {
                            ID = (int)reader["ID"],
                            Name = reader["Name"].ToString(),
                            Description = reader["Description"].ToString()
                        };
                        listProduct.Add(products);
                    }
                }
            
            }
            catch (Exception e)
            {
                log.LogError(e.ToString());
            }
            if (listProduct.Count > 0)
            {
                return new OkObjectResult(listProduct);
            }
            else
            {
                return new NotFoundResult();
            }
        }

Publish project to azure

  1. Right-click the project and select Publish and in Target, select Azure then Next.
  2. In specific target select “Azure Function App (Windows)” and select Next
  3. In the Function instance options. and click on + button to add Azure function as shown in the image below.

4. This will open another window. Please fill in the information Name, Subscription name, resource group, Location. Leave the rest of the information default, and in the next screen, click finish.

Connect Azure function to Azure SQL database

We need to get the connection string for the Azure SQL database. Login to Azure, select Azure database from the connection string under settings copy your connection string. Your connection string should look as shown below. Replace xxxxx with correct information.

Make sure that you add your local machine’s IP address in the Azure SQL database’s firewall setting. It is important to test API locally on PostMan.

Server=tcp:XXXXXXXXXX.database.windows.net,1433;Initial Catalog=xxxxxxx;Persist Security Info=False;User ID=xxxxxxx;Password=xxxxxxx@;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;

Setup connection string

It is always a good security best practice to store connection string and other confidential information in the azure function settings.

In Solution Explorer, right-click the function app project and select Publish. Under Hosting, click three dots (…) and select Manage Azure App Service Settings. In application settings, click Add setting. Enter New App Setting name “db_connection” and select ok. Enter your copied SQL connection string in the application setting “db_Connection“.

This will add a database connection string in the file named “local.settings.json”

You are all set and finally, enter publish as shown in the image below.

Test API locally using Postman.

You can run and test your API locally by using Postman. By default, Azure App functions run on port 7071. When you build and run your project, you will be able to see all APIs created in the function as shown in the image below

Post is a free API testing tool that makes testing any API very easy. Copy the URL “http://localhost:7071/api/GetAllProducts” shown in the image and run it in the postman. Here is the output as shown in the Postman.

Link to GitHub source code

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *