This Azure tutorial will discuss an Azure functions rest api example c#.
Suppose you need 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 Azure Functions. We need to create multiple functions and then map them based on the operations like GET, POST, DELETE, etc
Table of Contents
Azure Functions Rest API Example C#
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 following 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 the 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.
Creating a REST API with Azure Functions using Visual Studio 2019
Assuming you have installed Visual Studio 2019 with the Azure development workload, let’s start the development activity. First, we will create the Azure Function Project using Visual Studio 2019.
Open Visual Studio 2019

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

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

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.

As we all know, a trigger is essential for an Azure Function. In this step, we need to select the trigger for our Azure Function. Select the HTTP trigger option on the window below, and choose the Storage Account (AzureWebJobsStorage) option as Storage Emulator. Then, select Anonymous as the Authorization level, and click the Create button.

The project was created successfully.

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, which includes four 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; }
}
The next class is named CreateProduct, and that contains one property, ProductDescription, as shown below
public class CreateProduct
{
public string ProductDescription { get; set; }
}
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; }
}
Creating Product Method
Now, we have created all the Model class definitions above. Now is the time to develop all the necessary methods for each functionality. The idea is to create all the functions inside the Function1.cs class file. We will delete the default function code and replace it with our own function.
The first function is the CreateProduct, which contains the lines of code below.
If we try to understand this function, the First thing is that we are using the ILogger interface to log a message, i.e., “Creating a new Product Item”. Next, we read the body of the HTTP request into a string and, with the help of Newtonsoft.Json, deserialize it into an object of our CreateProduct class.
Next, 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

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 GetAllProducts method below here

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 in this case. 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 use the OkObjectResult with the Product Item in the body, and we will receive a response code of 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

The Update Product Method
Below is the UpdateProduct method. We have used the HTTP PUT method in this case. This method updates the existing product item with the specified ID.
If you examine this function closely, you’ll see that we’re checking to see if the product item you want to update exists. If it doesn’t, it will return an HTTP 404 error. 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

The Delete Product Method
The deleteProduct method will delete the existing Product based on its ID. We are using the HTTP DELETE method. Inside the method, if the product is not found, it will return an HTTP 404 Not Found Result. If the product is available, I will remove it 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

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}
Let’s use the Postman tool to verify that all Azure functions are working. As you can see below, the GetAllProducts method returns an empty array, which is the expected output with the proper response code of 200 OK. There are no items currently present in the lists.
GetAllProducts: [GET] http://localhost:7071/api/products

Now, if you examine the CreateProduct method, we have verified it using the Postman tool, and you can see that the item is added successfully. We are providing the input as shown below in JSON format, and we received 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}

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. As you can see, we obtained the expected output.
UpdateProduct: [PUT] http://localhost:7071/api/product/{id}
UpdateProduct: [PUT] http://localhost:7071/api/product/f1ed4a8341434e51a55ad6968a31ae5c
{
“ProductDescription”: “Cool Product”,
“IsSoldOut” : “true”
}

Now, we will check the GetProductById using the Postman app. As you can see, we obtained the expected output below.
GetProductById: [GET] http://localhost:7071/api/products/{id}

We will now test the DeleteProduct method using the Postman app to verify its functionality. The product was successfully deleted, and we received a response code of 200 OK.
DeleteProduct: [DELETE] http://localhost:7071/api/product/{id}

Creating the API With Azure Functions Using the Azure Portal
To create the API, follow the steps below.
- Log in to the Azure Portal (https://portal.azure.com/)
- Once youhave logged in to the Azure Portal successfully, click on the + Create a resource

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

4. On the API Management service window, provide the following 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 haven’t created one yet, 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: Please provide the Administrator’s 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.

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

If you want to go to the API that you have created above, then follow the steps below
Log in to the Azure Portal and search for API Management services. Then click on the search result API Management services.

Now you can view the API you created on the API Management Services page, as shown below.

Import and publish the API in the 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.

Now, on the Create from OpenAPI specification page. Select the Full option and provide the details below
OpenAPI specification: Provide the URL that helps the API management 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.


Check out how to call an external API from an Azure function c#
Wrapping Up
In this article, we discussed Azure functions rest api example C#. I hope you enjoyed this article !!!!
You may also like the following articles
I am Bijay, a Microsoft MVP (10 times) having more than 17 years of experience in the software industry. During my IT career, I got a chance to share my expertise in SharePoint and Microsoft Azure, like Azure VM, Azure Active Directory, Azure PowerShell, etc. I hope you will learn from these Azure tutorials. Read more
