How to consume a Web API using RestSharp

Take advantage of the flexible and easy-to-use RestSharp HTTP API client to consume your REST APIs

How to consume a Web API using RestSharp
Thinkstock

When working with APIs you might often need to interface with public APIs and perform CRUD operations. To connect to and work with such APIs, you have libraries aplenty. One of the most popular is RestSharp, mainly because of its simplicity.

RestSharp is an open source HTTP client library that can interface with public APIs and consume data without the need to deal with the complexity of the raw HTTP requests. It is an easy to use and powerful library that you can leverage to consume your RESTful API built using .NET. The best thing in RestSharp is that it can even work with even .NET 2.0 and it supports Xamarin and Windows Phone as well. This article presents a discussion on RestSharp and how it can be used to consume RESTful APIs build using ASP.NET Web API.

Install RestSharp

You can install RestSharp in your project from the NuGet Package Manager UI or by typing the following command in the NuGet Package Manager console.

Install-Package RestSharp

As of this writing, the latest stable version of RestSharp is 106.2.1.

Create a simple Web API

First off, create a new Web API project in Visual Studio. Next, create a new Web API controller class as shown below.

 public class CustomersController : ApiController
    {
        private readonly List<Customer> lstCustomer = null;
        public List<Customer> Get()
        {
            return lstCustomer;
        }
        public CustomersController()
        {
            lstCustomer = new List<Customer>();
            lstCustomer.Add(new Customer() { Id = 1, FirstName = "Joydip", LastName = "Kanjilal" });
            lstCustomer.Add(new Customer() { Id = 2, FirstName = "Michael", LastName = "Jones" });
        }
        public Customer Get(int id)
        {
            return lstCustomer[id];
        }
        public void Post([FromBody]Customer customer)
        {
            //Usual code
        }
        public void Put(int id, [FromBody]Customer customer)
        {
            //Usual code
        }
        public void Delete(int id)
        {
            //Usual code
        }
 }

Here is a look at the Customer class for your reference.

public class Customer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

We’ll use JSON as the formatter in this example, so we can remove the default XML formatter. To do this, write the following piece of code in the Register method of the WebApiConfig.cs file.

config.Formatters.Remove(config.Formatters.XmlFormatter);

Consume the Web API using RestSharp

Now that our Web API is ready for use, let’s start consuming it. Create another project – this time a Console application project to keep it simple. In this console project, install RestSharp via NuGet by following the steps discussed above.

Once RestSharp has been downloaded and installed in your project, you can get started using it simply by creating an instance of RestClient as shown in the code snippet below.
RestClient restClient = new RestClient("http://localhost:9000/api/");

Next, instantiate the RestRequest class and specify the appropriate HTTP verb, in this case is Method.GET.

RestRequest restRequest = new RestRequest("Customers", Method.GET);

Finally, execute the request.

var response = restClient.Execute<List<Customer>>(restRequest);

The following method, which consolidates all of these steps, shows how you can retrieve a list of all customers from the Web API using RestSharp.

public static List<Customer> GetCustomers(string baseUri)
        {
            var client = new RestClient(baseUri);
            RestRequest request = new RestRequest("api/Customers/", Method.GET);
            var response = client.Execute<List<Customer>>(request);
            return response.Data;
        }

POST to the Web API using RestSharp

Creating a new customer is also simple. This time, we specify Method.POST as the HTTP verb. Note how the AddJsonBody method has been used in the code listing below to serialize the customer object into JSON before it is passed to the Web API.

public static void CreateCustomer(string baseUri, Customer customer)
        {
            var client = new RestClient(baseUri);
            var request = new RestRequest("api/Customers/", Method.POST);
            request.AddJsonBody(customer);
            client.Execute(request);
        }

Updates and deletes to the Web API using RestSharp

The following two methods can be used to update and delete customer data respectively. Note the use of Method.PUT and Method.DELETE to specify the appropriate HTTP verb for the action that needs to be executed by your Web API.

public void Update(string baseUri, int id, Customer customer)
        {
            var client = new RestClient(baseUri);
            var request = new RestRequest("Customers/" + id, Method.PUT);
            request.AddJsonBody(customer);
            client.Execute(request);
        }
        public void Delete(string baseUri, int id)
        {
            var client = new RestClient(baseUri);
            var request = new RestRequest("Customers/" + id, Method.DELETE);
            client.Execute(request);
        }

If you want to add additional headers using RestSharp, you can do that with ease. All you need to do is invoke the AddHeader method on the RestRequest instance and pass the necessary parameters.

request.AddHeader("Security", "Some data");

Copyright © 2018 IDG Communications, Inc.