Take advantage of the simple and easy RestSharp library to consume RESTful services in ASP.NET Core Credit: Metamorworks / Getty Images REST is an acronym for Representational State Transfer, an architectural style that has become extremely popular over the past few years. A RESTful API is one that it is built in accordance with the principles and guidelines of REST. RESTful APIs usually return plain text, JSON, or XML as a response. RestSharp is an open source HTTP client library that makes it easy to consume RESTful services. RestSharp provides a developer friendly interface to work with RESTful services while abstracting the internal intricacies of working with HTTP requests. RestSharp supports both synchronous and asynchronous requests. This article presents a discussion of how we can work with RestSharp to consume services built using ASP.NET Core. To work with the code examples in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here. Create an ASP.NET Core API project First off, let’s create an ASP.NET Core project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.Net Core project in Visual Studio. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Click Create. In the “Create New ASP.Net Core Web Application” window, select .NET Core as the runtime and ASP.NET Core 2.2 (or later) from the drop-down list at the top. I’ll be using ASP.NET Core 3.0 here. Select “API” as the project template to create a new ASP.NET Core API application. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here. Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either. Click Create. Following these steps will create a new ASP.NET Core API project in Visual Studio. Next, select the Controllers solution folder in the Solution Explorer window, click “Add -> Controller…,” and select “API Controller with Read/Write Actions.” Name this new controller DefaultController. We’ll use this project in the subsequent sections of this article. Implement the DefaultController in ASP.NET Core API Open the DefaultController.cs file and replace the code in it with the one given below: using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; namespace RESTAPIDemo.Controllers { [Route("api/[controller]")] [ApiController] public class DefaultController : ControllerBase { private readonly Dictionary<int, string> authors = new Dictionary<int, string>(); public DefaultController() { authors.Add(1, "Joydip Kanjilal"); authors.Add(2, "Steve Smith"); authors.Add(3, "Michele Smith"); } [HttpGet] public List<string> Get() { List<string> lstAuthors = new List<string>(); foreach (KeyValuePair<int,string> keyValuePair in authors) lstAuthors.Add(keyValuePair.Value); return lstAuthors; } [HttpGet("{id}", Name = "Get")] public string Get(int id) { return authors[id]; } [HttpPost] public void Post([FromBody] string value) { authors.Add(4, value); } [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { authors[id] = value; } [HttpDelete("{id}")] public void Delete(int id) { authors.Remove(id); } } } Refer to the DefaultController class above. Note that this class contains action methods corresponding to each of the HTTP verbs GET, POST, PUT, and DELETE. For the sake of simplicity, we’re using a Dictionary here to store and retrieve data. You can test this API using your web browser or tools like Postman or Fiddler. Note that I’ve hardcoded the ID in the HttpPost method just for simplicity. You should implement it in your own way to generate an unique key. So far so good. In the sections that follow we’ll learn how to work with RestSharp to consume the API we’ve built. Create the client to consume the API We’ll be using a console application as the client to consume the API we built earlier. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core Console Application project in Visual Studio. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed. Click Next. In the “Configure your new project” window shown next, specify the name and location for the new project. Click Create. That’s all we have to do to create a new .NET Core Console Application project. Install the RestSharp NuGet package To work with RestSharp, you should install the RestSharp package from NuGet. You can do this either via the NuGet Package Manager inside the Visual Studio 2019 IDE, or by executing the following command in the NuGet Package Manager Console: Install-Package RestSharp Consume the ASP.NET Core API using RestSharp Once you’ve installed RestSharp into your project, you can start using it. First, you will need to create an instance of RestClient. The following code snippet shows how you can instantiate and initialize the RestClient class. Note that we’re passing the base URL to the constructor of the RestClient class. RestClient client = new RestClient("http://localhost:58179/api/"); Next, you should create an instance of the RestRequest class by passing the resource name and the method to be used. The following code snippet shows how this can be achieved. RestRequest request = new RestRequest("Default", Method.GET); Lastly, you need to execute the request, deserialize the response, and assign it to an object as appropriate as shown in the code snippet given below. IRestResponse<List<string>> response = client.Execute<List<string>>(request); The following is the complete code listing for your reference. using RestSharp; using System; using System.Collections.Generic; namespace RESTSharpClientDemo { class Program { private static RestClient client = new RestClient("http://localhost:58179/api/"); static void Main(string[] args) { RestRequest request = new RestRequest("Default", Method.GET); IRestResponse<List<string>> response = client.Execute<List<string>>(request); Console.ReadKey(); } } } To make a POST request using RestSharp, you can use the following code: RestRequest request = new RestRequest("Default", Method.POST); request.AddJsonBody("Robert Michael"); var response = client.Execute(request); RestSharp is available across several .NET platforms, which is one of the reasons why it is so popular. The automatic deserialization capability of RestSharp is also noteworthy. You can learn more about RestSharp on GitHub. 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