Azure

Constructing Serverless API’s Utilizing Azure Features And C#

Introduction

Azure Features is a serverless compute service and simple resolution for working small items of code, or “capabilities,” inside the cloud. It might probably make our growth much more productive. You may write simply the code you prefer to for the matter at hand, with out concern of the entire utility or the infrastructure to run it.

On this tutorial, I’ll attempt to make you perceive how Azure Features will permit us to create APIs utilizing HTTP Set off by utilizing Entity Framework Core Layer as an ORM with C# Code and SQL Database for Information Storage. So, let’s get began.

You’ll find the Supply Code right here 

Conditions

Desk of Contents

  1. Establishing the Azure Perform
  2. Database Schema and Entity Mannequin
  3. Establishing the Reference to SQL Database by utilizing EF Core
  4. Initialize Dependency Injection
  5. Injecting the DbContext right into a operate
  6. Implementing Features
  7. Tesing the APIs utilizing Postman 
  8. Conclusion

Establishing the Azure Perform

Open the Visual Studio and seek for Blazor App. Click on on the Subsequent button,

Outline the undertaking identify, path, and resolution identify. Click on on the Create button,

After that, a new window will pop up to decide on the goal framework (Azure Features v2 (.Web Core)) from the dropdown and ensure to pick the Http Set off and within the Authorization degree part choose Nameless as we’re not following within the current article.

Building Serverless APIs Using Azure Functions

This creates a skeletal undertaking with a primary Azure Perform.

Database Schema and Mannequin Entity 

Right here is the schema for the worker desk. Execute the schema in your respective SQL Database. Beneath is the image after creating the desk within the Database.

CREATE TABLE Worker(
    Id int IDENTITY(1,1) PRIMARY KEY,
    Identify nvarchar(100) NOT NULL,
    Designation nvarchar(100) NOT NULL,
    Metropolis nvarchar(100) NOT NULL
);

Create a folder named Fashions and contained in the folder will create a category named Worker –  Entity Mannequin with minimal properties to make our implementation simple

Worker. cs

namespace API_EFCore_AzureFunctions.Fashions
{
    public class Worker
    {
        public int Id { get; set; }
        public string Identify { get; set; }
        public string Designation { get; set; }
        public string Metropolis { get; set; }
    }
}

Subsequent, let’s add the DbContext class to our utility. This helps us to entry the Database tables which will probably be generated by our Fashions through the appliance. Create a  AppDbContext class to outline our DbContext.

AppDbContext.cs

utilizing Microsoft.EntityFrameworkCore;

namespace API_EFCore_AzureFunctions.Fashions
{
   public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> choices)
        : base(choices)
        {

        }
        public DbSet<Worker> Worker { get; set; }
    }
}

Establishing the Reference to SQL Database by utilizing EF Core

As a way to make a connection to SQL Database with EF Core right here, we require the next packages to ascertain the connection by utilizing the Db first strategy. We will set up the required packages by utilizing the Nuget Package deal Supervisor or by utilizing the Package deal supervisor console.

Be sure to set up the bundle with model v2.0.0 as a result of that’s the totally working model with none points with v2 Web Core.

Building Serverless APIs Using Azure Functions

Initialize Dependency Injection

To arrange dependency injection for our operate app we use the FunctionsStartup attribute on the meeting to point a startup class that may run when the operate app begins. In that class, which inherits from FunctionsStartup we override the Configure technique. This permits us to retrieve the SQL connection string from configuration, and register a DbContext within the companies, which can permit us to inject the AppDbContext into our operate. Create a Class named Startup.cs to combine the Dependency Injection

Startup.cs 

utilizing API_EFCore_AzureFunctions.Fashions;
utilizing Microsoft.Azure.Features.Extensions.DependencyInjection;
utilizing Microsoft.EntityFrameworkCore;
utilizing Microsoft.Extensions.DependencyInjection;

[assembly: FunctionsStartup(typeof(API_EFCore_AzureFunctions.Startup))]

