• Ivy Seo

Azure Function, Postgresql, JSON format, C#

this Azure function grabs data from cloud database (which is Azure cloud postgres)

and data is sent in JSON format.


using Npgsql;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace MartenAzureDocDbDemo
    public static class QuotesGet
        public class M7Data
            public M7Data(int Id_, string Text_, string TruckID_)
                Id = Id_;
                Text = Text_;
                TruckID = TruckID_;
            public int Id { get; set; }
            public string Text { get; set; }
            public string TruckID { get; set; }
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
            // connect to postgresql
            var cs = "Host=##; Username=##; Password=##; Database=##";
            var con = new NpgsqlConnection(cs);
            // run query
            string sql = "SELECT id, Company, TruckID  FROM m7_data_table LIMIT 5";
            var cmd = new NpgsqlCommand(sql, con);
            NpgsqlDataReader rdr = cmd.ExecuteReader();
            var M7Data = new List<M7Data>();
            string test = "";
            // save each row of data
            while (rdr.Read())
                int id = rdr.GetInt32(0);
                string text = rdr.GetString(1);
                string truckID = rdr.GetString(2);
                M7Data.Add(new M7Data(id, text, truckID));
                test = text;
            // convert into Json format
            string _output = JsonConvert.SerializeObject(M7Data);
            // if there is no data: otherwise it shows data in Json format
            string responseMessage = string.IsNullOrEmpty(test)
                           ? "There is no data"
                           : $"Hello, {_output}";
            // will show responseMessage 
            return new OkObjectResult(responseMessage);

<output when you run>