CRUD Rest API With Azure Function

Print Friendly, PDF & Email

CRUD Rest API With Azure Function

In the last post we updated the code to use local.settings.json and the Azure Function Application Settings. In this post were going to create three additional REST methods, Create, Update and Delete Person. In addition to this I have also added Route information to each of the methods to add in a version to the end point URL path. additional the original method was called Run, this had to be changed so that we could create multi methods, so i used the end point name for each of the method names.

Get All People

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;

using MySql.Data.MySqlClient;

using Dapper;

using Newtonsoft.Json;

namespace DemoFunctionApp
{
    public static class PeopleFunctions
    {
        //These must be added in Azure in the AppSettings Section and local.settings.json
        public static readonly string kvUri = Environment.GetEnvironmentVariable("KeyVault_URI");
        public static readonly List<string> secrets = Environment.GetEnvironmentVariable("Secret_Names").Split(',').ToList();

        [FunctionName("GetAllPeople")]
        public static IActionResult GetAllPeople(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "v1/GetAllPeople")] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            using (IDbConnection connection = new MySqlConnection(AzureMySqlConnectionHelper.Connection(log, kvUri, secrets)))
            {
                string queryString = "Select * From peopletable";
                log.LogInformation(string.Format("Function - GetAllPeopleModels - {0}", queryString));
                try
                {
                    IEnumerable<PeopleModel> output = connection.Query<PeopleModel>(queryString, new DynamicParameters()).ToList();
                    log.LogInformation(string.Format("Function - NUmber of Return Results is - {0}", output.Count()));
                    return new OkObjectResult(output);
                }
                catch (Exception ex)
                {
                    log.LogError(ex.Message);
                    return new BadRequestObjectResult(ex.Message);
                }
            }
        }
    }
}

Create Person

With Create, Update and Delete a Json payload will be sent to these methods as a result an async read method will have to be used to read all of the request body, once we have the body it can be deserialized into a person model.

        [FunctionName("CreatePerson")]
        public static async Task<IActionResult> CreatePerson(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "v1/CreatePerson")] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            PeopleModel peopleModel = JsonConvert.DeserializeObject<PeopleModel>(requestBody);

            if (peopleModel != null)
            {
                using (IDbConnection connection = new MySqlConnection(AzureMySqlConnectionHelper.Connection(log, kvUri, secrets)))
                {
                    string queryString = "Insert into peopletable (Name,LastName,Age) Values(@Name,@LastName,@Age)";
                    log.LogInformation(string.Format("Function - CreatePerson - {0}", queryString));
                    try
                    {
                        connection.Execute(queryString, peopleModel);
                        return new OkObjectResult(peopleModel);
                    }
                    catch (Exception ex)
                    {
                        log.LogError(ex.Message);
                        return new BadRequestObjectResult(ex.Message);
                    }
                }
            }
            return new BadRequestResult();
        }

Update Person

        [FunctionName("UpdatePerson")]
        public static async Task<IActionResult> UpdatePerson(
            [HttpTrigger(AuthorizationLevel.Function, "patch", Route = "v1/UpdatePerson")] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            PeopleModel peopleModel = JsonConvert.DeserializeObject<PeopleModel>(requestBody);

            if (peopleModel != null)
            {
                using (IDbConnection connection = new MySqlConnection(AzureMySqlConnectionHelper.Connection(log, kvUri, secrets)))
                {
                    string queryString = "Update peopletable Set Name = @Name, LastName = @LastName,Age=@Age WHERE ID=@ID";
                    log.LogInformation(string.Format("Function - UpdatePerson - {0}", queryString));
                    try
                    {
                        connection.Execute(queryString, peopleModel);
                        return new OkObjectResult(peopleModel);
                    }
                    catch (Exception ex)
                    {
                        log.LogError(ex.Message);
                        return new BadRequestObjectResult(ex.Message);
                    }
                }
            }
            return new BadRequestResult();
        }

Delete Person

		[FunctionName("DeletePerson")]
        public static async Task<IActionResult> DeletePerson(
            [HttpTrigger(AuthorizationLevel.Function, "delete", Route = "v1/DeletePerson")] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            PeopleModel peopleModel = JsonConvert.DeserializeObject<PeopleModel>(requestBody);

            if (peopleModel != null)
            {
                using (IDbConnection connection = new MySqlConnection(AzureMySqlConnectionHelper.Connection(log, kvUri, secrets)))
                {
                    string queryString = "Delete from peopletable WHERE ID=@ID";
                    log.LogInformation(string.Format("Function - DeletePerson - {0}", queryString));
                    try
                    {
                        connection.Execute(queryString, peopleModel);
                        return new OkObjectResult(true);
                    }
                    catch (Exception ex)
                    {
                        log.LogError(ex.Message);
                        return new BadRequestObjectResult(ex.Message);
                    }
                }
            }
            return new BadRequestResult();
        }