namespace API_EFCore_AzureFunctions
{
   public class Startup : FunctionsStartup
   {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            string connectionString = "Information Supply=Server Identify;Built-in Safety=true;Database=Database Identify";
            builder.Providers.AddDbContext<AppDbContext>(
                choices => SqlServerDbContextOptionsExtensions.UseSqlServer(choices, connectionString));
        }
   }
}

Injecting the DbContext right into a Perform

What dependency injection now gives to us is the flexibility for us to outline our capabilities in courses which have their dependencies injected into their constructor. Open the Function1.cs file to inject our dependencies.

Function1.cs

        #area Property
        personal readonly AppDbContext _appDbContext;
        #endregion

        #area Constructor
        public Function1(AppDbContext appDbContext)
        {
            _appDbContext = appDbContext;
        }
        #endregion

Implementing Features

On this instance, we’re utilizing 5 capabilities

  • GetEmployees: Get all the staff from the DB
  • CreateEmployee: Insert the employee-related info to DB
  • GetEmployeebyId: Get the Worker document based mostly on their worker Id
  • UpdateEmployee: Replace the present worker with modifications
  • DeleteEmployee:  Deletion of Worker Report from the Database.

GetEmployees

#area Perform Get Staff
        /// <abstract>
        /// Get Record of Staff
        /// </abstract>
        /// <param identify="req"></param>
        /// <param identify="log"></param>
        /// <returns></returns>
        [FunctionName("GetAllEmployees")]
        public async Activity<IActionResult> GetAllEmployees(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]
          HttpRequest req, ILogger log)
        {
            attempt
            {
                log.LogInformation("Getting Worker record objects");
                return new OkObjectResult(await _appDbContext.Worker.ToListAsync());
            }
            catch (System.Exception)
            {
                throw;
            }
            
        }
        #endregion

Line – 8: Added Identify for the Perform identify attribute.

Line – 9: Defining a Perform (Methodology)

Line – 10:  Attribute Property for HTTP Set off.

  • AuthorizationLevel  – Azure Perform protects your HTTP set off utilizing Authorization keys. Authorization Stage is available in three flavors
                                              1. Nameless: No secret’s required.
                                      2.  Perform: A selected operate secret’s required. That is the default worth if none is specified.
                                      3.  Admin: A grasp secret’s required.
  • Route – It defines the route template on which the endpoint is listening. The default worth of the route is ready to api/<FunctionName>.
  • Methodology – That is used to outline HTTP verbs for the capabilities.

Line 13- 21: Including attempt catch block to deal with the exceptions and fetching all of the Worker information from the Database.

CreateEmployee

 #area Create Worker
        /// <abstract>
        /// Create New Worker
        /// </abstract>
        /// <param identify="req"></param>
        /// <param identify="log"></param>
        /// <returns></returns>
        [FunctionName("CreateEmployee")]
        public async Activity<IActionResult> CreateEmployee(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = Route +"/Create")]
          HttpRequest req, ILogger log)
        {
            log.LogInformation("Creating a brand new worker record merchandise");
            var requestBody = await new StreamReader(req.Physique).ReadToEndAsync();
            var enter = JsonConvert.DeserializeObject<Worker>(requestBody);
            var worker = new Worker { Identify = enter.Identify, Designation = enter.Designation,Metropolis= enter.Metropolis };
            await _appDbContext.Worker.AddAsync(worker);
            await _appDbContext.SaveChangesAsync();
            return new OkObjectResult(new { Message = "Report Saved SuccessFully", Information = worker });
        }
        #endregion

