How To Create API With Azure Functions

How To Create API With Azure Functions

In this Azure tutorial, we will discuss How To Create API With Azure Functions. Along with this, we will also discuss a few other topics like How to Create a REST API with Azure Functions using Visual Studio 2019, Azure Function REST API C#, How To Create API With Azure Functions Using Azure Portal and we also discussed Azure Function Call External API.

How To Create API With Azure Functions? To create the API with the Azure Function we will do the following stuffs

  • Built Azure Function Project in Visual Studio 2019
  • Creating the needed Model Classes
  • Create Product method
  • Create Get All Product method
  • Create Get Product By Id method
  • Create the Update Product method
  • Create the Delete Product method
  • Test The API

How To Create API With Azure Functions

If you have the requirement to create a REST API application. Then you can able to create a simple REST API application using the Azure Function. It is really easy to do with the help of the Azure Functions. We need to create multiple functions and then map them based on the operations like GET, POST, DELETE, etc

Here, as part of the development activities, we will create the Azure Function App project with the latest IDE i.e Visual Studio 2019. We will deal with a Product list by implementing the REST API operation.

We will do the below operations with REST API implementation as part of our development activities

  • Get all Products (GET api/Product)
  • Get Product By ID(GET api/product/{id})
  • Create a new Product(POST api/product)
  • Update a Product(PUT api/product/{id})
  • Delete a Product(DELETE api/product/{id})

Prerequisites

  • Visual Studio 2019 with Azure development workload needs to be installed in your machine. If you don’t have Visual Studio 2019 installed in your machine then install the Visual Studio 2019 now.

How to Create a REST API with Azure Functions using Visual Studio 2019

Now assuming you have installed the Visual Studio 2019 with Azure development workload, now let’s start the development activity. First, we will create the Azure Function Project using Visual Studio 2019.

Open the Visual Studio 2019

How To Create API With Azure Function

Now, On the Get started window, click on the Create a new project button.

Create REST API With Azure Functions

The next step is to select the template for the Project so for that, search for the Azure Functions template and choose the Azure Functions from the search result and then click on the Next button.


Creating simple CRUD REST-style APIs with Azure Functions C# Bindings

Provide the name for your project and then Choose the Location where you want to save your project and then click on the Create button on the Configure your new project window.

Creating A REST API With Azure Functions

As we all know that a trigger is a must for the Azure Function. So in this step, we need to choose the trigger for our Azure Function. Select the HTTP trigger option on the below window, Storage Account(AzureWebJobsStorage) option as Storage Emulator, and then Choose Anonymous as the Authorization level and then click on the Create button.

Build a Basic REST API  with Azure Functions

Now the Project created successfully.

How to Build a Basic REST API with Azure Functions

Azure Function REST API C#

Create Model Class

Now the next step is to create the Model Class. So I have created a model class named Product.cs. It contains 3 class definitions. One is the Product class that contains 4 properties that are ID, ManufactureTime, ProductDescription, IsSoldOut.


Public class Product
    {
        public string Id { get; set; } = Guid.NewGuid().ToString("n");
        public DateTime ManufactureTime { get; set; } = DateTime.UtcNow;
        public string ProductDescription { get; set; }
        public bool IsSoldOut { get; set; }
    
    }
Create REST API With Azure Functions

The next class is named CreateProduct and that contains one property ProductDescription as shown below

public class CreateProduct
    {
        public string ProductDescription { get; set; }
    }
How To Create API With Azure Functions

The third class is known as UpdateProduct and it contains ProductDescription and IsSoldOut. See below for the reference

 public class UpdateProduct
    {
        public string ProductDescription { get; set; }

        public bool IsSoldOut { get; set; }
    }
Create API With Azure Functions

Creating Product Method

Now we have created all the Model class definitions above. Now the time to create all the methods needed for all the functionalities. Now the idea is to create all the functions inside the Function1.cs class file. Now we will delete the default function code and will write our own function there.

