In this article, we will discuss an easy way to call our REST APIs in .NET Core. When we call other APIs in .NET Core, HttpClient will be the first choice. And most of us will create a wrapper to make it easy to use. There are many libraries that are based on HttpClient which help us to call REST APIs.

In this article, I will use WebApiClient.

WebApiClient
WebApiClient is an awesome project which help us to call HTTP(S) APIs. For more information, please visit its GITHUB page,

Here I will use WebApiClient.JIT to demonstrate how to use. Let's begin!

Create Some APIs

Here I use ASP.NET Core WebAPI to creat some RESTful APIs.
    [Route("api/[controller]")] 
    public class PersonsController : Controller 
    { 
        // GET: api/persons 
        [HttpGet] 
        public IEnumerable<Person> Get() 
        { 
            return new List<Person> 
            { 
                new Person{Id = 1 , Name = "stewart"}, 
                new Person{Id = 2 , Name = "peter"} 
            }; 
        } 
     
        // GET api/persons/5 
        [HttpGet("{id}")] 
        public Person Get(int id) 
        { 
            return new Person { Id = id, Name = "name" }; 
        } 
     
        // POST api/persons 
        [HttpPost] 
        public Person Post([FromBody]Person person) 
        { 
            if (person == null) return new Person(); 
     
            return new Person { Id = person.Id, Name = person.Name }; 
        } 
     
        // PUT api/persons/ 
        [HttpPut] 
        public string Put([FromBody]int id) 
        { 
            return $"put {id}"; 
        } 
     
        // DELETE api/persons/5 
        [HttpDelete("{id}")] 
        public string Delete(int id) 
        { 
            return $"del {id}"; 
        } 
    } 


Interface Declaration

Create an interface named IPersonApiClient which inherit from IHttpApiClient.
    public interface IPersonApiClient : IHttpApiClient { } 

Add some methods that need to call APIs.
Every method must have a HTTP attribute that provides the request method and relative URL. The return type should be ITask<T>.
    [HttpGet("/api/persons")]   
    ITask<List<Person>> GetPersonsAsync();   

A request URL can be updated dynamically using replacement blocks and parameters on the method. A replacement block is an alphanumeric string surrounded by { and }.
    [HttpGet("/api/persons/{id}")] 
    ITask<Person> GetPersonAsync(int id); 


When our requst parameters should in request body, we can use some attributes to specify the content, such as JsonContent, FormContent .etc.
    [HttpPost("/api/persons")] 
    ITask<Person> AddPersonAsync([JsonContent]Person person);  


The following code demonstrates the basic usage.
    public interface IPersonApiClient : IHttpApiClient 
    { 
        [HttpGet("/api/persons")] 
        ITask<List<Person>> GetPersonsAsync(); 
     
        [HttpGet("/api/persons/{id}")] 
        ITask<Person> GetPersonAsync(int id); 
     
        [HttpPost("/api/persons")] 
        ITask<Person> AddPersonAsync([JsonContent]Person person); 
     
        [HttpPut("/api/persons")] 
        ITask<string> EditPersonAsync([JsonContent]int id); 
     
        [HttpDelete("/api/persons/{id}")] 
        ITask<string> DeletePersonAsync(int id); 
    } 


The next step is how to retrieve the response of the request.
Retrieving Response

We should create a client first. After creating , what we need to do is call the methods we declared in the interface.

    //specify the config 
    var config = new HttpApiConfig 
    {                 
        HttpHost = new Uri("http://localhost:9999"), 
    }; 
     
    var client = HttpApiClient.Create<IPersonApiClient>(config); 
     
    var persons = await client.GetPersonsAsync(); 
     
    Console.WriteLine("GetPersonsAsync result:"); 
    foreach (var item in persons) 
    { 
        Console.WriteLine($"{item.Id}-{item.Name}"); 
    } 
     
    var person = await client.GetPersonAsync(1000); 
    Console.WriteLine("GetPersonAsync result:"); 
    Console.WriteLine($"{person.Id}-{person.Name}"); 
     
     
    var newPerson = new Person { Id = 999, Name = "999" }; 
    var postResult = await client.AddPersonAsync(newPerson); 
    Console.WriteLine("AddPersonAsync result:"); 
    Console.WriteLine($"{postResult.Id}-{postResult.Name}"); 
     
     
    var editResult = await client.EditPersonAsync(1); 
    Console.WriteLine("EditPersonAsync result:"); 
    Console.WriteLine($"{editResult}"); 
     
    var delResult = await client.DeletePersonAsync(1); 
    Console.WriteLine("DeletePersonAsync result:"); 
    Console.WriteLine($"{delResult}");

HostForLIFE.eu ASP.NET Core 2.2.1 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.