65.9K
CodeProject is changing. Read more.
Home

Calling an API using RestSharp in ASP.NET

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (3 votes)

Aug 12, 2015

CPOL
viewsIcon

22483

Calling an API using RestSharp in ASP.NET

These days, Rest Services are most popular, everyone likes to use Rest Services. RestSharp is a Simple REST and HTTP client for .NET.

There are many ways to consume RESTful services in client veg. WebClient, etc. But, RestSharp is wonderful to consume REST services. This provides a simple call while we want to 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 the 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 follows (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);

The 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 an abstract way.

The post Calling an API using RestSharp in ASP.NET appeared first on Gaurav-Arora.com.