Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Function as a Web API performance and pricing

We are planning to build a web application, and I was hoping someone could help us to decide whether to use Azure App Service or Azure Function for providing rest API to the client side. Our requirements are as follows.

  1. Authentication and authorization
  2. CRUD on Azure SQL and Cosmos DB
  3. Multi region
  4. 100,000,000 API calls per month

At first, we were going to build the backend using Azure App Service. But after studying pros and cons on Azure Functions, Azure Functions became more appealing to us.

So is it even a good idea to build a web application that depends on Azure Functions as a REST API provider?

Does anyone have an experience building, managing and scaling up and out Azure Functions as a REST API provider?

like image 561
jong shin Avatar asked Jun 07 '19 15:06

jong shin


People also ask

Are Azure functions cost effective?

Azure charges for bandwidth on a sliding scale. The more you use, the cheaper it gets. You get the first 5 GB free. Then it costs 8.7 cents per GB of bandwidth for 5GB - 10TB.

Can Azure functions replace Web API?

Conclusion. Migrating from a simple web API that has little commercial pressure to Azure Function can save significant development and operational costs. By using the serverless platform, we can focus on the business logic itself rather than the infrastructure code.

Can Azure function used as API?

Use Visual Studio Code and Azure Functions to rapidly create a serverless API, implement a RESTful architecture and safely store secure information like connection strings.

Is Azure function fast?

Azure Function execution speed is extremely slow and inconsistent.


1 Answers

Is it even a good idea to build a web application that depends on Azure Functions as a REST API provider?

It seems you are planning to have REST API using Web Service or Azure Function. Your decision is perfect I would say. For Azure Function its not mandatory to have web service for that. Azure function would be best option for you. You can implement all the feature that Web API provides. So if your target is only develop API then you can start with Azure Function with no other alternative. Its outstanding actually!

Does anyone have an experience building, managing and scaling up and out Azure Functions as a REST API provider?

I am working with Azure Function for our AI Base Bot with LUIS integration. From my understanding it's a very easily maintainable, fastest response time, you can build it from anywhere. So you can undoubtedly go with Azure function.

Why Choose Azure Function:

  1. It's stateless, need not any server to run
  2. Full REST, can call from anywhere any Region
  3. Can develop both Azure Portal and local Visual Studio
  4. Cost-effective, you can pay only how much you use.
  5. Multiple language support
  6. Easy Authorization and Authentication functionality
  7. No limit of calling as per your consumption plan

Do A Lot With Azure Function:

You can develop a robust API service with Azure functions. It has many outstanding features. Please check Check here

Authorization and Authentication:

You can simply integrate your authorization and authentication on your function App. Even you can implement it on each function separately or on a full application. It supports most of the popular authentication provider for example:

  1. Azure Active Directory
  2. Microsoft Identity
  3. Goggle
  4. Facebook
  5. Twitter auth

See how can you implement authentication:

Step:1

enter image description here

Step:2

enter image description here

Rest Function Code Sample:

Here I am giving you a simple code snippet to start with: though it's on Azure Table Storage, but help you to develop azure function and CRUD concept.

Your Sample Class:

  public class YourSampleClass
    {

        public string PartitionKey { get; set; }
        public string RowKey { get; set; }

    }

Table Storage Class:

 public class TableStorageClass
    {
        public TableStorageClass()
        {

        }
        public TableStorageClass(DynamicTableEntity entity)
        {
            PartitionKey = entity.PartitionKey;
            RowKey = entity.RowKey;

        }

        public string PartitionKey { get; set; }
        public string RowKey { get; set; }


    }

Azure Function V2 Example:

public static class FunctionReadFromTableStorage
    {
        [FunctionName("FunctionReadFromTableStorage")]
        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.");

            //Read Request Body
            var content = await new StreamReader(req.Body).ReadToEndAsync();

            //Extract Request Body and Parse To Class
            YourSampleClass objYourSampleClass = JsonConvert.DeserializeObject<YourSampleClass>(content);

            // Validate param because PartitionKey and RowKey is required to read from Table storage In this case , so I am checking here.
            dynamic validationMessage;

            if (string.IsNullOrEmpty(objYourSampleClass.PartitionKey))
            {
                validationMessage = new OkObjectResult("PartitionKey is required!");
                return (IActionResult)validationMessage;
            }
            if (string.IsNullOrEmpty(objYourSampleClass.RowKey))
            {
                validationMessage = new OkObjectResult("RowKey is required!");
                return (IActionResult)validationMessage;
            }


            // Table Storage operation  with credentials
            var client = new CloudTableClient(new Uri("https://YourStorageURL.table.core.windows.net/"),
                      new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials("YourStorageName", "xtaguZokAWbfYG4QDkBjT+YourStorageKey+T/kId/Ng+cl3TfYHtg=="));
            var table = client.GetTableReference("YourTableName");

            //Query filter
            var query = new TableQuery()
            {
                FilterString = string.Format("PartitionKey eq '{0}' and RowKey eq '{1}'", objYourSampleClass.PartitionKey, objYourSampleClass.RowKey)
            };


            //Request for storage query with query filter
            var continuationToken = new TableContinuationToken();
            var storageTableQueryResults = new List<TableStorageClass>();
            foreach (var entity in table.ExecuteQuerySegmentedAsync(query, continuationToken).GetAwaiter().GetResult().Results)
            {
                var request = new TableStorageClass(entity);
                storageTableQueryResults.Add(request);
            }

            //As we have to return IAction Type So converting to IAction Class Using OkObjectResult We Even Can Use OkResult
            var result = new OkObjectResult(storageTableQueryResults);
            return (IActionResult)result;
        }
    }

Point To Remember:

  1. In case of Azure Portal execution just get rid of FunctionReadFromTableStorage class
  2. You Need following reference to execute above code
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.WindowsAzure.Storage.Table;
using System.Collections.Generic;

Postman Request Pattern:

Function Invoke Sample:

{
   "PartitionKey": "Your Param According to Table Storage Design" ,
   "RowKey": "Your Param According to Table Storage Design",
   "Directory": "Your Param According to Table Storage Design"
}

See The Screen Shot:

enter image description here

Post Man Response:

Response is subject to my own table design

[
    {
        "partitionKey": "Microsoft SharePoint Server",
        "rowKey": "2016"
    }
]

See The Screen Shot Below:

enter image description here

Note: For CosmosDb Integration you could check here. Azure SQL with Function take a look here.

like image 53
Md Farid Uddin Kiron Avatar answered Oct 10 '22 18:10

Md Farid Uddin Kiron