Making Rest API Calls made much simpler using RestSharp in C#

Sathish Nadarajan
 
Solution Architect
November 19, 2018
 
Rate this article
 
Views
5197

Usually from a C# code, calling an API is somewhat cumbersome process to pass the body message and the authentication host headers. Recently, I was trying to look for an alternative and found an interesting NuGet Package called RestSharp, which handles all our headaches and made the API execution much simpler. (This is an Open Source which is not provided by Microsoft. Hence, I am leaving this with the readers to consume that).

1. From our C# application, add the RestSharp NuGet Package as below.

clip_image002

2. Once, added, add the namespace.

3. The complete sample code as below.

No more hassles of creating the HTTP objects.

 namespace CallRestAPI.Console
 
 {
 
 using RestSharp;
 
 class Program
 
 {
 
 static void Main(string[] args)
 
 {
 
 // Create a RestClient
 
 var client = new RestClient("https://URL of the API");
 
 // Define the HTTP Method
 
 var request = new RestRequest(Method.GET);
 
 //Add the headers
 
 request.AddHeader("api-key", "ANY  Authentication Keys if required");
 
 request.AddHeader("Content-Type", "application/json");
 
 //Add the Body Parameter
 
 request.AddParameter("undefined", "BODY", ParameterType.RequestBody);
 
 //Execute the Call
 
 IRestResponse response = client.Execute(request);
 
 }
 
 }
 
 }
 

 

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment