RestSharp simple complete example

Nil Pun picture Nil Pun · Apr 19, 2012 · Viewed 241.7k times · Source

I've been trying to create a simple prototype web application that uses RestSharp to call Rest API.

I've not been able to find one good example of it. Could anyone please share and direct me to right resource please? I've already looked at following, and doesn't provide what I'm looking for i.e fully functional example:

http://restsharp.org/ (Doesn't have full application with example)

http://www.stum.de/2009/12/22/using-restsharp-to-consume-restful-web-services/ (seems to be old)

While prototyping I get the error below for code below:

RestResponse response = client.Execute(request);

*Cannot implicitly convert type 'IRestResponse' to 'RestResponse'. An explicit conversion exists (are you missing a cast?)  *

Answer

wonea picture wonea · Jun 18, 2013

Pawel Sawicz .NET blog has a real good explanation and example code, explaining how to call the library;

GET:

var client = new RestClient("192.168.0.1");
var request = new RestRequest("api/item/", Method.GET);
var queryResult = client.Execute<List<Items>>(request).Data;

POST:

var client = new RestClient("http://192.168.0.1");
var request = new RestRequest("api/item/", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new Item
{
   ItemName = someName,
   Price = 19.99
});
client.Execute(request);

DELETE:

var item = new Item(){//body};
var client = new RestClient("http://192.168.0.1");
var request = new RestRequest("api/item/{id}", Method.DELETE);
request.AddParameter("id", idItem);
 
client.Execute(request)

The RestSharp GitHub page has quite an exhaustive sample halfway down the page. To get started install the RestSharp NuGet package in your project, then include the necessary namespace references in your code, then above code should work (possibly negating your need for a full example application).

NuGet RestSharp