Friday, 9 October 2020

RestSharp

You need to connect to some APIs but you don't know how or you are having some trouble to do that. Well, why not download RestSharp?

RestSharp is a REST API client for your .NET apps. Extremely useful if you are developing websites or apps that retrieve information from APIs. 

The REST mechanism is a easier and more secure way of fetching information from APIs
REST stands for Representational State Transfer. A web server is the place where the API is hosted. A HTTP request could be a GET, POST, PUT, DELETE... these are used to tell the API what action you want to perform. The client is your application. The Web server will respond in JSON or XML or both

The two packages that you need to install are Newtonsoft.JSON and RestSharp. Newtonsoft.JSON is used to parse the response from the API. Most APIs use a JSON response. Before doing anything you need to know how the API is going to reply and how the JSON response is going to look like. This is crucial as it is going to help you in creating a model class for your app. A model class is a class that represents the response and everything that the JSON file contains. 

You can create a model class from scratch by looking at the JSON file and copying every field title or you can use json2csharp. This website is going to ask for the JSON file and convert it to a C# model class.

On your main file create an async Task:

public async Task ApiMethod(string search){
            var client = new RestClient($"https://apiurl.com/{search}");
            var request = new RestRequest(Method.GET);
            request.AddHeader("a header", "header content");
            request.AddHeader("another header", "header content");
            IRestResponse response = client.Execute(request);


This is going to initialize the client and make the request to the API. The AddHeader is used to pass any headers that the API wants in order to allow access, this could be an API key for example. Having this done now you need to convert your JSON to C# model class. The code will change according to the API you use and the request. An example could be:

public class Response 
{
    public long id {get; set;}
       public string text {get; set;}
}

Now you need to deserialize by doing:

Response result = JsonConvert.DeserializeObject<Response>(response.Content)


And there you go! 
You can use the model by doing: result.[whatever value you have in the class]





1 comment:

Technologies for Websites

 Making websites from scratch isn't easy, you need to use specific technologies and protect yourself from common Internet Crimes, such a...