GetEmployeebyId

 #area Get Worker Based mostly on Worker Id
        /// <abstract>
        /// Get Worker by Querying with Id
        /// </abstract>
        /// <param identify="req"></param>
        /// <param identify="log"></param>
        /// <param identify="Id"></param>
        /// <returns></returns>
        [FunctionName("GetEmployeebyId")]
        public async Activity<IActionResult> GetEmployeebyId(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "{Id}")]
          HttpRequest req, ILogger log, int Id)
        {
            attempt
            {
                var consequence = await _appDbContext.Worker.FindAsync(Id);
                if (result's null)
                {
                    log.LogInformation($"Merchandise {Id} not discovered");
                    return new NotFoundResult();
                }
                return new OkObjectResult(consequence);
            }
            catch (System.Exception)
            {
                throw;
            }
        }
        #endregion

UpdateEmployee

  #area Replace Worker
      /// <abstract>
      /// Replace Worker - Adjustments
      /// </abstract>
      /// <param identify="req"></param>
      /// <param identify="log"></param>
      /// <param identify="Id"></param>
      /// <returns></returns>
        [FunctionName("UpdateEmployee")]
        public async Activity<IActionResult> UpdateEmployee(
        [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = Route +"/Update")]
          HttpRequest req, ILogger log)
        {
            log.LogInformation("Updating a brand new worker record merchandise");
            var requestBody = await new StreamReader(req.Physique).ReadToEndAsync();
            var up to date = JsonConvert.DeserializeObject<Worker>(requestBody);
            var worker = await _appDbContext.Worker.FindAsync(up to date.Id);
            if(worker is null)
            {
                log.LogError($"Merchandise {up to date.Id} not discovered");
                return new NotFoundResult();
            }
            if(!string.IsNullOrEmpty(up to date.Identify) && !string.IsNullOrEmpty(up to date.Designation))
            {
                worker.Identify = up to date.Identify; worker.Designation = up to date.Designation;
                worker.Metropolis = up to date.Metropolis;
            }
            _appDbContext.Worker.Replace(worker);
            await _appDbContext.SaveChangesAsync();
            return new OkObjectResult(new { Message = "Report Up to date SuccessFully", Information = worker });
        }
        #endregion

DeleteEmployee

#area Delete Worker
        /// <abstract>
        /// Deletion of Worker
        /// </abstract>
        /// <param identify="req"></param>
        /// <param identify="log"></param>
        /// <param identify="Id"></param>
        /// <returns></returns>
        [FunctionName("DeleteEmployee")]
        public async Activity<IActionResult> DeleteEmployee(
        [HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "DeleteEmployee/{Id}")]
          HttpRequest req, ILogger log,int Id)
        {
            log.LogInformation("Updating a brand new worker record merchandise");
            var worker = await _appDbContext.Worker.FindAsync(Id);
            if (worker is null)
            {
                log.LogError($"Merchandise {Id} not discovered");
                return new NotFoundResult();
            }
            _appDbContext.Worker.Take away(worker);
            await _appDbContext.SaveChangesAsync();
            return new OkObjectResult("Report Deleted !");
        }
        #endregion

Lastly, we’ve got managed to place all of the code modifications in place. Run the appliance and confirm the all of the strategies are working as anticipated within the Postman. After working the appliance all our capabilities will probably be loaded within the terminal as a result of the Azure Features will use the Storage emulator to fetch the responses contained in the terminal.

Building Serverless APIs Using Azure Functions

Funtion Run Time Model – The goal framework we choosed on the time of Azure Perform setup.

Now Listening on – The Port Quantity during which the Azure capabilities are working (7071).

Testing the APIs utilizing Postman  

Let’s create the Worker First utilizing the CreateEmployee API utilizing Postman

How this really works?

We had been fetching the req physique from the HTTP Set off and attaching the Json to our Worker mannequin class for deserialization  after which passing the Worker object to the Database which you’ll see within the CreateEmployee Perform.

Fetch the Record of Staff from the GetEmployee API.

Replace the Present Report utilizing the UpdateEmployee API and right here on this object the Worker Id is obligatory. Based mostly on Id we’re fetching the present document from the Db and updating the Identical document with new object.

Delete the Report from the Database by passing the EmployeeId as Question Parameter within the route.

Conclusion

On this article, we discovered find out how to implement the Serverless APIs utilizing the Azure Features and integrating with the Database by utilizing the Entity Framework Core Dependency Injection. Thanks for staying till the top. 

Thanks for studying, please let me know your questions, ideas, or suggestions within the feedback part. I recognize your suggestions and encouragement.

Continue learning….!

Tags
Show More

Related Articles

Leave a Reply

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

Close