Azure Functions Rest API Example C#

How To Create API With Azure Functions

This Azure tutorial will discuss Azure functions rest api example c#.

Azure Functions Rest API Example C#

Suppose you have the requirement to create a REST API application. Then, you can 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 must be installed on your machine. If you don’t have Visual Studio 2019 installed on your machine, install the Visual Studio 2019 now.

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

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

Open the Visual Studio 2019

azure function rest api c#

Click the Create a new project button on the Get Started window.

call external api from azure function c#

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

azure function rest api

Please provide a name for your project, select the location where you want to save it and click Create in the Configure your new project window.

call rest api from azure function c#

As we all know, 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, then Choose Anonymous as the Authorization level and click the Create button.

azure function api example

Now, the Project was created successfully.

create api with azure functions

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: ID, ManufactureTime, ProductDescription, and 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 in azure

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

public class CreateProduct
    {
        public string ProductDescription { get; set; }
    }
rest api with azure functions

The third class is called UpdateProduct, containing ProductDescription and IsSoldOut. See below for the reference

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

        public bool IsSoldOut { get; set; }
    }
you are developing an azure function that calls external api

Creating Product Method

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

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

If we 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, With the help of Newtonsoft.Json, deserialize that into the object of our CreateProduct class.

Now, the next thing is to create a new Product Item and copy the deserialized product description from our HTTP request body into it. We are adding the Product list items to the static list we 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 below

create api in azure

The Get All Products Method

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

As you can see, the function is very simple. Our method name is GetAllProducts. We use the Get HTTP request and the ILogger interface to log the message “Getting All Products”. Then, we use the OkObjectResult to return 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

azure functions rest api example

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 a case where the product with the ID does not exist. In that case, it will show you the HTTP 404 message. If the product exists, we are using the OkObjectResult with the Product Item in the body, and we will get the response code 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 below

create api azure

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 look at this function closely, you’ll see we’re checking to see if the product item you want to update exists. If it doesn’t, it will return HTTP 404. Then, we’ll deserialize the product entity. As you can see, the users can update the fields 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 below

azure function as rest api

The Delete Product Method

The 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 see that 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 see the DeleteProduct method below

azure function call external api

Now, let us rebuild and run the Project. You can see that all the Azure Functions ran successfully.

        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}
azure function rest api

Let’s use the Postman tool to check if all the Azure functions work. As you can see below, the GetAllProducts method returns an empty array, the expected output with the proper response code 200 OK. There are no items present in the Lists currently.

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

how to create api in azure

Now, if you see the CreateProduct method, we have verified it using the Postman tool, and you can 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}

azure function web api

Now 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 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”

}

azure function call rest api

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

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

c# azure api

We will now check the DeleteProduct method using the Postman app to see if it works. The product got deleted, and we got the response code 200 OK.

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

function app api

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

How To Create API With Azure Functions Using Azure Portal

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

  1. Login to the Azure Portal (https://portal.azure.com/)
  2. 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

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

azure function call rest api

4. 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 now, click 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: You can choose the Developer (No SLA) for this option.

After providing all the above details, click the Create button to create the API.

you are developing an azure function that calls external api

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

azure functions rest api

Navigate to your API

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

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

azure function api

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

azure functions rest api

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 the Full option and provide the below details

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

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

azure functions api
How To Import And Publish The API In Azure Portal

Check out how to call external API from Azure function c#

You may also like following the below Articles

Wrapping Up

In this article, we discussed Azure functions rest api example c#. I hope you enjoyed this article !!!!