How to call the web API interface using restsharp

Time:2021-9-7

Rest is byRepresentational State TransferThese three word prefixes are synthesized. This architecture style is particularly popular in previous years. The behavior specification of restful API can be referred to: https://docs.microsoft.com/en… Generally, the formats returned by the restful API are the common plurantext, JSON and XML formats.

Restsharp is an open source HTTP client class library, which is very convenient to interact with restful services. What’s more, this class library encapsulates the complex details of the request process, and restsharp supports synchronous and asynchronous request modes.

This article will discuss how to use restsharp to request asp.net core services.

Implement defaultcontroller

Open the defaultcontroller.cs file and replace it with the following code.


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);
       }
   }
}

Referring to the defaultcontroller class above, you can find that the name of the action method corresponds to get, post, put and delete of HTTP verbs. For simplicity, I use a dictionary to access data. You can test it with a browser, postman or fiddler. Please note that for convenience, I use hard coding in the post method, In the actual scenario, you can generate unique IDs in your own way.

In the next chapter, we will learn how to use restsharp to call the API interface just built.

Installing restsharp

To use restsharp, you can use theNuGet package managerVisual interface for installation, or throughNuGet package manager consoleOn the command line, enter the following command:


Install-Package RestSharp

Using restsharp to call asp.net core API

Once restsharp is successfully referenced to the project, you can use it. First, you need to create a restclient instance. The following code shows how to instantiate and initialize the restclient. Note that the URL in the constructor is configured with a base address. In other words, this is not a complete URL.


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

Next, you can passResource nameandRequest modeTwo parameters to instantiate the restrequest object. The following code shows how to implement it.


RestRequest request = new RestRequest("Default", Method.GET);

Finally, you can execute the request, serialize the returned result, and finally receive it with an appropriate object, just like the following code.


IRestResponse<List<string>> response = client.Execute<List<string>>(request);

The following is a complete code list for 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();
        }
    }
}

If you want to send 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 can be used across multiple. Net platforms, such as Momo, xamain, blazer, etc., which is why it is very popular. Moreover, restsharp supports obtaining results through generic methods. In particular, for more restsharp knowledge, please refer to GitHub: https://github.com/restsharp/…

Translation link: https://www.infoworld.com/art…

More high quality dry goods: see my GitHub: csharpranslate

Recommended Today

Java Engineer Interview Questions

The content covers: Java, mybatis, zookeeper, Dubbo, elasticsearch, memcached, redis, mysql, spring, spring boot, springcloud, rabbitmq, Kafka, Linux, etcMybatis interview questions1. What is mybatis?1. Mybatis is a semi ORM (object relational mapping) framework. It encapsulates JDBC internally. During development, you only need to pay attention to the SQL statement itself, and you don’t need to […]