The first function is the CreateProduct that contains the below lines of code.

If we will try to understand this function, the First thing is we are using the ILogger interface to log a message i.e “Creating a new Product Item”. Now we are reading the body of the HTTP request into a string and By the help of the Newtonsoft.Json to deserialize that into the object of our CreateProduct class.

Now the next thing is we are creating a new Product Item and we are copying the deserialized product description from our HTTP request body into it. We are adding the Product list items into the static list that we have created on the first line.

public static class Function1
    {
        public static readonly List<Product> productitems = new List<Product>();

        [FunctionName("CreateProduct")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
        {
            log.LogInformation("Creating a new Product Item.");

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var input = JsonConvert.DeserializeObject<CreateProduct>(requestBody);

            var product = new Product() { ProductDescription = input.ProductDescription };
            productitems.Add(product);
            return new OkObjectResult(product);
        }
    }

You can see the CreateProduct method as below

How To Create API With Azure Functions using Visual Studio 2019

The Get All Products Method

You can able to retrieve all the Products using this Azure Function. Below is the code for the GetAllProducts method.

If you can see the function is very simple. Our method name is GetAllProducts. We are using here, Get HTTP request and we are using the ILogger interface to log the message “Getting All Products”. Then we are using the OkObjectResult that actually returns the entire contents of our Product list as a JSON array. 

    [FunctionName("GetAllProducts")]
    public static IActionResult GetAllProducts(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "product")]
    HttpRequest req, ILogger log)
        {
            log.LogInformation("Getting All Products");
            return new OkObjectResult(productitems);
        }

You can also see the below GetAllProducts method here

Create REST API With Azure Functions using Visual Studio 2019

The Get Product By Id Method

GetProductById is the name of my function here. We will get the Product by the Id. We are using the HTTP Get method here. There might be the case the product with the Id does not exist, in that case, it will show you the HTTP 404 message. If the product exists then we are using the OkObjectResult with the Product Item in the body and we will get the response code as 200 OK.

Below is the code for my GetProductById method.

public static IActionResult GetProductById(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "products/{id}")]HttpRequest req,
ILogger log, string id)
        {
            var product = productitems.FirstOrDefault(p => p.Id == id);
            if (product == null)
            {
                return new NotFoundResult();
            }
            return new OkObjectResult(product);
        }

You can see the method as below

How to Create a REST API with Azure Functions and the Serverless Framework

The Update Product Method

Below is the UpdateProduct method. We have used the HTTP put method here. This method will update the existing product item with Id.

If you will see this function closely, We are checking if the product item you want to update actually exists. If the product Item doesn’t exist, it will return HTTP 404. Then we are actually deserializing the Product entity. If you can see the users are allowed to update the two fields that are IsSoldOut and ProductDescription.

[FunctionName("UpdateProduct")]
    public static async Task<IActionResult> UpdateProduct(
    [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = "product/{id}")]HttpRequest req,
ILogger log, string id)
        {
            var product = productitems.FirstOrDefault(p => p.Id == id);
            if (product == null)
            {
                return new NotFoundResult();
            }

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var updatedproduct = JsonConvert.DeserializeObject<UpdateProduct>(requestBody);

            product.IsSoldOut = updatedproduct.IsSoldOut;
            if (!string.IsNullOrEmpty(updatedproduct.ProductDescription))
            {
                product.ProductDescription = updatedproduct.ProductDescription;
            }

            return new OkObjectResult(product);
        }

You can see the UpdateProduct method as below

How to Create a REST API with Azure Functions using Visual Studio 2019

The Delete Product Method

DeleteProduct method will delete the existing Product based on the Id of the Product. We are using the HTTP DELETE method. Inside the method, if you will see if the product is not there then it will return HTTP 404 Not Found Result. If the product is available then I am removing that from the Product item list.

Below is the Code for the DeleteProduct Method.

[FunctionName("DeleteProduct")]
    public static IActionResult DeleteProduct(
    [HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "product/{id}")]HttpRequest req,
ILogger log, string id)
        {
            var product = productitems.FirstOrDefault(p => p.Id == id);
            if (product == null)
            {
                return new NotFoundResult();
            }
            productitems.Remove(product);
            return new OkResult();
        }

You can able to see the DeleteProduct method as below

azure functions rest api example c#

Now lets rebuild and run the Project. You can able to see the all the Azure Functions ran sucessfully.

        CreateProduct: [POST] http://localhost:7071/api/product

        DeleteProduct: [DELETE] http://localhost:7071/api/product/{id}

        GetAllProducts: [GET] http://localhost:7071/api/products

        GetProductById: [GET] http://localhost:7071/api/products/{id}

        UpdateProduct: [PUT] http://localhost:7071/api/product/{id}
Customize an HTTP endpoint in Azure Functions

Now let’s check if all the Azure functions are working fine using the Postman tool. If you can see below that the method GetAllProducts method returns an empty array and it is the expected output with the proper response code 200 OK. because till now there are no items present in the Lists as of now.

GetAllProducts: [GET] http://localhost:7071/api/products

how to create api with azure functions using visual studio

Now, If you will see the CreateProduct method, we have verified the CreateProduct method using the Postman tool and you can able to see the Item added successfully. We are providing the input as below in the JSON format and we got the expected output.

{

“ProductDescription”: “Cool Product”

}

CreateProduct: [POST] http://localhost:7071/api/product

We got the output as follows

{“id”:”f1ed4a8341434e51a55ad6968a31ae5c”,”manufactureTime”:”2020-08-26T14:18:15.9519097Z”,”productDescription”:”Cool Product”,”isSoldOut”:false}

how to create api with azure functions Visual Studio 2019

Now to check the UpdateProduct method. we can use the above product id. Now let’s make the “IsSoldOut” : “true”. Now let’s test this with the Postman app. You can able to see we got the expected output.

UpdateProduct: [PUT] http://localhost:7071/api/product/{id}

UpdateProduct: [PUT] http://localhost:7071/api/product/f1ed4a8341434e51a55ad6968a31ae5c

{

“ProductDescription”: “Cool Product”,

“IsSoldOut” : “true”

}

how to create api with azure function visual studio 2019 step by step

Now we will check the GetProductById using the Postman app. You can able to see we got the below expected output.

GetProductById: [GET] http://localhost:7071/api/products/{id}

how to create api with azure function using visual studio 2019

Now we will check the DeleteProduct method using the Postman app if it is working fine. You can able to see the product got deleted and we got the response code as 200 Ok.

DeleteProduct: [DELETE] http://localhost:7071/api/product/{id}

how to create REST api with azure function using visual studio 2019

This is How you can Build a Basic REST API Quickly with Azure Functions.

How To Create API With Azure Functions Using Azure Portal

Well, here we will discuss How to create API with Azure Functions using the Azure Portal. To create the API, follow the below steps.

