Take advantage of the flexible and easy-to-use RestSharp HTTP API client to consume your REST APIs Credit: 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 <code>RestClient</code> 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"); Related content feature 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos