Using RESTSharp for CRUD Operations in ASP.NET Core Web API

RESTSharp is a fantastic library for performing CRUD (Create, Read, Update, Delete) operations within C# applications, especially when dealing with APIs. For this example, I'll demonstrate the usage of RESTSharp for CRUD operations in an ASP.NET Core Web API. I'll break down each operation (POST, PUT, DELETE, GET, PATCH) along with the corresponding code.

Setting Up RESTSharp

Firstly, make sure you have RESTSharp installed in your project. You can install it via NuGet Package Manager or through the Package Manager Console:

Install-Package RestSharp

Configuration

Create a helper class to handle RESTSharp configuration and API calls:

using RestSharp;

namespace ThirdPartyAPIIntegrationRestSharpCRUD.RestSharpHealper
{
    public class RestClientHelper
    {
        private readonly RestClient _client;

        public RestClientHelper(string baseUrl)
        {
            _client = new RestClient(baseUrl);
        }

        public T Execute<T>(RestRequest request) where T : new()
        {
            var response = _client.Execute<T>(request);
            return response.Data;
        }

        public void Execute(RestRequest request)
        {
            _client.Execute(request);
        }
    }
}

Model Class

namespace ThirdPartyAPIIntegrationRestSharpCRUD.Model
{
    public class Article
    {
        public Guid Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string Author { get; set; }
        public string AuthorUrl { get; set; }
        public string Content { get; set; }
    }
}

CRUD Operations


POST Request

[HttpPost(nameof(RestSharpPostRequest))]
public void RestSharpPostRequest(Article article)
{
  var client = new RestClientHelper("https://www.c-sharpcorner.com/articles/");

    var request = new RestRequest("/articles", Method.Post);
     request.AddJsonBody(article);

       client.Execute(request);
}

PUT Request

[HttpPut(nameof(RestSharpUpdateRequest))]
public void RestSharpUpdateRequest(Article article)
{
            var client = new RestClientHelper("https://www.c-sharpcorner.com/articles/");

            var request = new RestRequest($"/articles/{article.Id}", Method.Put);
            request.AddJsonBody(article);

            client.Execute(request);
 }

DELETE Request

[HttpDelete(nameof(RestSharpDeleteRequest))]
public void RestSharpDeleteRequest(int articleId)
{
            var client = new RestClientHelper("https://www.c-sharpcorner.com/articles/");

            var request = new RestRequest($"/articles/{articleId}", Method.Delete);

            client.Execute(request);
}

GET Request

[HttpGet(nameof(RestSharpGetRequest))]
public Article RestSharpGetRequest(int articleId)
{
    var client = new RestClientHelper("https://www.c-sharpcorner.com/articles/");

    var request = new RestRequest($"/articles/{articleId}", Method.Get);

    return client.Execute<Article>(request);
}

PATCH Request

[HttpPatch(nameof(RestSharpPatchRequest))]
public void RestSharpPatchRequest(Article article)
{
    var client = new RestClientHelper("https://www.c-sharpcorner.com/articles/");

    var request = new RestRequest($"/articles/{article.Id}", Method.Patch);
    request.AddJsonBody(new { article.Title, article.Content });
    client.Execute(request);
}

Complete Controller Code

using Microsoft.AspNetCore.Mvc;
using RestSharp;
using ThirdPartyAPIIntegrationRestSharpCRUD.Model;
using ThirdPartyAPIIntegrationRestSharpCRUD.RestSharpHealper;

namespace ThirdPartyAPIIntegrationRestSharpCRUD.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class RestSharpController : ControllerBase
    {
        [HttpPost(nameof(RestSharpPostRequest))]
        public void RestSharpPostRequest(Article article)
        {
            var client = new RestClientHelper("https://www.c-sharpcorner.com/articles/");

            var request = new RestRequest("/articles", Method.Post);
            request.AddJsonBody(article);

            client.Execute(request);
        }


        [HttpPut(nameof(RestSharpUpdateRequest))]
        public void RestSharpUpdateRequest(Article article)
        {
            var client = new RestClientHelper("https://www.c-sharpcorner.com/articles/");

            var request = new RestRequest($"/articles/{article.Id}", Method.Put);
            request.AddJsonBody(article);

            client.Execute(request);
        }


        [HttpDelete(nameof(RestSharpDeleteRequest))]
        public void RestSharpDeleteRequest(int articleId)
        {
            var client = new RestClientHelper("https://www.c-sharpcorner.com/articles/");

            var request = new RestRequest($"/articles/{articleId}", Method.Delete);

            client.Execute(request);
        }


        [HttpGet(nameof(RestSharpGetRequest))]
        public Article RestSharpGetRequest(int articleId)
        {
            var client = new RestClientHelper("https://www.c-sharpcorner.com/articles/");

            var request = new RestRequest($"/articles/{articleId}", Method.Get);

            return client.Execute<Article>(request);
        }


        [HttpPatch(nameof(RestSharpPatchRequest))]
        public void RestSharpPatchRequest(Article article)
        {
            var client = new RestClientHelper("https://www.c-sharpcorner.com/articles/");

            var request = new RestRequest($"/articles/{article.Id}", Method.Patch);
            request.AddJsonBody(new { article.Title, article.Content });

            client.Execute(request);
        }


    }
}

Output

RESTSharp for CRUD Operations in ASP.NET Core Web API

Conclusion

In conclusion, utilizing RESTSharp for CRUD operations in ASP.NET Core Web API offers a streamlined approach to interacting with APIs. This library simplifies HTTP requests and responses, allowing developers to focus on implementing functionality rather than managing low-level HTTP communication.

By breaking down each operation POST, PUT, DELETE, GET, PATCH, and providing corresponding code snippets, the process of creating, retrieving, updating, and deleting resources becomes more accessible. The RestClientHelper class encapsulates RESTSharp configuration, promoting code reusability and maintainability.

However, while RESTSharp offers simplicity and efficiency, it's crucial to handle potential errors, implement validation, and manage exceptions effectively. Robust error handling ensures application stability and a smooth user experience.

Remember, adapt these examples to fit your specific project requirements, replacing placeholders like API URLs and model classes with your actual implementation details.

With RESTSharp, developers can build powerful, API-driven applications in ASP.NET Core Web API, promoting cleaner code and efficient communication with external services.

GitHub Project URL


Similar Articles