Login to the Azure Portal (https://portal.azure.com/)

Once you logged in to the Azure Portal successfully, click on the + Create a resource

How To Create API With Azure Functions Using Azure Portal

Now click on the Integration link and then click on the API Management.

How To Create API With Azure Functions in Azure Portal

On the API Management service window, provide the below details

  • Name: Provide a valid name for the API
  • Subscription: Choose your valid Azure subscription.
  • Resource group: Choose an existing Resource Group or if you don’t have the Resource Group created till now, then click on the Create new link to create a new Resource Group.
  • Location: Choose a location for your API.
  • Organization Name: Provide your Organization name.
  • Administrator email: Provide the Administrator email ID for the Administrator activity.
  • Pricing Tier: For this option, you can choose the Developer (No SLA).

Now after providing all the above details, click on the Create button to create the API.

Create API With Azure Functions Using Azure Portal

Now it’s deployed successfully, You can see below the HelloAPI that you have created.

Navigate to your API in Azure Portal

Navigate to your API

If you want to go to your API that you have created above, then follow the below steps

Log in to the Azure Portal and Search for the API Management services. Then click on the Search result API Management services.

Find your API in Azure Portal

Now you can able to see the API you have created on the API Management Services page like below.

Navigate to your API in Azure Portal

How To Import And Publish The API In Azure Portal

So Above, we have created our Hello API. Now click on that and on the API page, Click on the APIs link from the left navigation and then select the OpenAPI tile as highlighted below.

How To Import And Publish The API

Now on the Create from OpenAPI specification page. select Full option and provides the below details

OpenAPI specification: Provide the URL that helps the API management to forward requests to this address

Provide the Display name, Name, Choose the URL scheme as HTTPS and select the other options as highlighted and then click on the Create button.

Import And Publish The API In Azure Portal
How To Import And Publish The API In Azure Portal

Azure Function Call External API

Above we discussed How To Create REST API With Azure Functions. Here we will discuss How to call the External API from the Azure Function.

I will show this with the help of an example. If you will see the below example I have an external API named WaveProductAPI. There I am validating if the WaveProductID provided is valid or not and returning the response True or False.

using System;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net;


namespace ExternalAPICall
{
    public static class WaveProductAPIFunctionClass
    {
        [FunctionName("WaveProductAPIFunction")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, ILogger log)
        {
            log.LogInformation("Calling my External API");


            try
            {

                var mycontent = req.Content;
                string jsonContent = mycontent.ReadAsStringAsync().Result;
                dynamic actualparm = JsonConvert.DeserializeObject<WaveProductModel>(jsonContent);


                if (string.IsNullOrEmpty(actualparm.WaveProductID))
                {
                    return req.CreateResponse(HttpStatusCode.OK, "Please enter a valid Wave Product Id!");
                }
           
                HttpClient client = new HttpClient();
                HttpRequestMessage myRequest = new HttpRequestMessage(HttpMethod.Get, string.Format("YourWaveProductAPIURL?waveproductId={0}", actualparm.WaveProductID));

               
                HttpResponseMessage httpresponse = await client.SendAsync(myRequest);
                bool isValidWaveProduct = await httpresponse.Content.ReadAsAsync<bool>();


              
                return req.CreateResponse(HttpStatusCode.OK, new WaveProductResponseModel { isValidWaveProductID = isValidWaveProduct });
            }
            catch (Exception ex)
            {

                return req.CreateResponse(HttpStatusCode.OK, "Wave API product ID is not valid !!! Reason: {0}", string.Format(ex.Message));
            }
        }
    }


    public class WaveProductModel
    {
        public string WaveProductID { get; set; }
    }


    public class WaveProductResponseModel
    {
        public bool isValidWaveProductID { get; set; }
    }
    
}

This is what the format for the WaveProductAPI is like below

{
    "WaveProductID": "abc346"
}

Azure Functions c#

Azure Functions is simply called as “Functions-as-a-service” that provides the solution to run some lines of code or known as functions in the cloud environment. No need to take any headache for the whole application or the infrastructure. You just need to bother about writing the code.

You can create the Azure functions using C# with different IDE like Visual Studio, Visual Studio Code.

So now, Create the Azure Functions using C# in Visual Studio 2019, and also you can create the Azure Functions using C# in Visual Studio Code.

You may also like following the below Articles

Wrapping Up

Well, in this article, we discussed How To Create API With Azure Functions, How to Create a REST API with Azure Functions using Visual Studio 2019, Azure Function REST API C#, How To Create API With Azure Functions Using Azure Portal, How To Import And Publish The API In Azure Portal and we also discussed Azure Function Call External API and Azure Functions c#. Hope you enjoyed this article !!!!

Leave a Comment