Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Calling an API using RestSharp in ASP.NET

0.00/5 (No votes)
12 Aug 2015 1  
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here