LINQ API REST AND DESERIALIZATION

We will focus on three concepts here:  

Now for a date we can have access to the status of a financial portfolio, which we can see via the api route: 

                                         https://XXXXXX/api/v1/portfolioData/bydatewithbbcompany/2022-01-01


The goal is therefore to carry out an evolutionary study on investments by sector, investment by country and for example to compare the probability of default in each sector. To make it simple, we have to make the data talk and try to extract as much information as possible, taking into account the performances and the graphical rendering.

Step 1  :

// Create an HttpClientHandler object and set to use default credentials

HttpClientHandler handler = new HttpClientHandler()

{

UseDefaultCredentials = true,

AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate,

UseProxy = false

};


The HttpClientHandler class and derived classes allow developers to configure various options ranging from proxies to authentication.

Step 2  :

using (HttpClient Client = new HttpClient(handler, true)) // Use http request

{

var GetData = Client.GetAsync(url).GetAwaiter().GetResult();

var GetGataString =

GetData.Content.ReadAsStringAsync().GetAwaiter().GetResult(); //Take the content of response

var list = JsonConvert.DeserializeObject<List<Class1>>( GetGataString);// Make list of our object

ListOfDate = list.Select(x => x.item2.ToString("yyyy-MM-dd")).Distinct().ToList(); // Take just date which item2 in object

}

We will concentrate on explaining these two steps which contain the important notions 

API requests


An API (Application Programming Interface) is an interface that allows different applications to communicate with each other. It is like a gateway that allows two programs to talk to each other.

The term REST stands for "Representational State Transfer". It is a software architecture that defines a set of constraints for creating web services. Basically, a REST API is an API that respects these constraints to create web services.

A REST API is based on HTTP (Hypertext Transfer Protocol), which is the communication protocol used on the Web. The API is built around the basic operations of HTTP, such as GET, POST, PUT and DELETE, which correspond to the actions of reading, writing, updating and deleting data.

The basic idea behind the REST API is that each resource (an object, image, file, etc.) is identified by a URI (Uniform Resource Identifier), which is the address of the resource on the Web. You can therefore access a resource by sending a request to its URI.

For example, if you want to get the information about a user in an application, you can send an HTTP GET request to the corresponding URI. That's what I do here :

var GetData = Client.GetAsync(url).GetAwaiter().GetResult();

var GetGataString = GetData.Content.ReadAsStringAsync().GetAwaiter().GetResult(); 

//Take the content of response


If you want to create a new user, you can send an HTTP POST request to the corresponding URI. If you want to update a user's information, you can send an HTTP PUT request to the corresponding URI.

In short, a REST API is a set of rules and conventions that allow different applications to communicate with each other using standard Web protocols. It allows developers to access and manipulate data in an application using basic operations such as GET, POST, PUT and DELETE.


Serialisatin Deserialization 


Serialization is like taking an image and turning it into something else so that it can be stored or transmitted more easily. In programming, it means taking an object in your code and turning it into a form that can be stored or transmitted more easily. This can be useful if you want to save data to a hard drive or send it to another program.

Deserialization is the opposite. It means taking something you have stored or received and turning it into an object that your program can understand and use.

Now let's move on to System.Text.Json.JsonSerializer. This is a tool in the C# programming language that allows you to serialize and deserialize objects in JSON (JavaScript Object Notation). JSON is a data format that is easy for humans to read and easy for computers to process.

To serialize an object to JSON with System.Text.Json.JsonSerializer, you simply create an instance of the JsonSerializer class, then call its Serialize method by passing the object you want to serialize. This will return a string containing the JSON corresponding to the object.

To deserialize an object from JSON with System.Text.Json.JsonSerializer, you must also create an instance of the JsonSerializer class, then call its Deserialize method passing the JSON string you want to deserialize. This will return the corresponding object.


That's what we do here, we transform our data retrieved via the Get request into List<Class1> 

var list = JsonConvert.DeserializeObject<List<Class1>>( GetGataString);// Make list of our object

And so I would have a list of class1 that I could manipulate with the Linq methods

   AND CLASS 1 IS

public class Class1

{

public Guid item1 { get; set; }

public DateTime item2 { get; set; }

}











But what are Linq methods ?????

LINQ (Language Integrated Query) is a feature of C# that allows developers to manipulate and query data in a simple and elegant way. LINQ methods are extension methods that are applied to data collections and return a new modified or filtered data collection. LINQ methods are also called query operators.

Here are some examples of common LINQ methods in C#:

string[] names = { "MArie", "Ahmed", "Charlie", "Dave" };

var filteredNames = names.Where(name => name.StartsWith("A"));

/The variable filteredNames will contain a new collection that contains only the name "Ahmed"

int[] numbers = { 1, 2, 3, 4 };

var multipliedNumbers = numbers.Select(number => number * 2);

//The multipliedNumbers variable will contain a new collection that contains the numbers 2, 4, 6 and 8


These are just a few examples of LINQ methods. There are many others, like Aggregate, Join, GroupBy, etc. LINQ methods can be very useful for working with data collections and writing queries in a more elegant and expressive way.


For example here: 

ListOfDate = list.Select(x => x.item2.ToString("yyyy-MM-dd")).Distinct().ToList();

I want to keep only the dates that's my goal, so I have to select item2 in my class 1 list avoiding redundancy and then transform it into a list ehehe which becomes a list<string>.

Now that I have all the dates that interest me I can use them to retrieve all the information for a selected date

var url = string.Format("https://cart-uat.axa-im.intraxa:8535/api/v1/portfolioData/bydatewithbbcompany/{0}", DATESELECTED); //Access to the Dataset of date

HttpClientHandler handler1 = new HttpClientHandler()

{

UseDefaultCredentials = true,

AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate,

UseProxy = false

};







using (HttpClient Client1 = new HttpClient(handler1, true))

{

var date1 = Client1.GetAsync(url).GetAwaiter().GetResult();

var datestring1 = date1.Content.ReadAsStringAsync().GetAwaiter().GetResult();

var data = JsonConvert.DeserializeObject<List<Class2>>(datestring1);

sectorMax = data.Where(x => x.Sector != " ").GroupBy(x => x.Sector).Select(x => new Class3{ Name = x.Key, Count = x.Count() }).OrderByDescending(x => x.Count).Where(x => x.Count > 25).ToList();

countryMax = data.Where(x => x.Country != " ").GroupBy(x => x.Country).Select(x => new Class3 { Name = x.Key, Count = x.Count() }).OrderByDescending(x => x.Count).Where(x=>x.Count>3).ToList();

PDMAX = data.Where(x => x.Sector != " " & x.Pd != null).Select(x => new Class4{ PD = x.Pd, Sector = x.Sector }).Distinct().Where(x=>x.PD>0.1).ToList();

}

I will detail this example a bit:

sectorMax = data.Where(x => x.Sector != " ").GroupBy(x => x.Sector).Select(x => new Class3{ Name = x.Key, Count = x.Count() }).OrderByDescending(x => x.Count).Where(x => x.Count > 25).ToList();

here what interests me is to return the most abundant sector at a fixed date, well it's simple, already I exclude the data or sector is empty (no sector of invessment):

  Where(x => x.Sector != " ")

then I make a grouping by sector GroupBy(x => x.Sector) then I keep only the sector and the number of times repeated, that corresponds to all the invesstissement in the same sector ) with 

Select(x => new Class3{ Name = x.Key, Count = x.Count() }) 

All that is left to do is to display this as a graph and a histogram ! For the blow I built this project in Blazor and use the components provided by Radzen https://blazor.radzen.com/column-chart


I was able to create a whole project of data analysis, data extraction with API and data manipulation with linq and serialization/deserialization. And finally it is necessary to make it visible for that I used the framwork blazor.