Calling an API using RestSharp in ASP.NET

In these days Rest Services are most popular, everyone like to use Rest Services. RestSharp is a Simple REST and HTTP client for .Net

There are many ways to consume RESTFull services in client veg. WebClient etc. But, RestSharp is the wonderful to consule REST services. This provides a simple call while we want o consume services at client side.

This is easier just in three steps:

Create RestClient

private readonly RestClient _client;  
private readonly string _url = ConfigurationManager.AppSettings["webapibaseurl"];  
  
public ServerDataRestClient()  
{  
   _client = new RestClient(_url);  
}

In above, snippet we created a client with Base url of our services and retrieving this url from our config file (a recommended way). Also, we can use the same as followings (not recommended)

var client = new RestClient("http://crudwithwebapi.azurewebsites.net/"); 

Make a request

var request = new RestRequest("api/serverdata", Method.GET) {RequestFormat = DataFormat.Json};

Here, we are calling GET resource and telling RestSharp to provide data/response in JSON format.

Play with response

var response = _client.Execute<List<ServerDataModel>>(request);

Complete code would look like:

private readonly RestClient _client;  
private readonly string _url = ConfigurationManager.AppSettings["webapibaseurl"];  
  
public ServerDataRestClient()  
{  
   _client = new RestClient(_url);  
}  
  
public IEnumerable<ServerDataModel> GetAll()  
{  
    var request = new RestRequest("api/serverdata", Method.GET) {RequestFormat = DataFormat.Json};  
  
    var response = _client.Execute<List<ServerDataModel>>(request);  
  
     if (response.Data == null)  
          throw new Exception(response.ErrorMessage);  
  
     return response.Data;  
}

This is just a simple implementation, we can create a generic class and use the same in abstract way.

Leave A Reply