Sunday, December 22, 2024
HomeProductsADO.NET Data ProvidersConsume a RESTful API Using RestSharp and C#

Consume a RESTful API Using RestSharp and C#

This article talks about REST concepts, the RESTSharp library, and how it can be used to work with RESTful APIs in ASP.NET 6. We’ll use a PostgreSQL database using Devart dotConnect for PostgreSQL to store and retrieve data.

RESTSharp is an open-source, portable, lightweight .NET library for working with RESTful web services. You can use it to perform CRUD (create, read, update, and delete) operations on your data using any RESTful API. RestSharp is a popular library for interacting with RESTful APIs. It is a port of the Java version, and it is used to make HTTP requests and parse the responses. 

Pre-requisites

You’ll need the following tools to deal with code examples:

  • Visual Studio 2022 Community Edition
  • dotConnect for PostgreSQL

You can download PostgreSQL from here: https://www.postgresql.org/download/

What is REST? Why do we need it?

The REST architectural style is used to create distributed applications that can communicate among themselves. REST is neither a technology nor a set of standards. It is rather a set of constraints that can be used to define new architectural styles. It is essentially a client-server architecture with stateless connections. REST uses an HTTP-based interface to expose data and services and is based on the concept of resources.

What is RESTSharp?

Using RestSharp, you can interact with RESTful services while abstracting the technical details of HTTP requests. RestSharp offers a developer-friendly interface for interacting with RESTful services while abstracting the technical workings of HTTP queries. RestSharp can handle synchronous and asynchronous requests.

Create a new ASP.NET 6 Core Web API Project

In this section, we’ll learn how to create a new ASP.NET 6 Core Web API project in Visual Studio 2022. 

Now, follow the steps outlined below:

  1. Open Visual Studio 2022.
  2. Click Create a new project.
  3. Select ASP.NET Core Web API and click Next.
  4. Specify the project name and location to store that project in your system. Optionally, checkmark the Place solution and project in the same directory checkbox.
  5. Click Next.
  6. In the Additional information window, select .NET 6.0 (Long-term support) as the project version.
  7. Disable the Configure for HTTPS and Enable Docker Support options (uncheck them).
  8. Since we’ll not be using authentication in this example, select the Authentication type as None.
  9. Since we won’t use Open API in this example, deselect the Enable OpenAPI support checkbox.
  10. Since we’ll not be using minimal APIs in this example, ensure that the Use controllers (uncheck to use minimal APIs) is checked.
  11. Leave the Do not use top-level statements checkbox unchecked.
  12. Click Create to finish the process.

We’ll use this project in this article.

Install NuGet Packages

Before you get started implementing rate limiting, you should install the dotConnect for PostgreSQL package in your project. You can install them either from the NuGet Package Manager tool inside Visual Studio or, from the NuGet Package Manager console using the following commands:

PM> Install-Package Devart.Data.PostgreSql

Getting Started

Create a PostgreSQL database table named Author having the following fields:

  • Id 
  • FirstName
  • LastName
  • Author 

Next, insert some dummy records into this table. We’ll use this table to store and retrieve data using RestSharp.

Create the Model Class

Create a solution folder in the Solution Explorer window and name it Models. Next, create a .cs file called Author.cs with the following code in there:

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

Create the AuthorRepository Class

The IAuthorRepository interface contains the declaration of two methods:

public interface IAuthorRepository
    {
        public void Save(Author author);
        public List<Author> GetAuthors();
    }

The AuthorRepository class implements the methods of the IAuthorRepository interface and encapsulates all database operations.

