Creating a Generic RestClient from Scratch for Xamarin Projects

Introduction

 
In every project of Xamarin, we need to call internet services or Rest APIs for getting remote data for users. There are many Restclients in Nuget as well as other sources. Here, I am going to explain or rather give information about the rest-client which I have built and made Generic for any API calls.
 
Step 1: Create a Visual studio solution for Xamarin application targetting Xamarin forms(can work for Xamarin native apps as well). Add an interface called as IRestClient as shown below:
 
 
Step 2: Add a new class called RestClient and implement IRestClient interface in it as shown below:
 
 
 
Step 3: In MainPage.Xaml, create a button and name it as Call Rest API and add the handler for that in code behind as shown below:
 
 
 
Step 4: For demo purposes, I am using RestApi samples from here and converting the response to C# POCO classes using this.
 
Step 5: With this, we are ready to call apis with just simple call like this below:
 
var response = await _restClient.GetAsync<PostObject>("https://jsonplaceholder.typicode.com/posts/1");
 
_restClient is a singleton instance created from RestClient class.
 
 

Conclusion

 
This RestClient will work for any Xamarin projects and with any customization. Users are required to change the process slightly for custom authentication.
Happy coding