public class AuthorRepository: IAuthorRepository
    {
        public List<Author> GetAuthors()
        {
            try
            {
                List<Author> authors = new List<Author>();
                using (PgSqlConnection pgSqlConnection =
                 new PgSqlConnection("User Id = postgres; Password = sa123#;" +
                 "host=localhost;database=postgres;")) 
                {
                    using (PgSqlCommand pgSqlCommand = new PgSqlCommand())
                    {
                        pgSqlCommand.CommandText = 
                        "Select * From public.Author";
                        pgSqlCommand.Connection = pgSqlConnection;

                        if (pgSqlConnection.State != 
                        System.Data.ConnectionState.Open)
                            pgSqlConnection.Open();

                        using (PgSqlDataReader pgSqlReader = 
                         pgSqlCommand.ExecuteReader())
                        {
                            while (pgSqlReader.Read())
                            {
                                Author author = new Author();
                                author.Id = 
                             int.Parse(pgSqlReader.GetValue(0).ToString());
                                author.FirstName = 
                             pgSqlReader.GetValue(1).ToString();
                                author.LastName = 
                             pgSqlReader.GetValue(2).ToString();
                                author.Address =
                             pgSqlReader.GetValue(3).ToString();

                             authors.Add(author);
                            }
                        }
                    }
                }
                return authors;
            }
            catch
            {
                throw;
            }
        }
        public void Save(Author author)
        {
            try
            {
                using (PgSqlConnection pgSqlConnection =
                  new PgSqlConnection("User Id = postgres; Password = sa123#;" +
                  "host=localhost;database=postgres;"))
                {
                    using (PgSqlCommand cmd = new PgSqlCommand())
                    {
                        cmd.CommandText = "INSERT INTO public.Author " +
                         "(id, firstname, lastname, address) VALUES " +
                            "(@id, @firstname, @lastname, @address)";
      
                        cmd.Connection = pgSqlConnection;
                        cmd.Parameters.AddWithValue("id", 
                        Guid.NewGuid().ToString());
                        cmd.Parameters.AddWithValue("firstname", 
                        author.FirstName);
                        cmd.Parameters.AddWithValue("lastname", 
                        author.LastName);
                        cmd.Parameters.AddWithValue("address", author.Address);

                        if (pgSqlConnection.State != 
                        System.Data.ConnectionState.Open)
                            pgSqlConnection.Open();
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch
            {
                throw;
            }
        }
    }

Create the AuthorController Class

Next, select and right-click on the Controllers solution folder and create a new controller class called AuthorController with the following code in there:

[Route("api/[controller]")]
    [ApiController]
    public class AuthorController : ControllerBase
    {
        private readonly IAuthorRepository _authorRepository;
        public AuthorController(IAuthorRepository authorRepository)
        {
            _authorRepository = authorRepository;
        }

        [HttpGet]
        public List<Author> Get()
        {
            return _authorRepository.GetAuthors();
        }

        [HttpPost]
        public void Post([FromBody] Author author)
        {
            _authorRepository.Save(author);
        }
    }

Note how an instance of type IAuthorRepository is injected into the constructor of the AuthorController class.

Remember that you must add an instance of type IAuthorRepository to the services container using the following piece of code in the Program.cs file:

builder.Services.AddScoped<IAuthorRepository, AuthorRepository>();

Create the Client Application to Consume the RESTful API

Now create a console application to consume the RESTful API using RESTSharp.

Install NuGet Packages

To take advantage of RestSharp, you should install the RestSharp package in your project. You can install them either from the NuGet Package Manager tool inside Visual Studio or, from the NuGet Package Manager console using the following commands:

PM> Install-Package RestSharp

Once RestSharp has been successfully installed in your project, you can start using the library. First off, you should create an instance of RestClient and pass the base address of the Url in the constructor as shown in the following code:

RestClient client = new RestClient("http://localhost:5073/api/");

Now, create an instance of the RestRequest class as shown in the code given below:

RestRequest request = new RestRequest("Author", Method.Get);

Lastly, you can now call the Execute method using the instance of RestClient and retrieve data using the following code:

var response = client.Execute<List<Author>>(request);

Here’s the complete code listing of the client app:

using RestSharp;
using System;
using System.Collections.Generic;

namespace RESTSharpClient
{
    class Program
    {
        private static RestClient client = new
        RestClient("http://localhost:5073/api/");
        static void Main(string[] args)
        {
		RestRequest request = new RestRequest("Author", Method.GET);
		var response = client.Execute<List<Author>>(request);
           Console.ReadKey();
        }
    }
}

To make Post requests, you can use the following code:

Author author = new Author();
var request = new RestRequest("api/author")
              .AddJsonBody(author);
var response = await client.ExecutePostAsync<Author>(request);

if (!response.IsSuccessful)
{
    //Write code here to handle errors
}

Summary

RestSharp can be used in any .NET application that needs to interact with web services. RESTSharp is a lightweight alternative to WebClient in cases where you need more control over how the request passes through your pipeline. It has full support for the HTTP specification and allows you to easily interact with any RESTful web service endpoint.

RELATED ARTICLES

Whitepaper

Social

Topics

Products