Using WebApiClient To Call REST APIs In .NET Core

Introduction

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,

There are two package of WebApiClient we can find in Nuget.
 
NameDescription
WebApiClient.JITUsing Emit to create the proxy class of http request interface at runtime.
WebApiClient.AOTSupport all platforms, including the platform that requires AOT, inserting proxy class IL instructions from http request interface to output assembly at compile time.

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.
  1. [Route("api/[controller]")]  
  2. public class PersonsController : Controller  
  3. {  
  4.     // GET: api/persons  
  5.     [HttpGet]  
  6.     public IEnumerable<Person> Get()  
  7.     {  
  8.         return new List<Person>  
  9.         {  
  10.             new Person{Id = 1 , Name = "catcher wong"},  
  11.             new Person{Id = 2 , Name = "james"}  
  12.         };  
  13.     }  
  14.   
  15.     // GET api/persons/5  
  16.     [HttpGet("{id}")]  
  17.     public Person Get(int id)  
  18.     {  
  19.         return new Person { Id = id, Name = "name" };  
  20.     }  
  21.   
  22.     // POST api/persons  
  23.     [HttpPost]  
  24.     public Person Post([FromBody]Person person)  
  25.     {  
  26.         if (person == nullreturn new Person();  
  27.   
  28.         return new Person { Id = person.Id, Name = person.Name };  
  29.     }  
  30.   
  31.     // PUT api/persons/  
  32.     [HttpPut]  
  33.     public string Put([FromBody]int id)  
  34.     {  
  35.         return $"put {id}";  
  36.     }  
  37.   
  38.     // DELETE api/persons/5  
  39.     [HttpDelete("{id}")]  
  40.     public string Delete(int id)  
  41.     {  
  42.         return $"del {id}";  
  43.     }  
  44. }  
Interface Declaration

Create an interface named IPersonApiClient which inherit from IHttpApiClient.
  1. 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>.
  1. [HttpGet("/api/persons")]    
  2. 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 }.

  1. [HttpGet("/api/persons/{id}")]  
  2. 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.

  1. [HttpPost("/api/persons")]  
  2. ITask<Person> AddPersonAsync([JsonContent]Person person);   
The following code demonstrates the basic usage.
  1. public interface IPersonApiClient : IHttpApiClient  
  2. {  
  3.     [HttpGet("/api/persons")]  
  4.     ITask<List<Person>> GetPersonsAsync();  
  5.   
  6.     [HttpGet("/api/persons/{id}")]  
  7.     ITask<Person> GetPersonAsync(int id);  
  8.   
  9.     [HttpPost("/api/persons")]  
  10.     ITask<Person> AddPersonAsync([JsonContent]Person person);  
  11.   
  12.     [HttpPut("/api/persons")]  
  13.     ITask<string> EditPersonAsync([JsonContent]int id);  
  14.   
  15.     [HttpDelete("/api/persons/{id}")]  
  16.     ITask<string> DeletePersonAsync(int id);  
  17. }  

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.
  1. //specify the config  
  2. var config = new HttpApiConfig  
  3. {                  
  4.     HttpHost = new Uri("http://localhost:9999"),  
  5. };  
  6.   
  7. var client = HttpApiClient.Create<IPersonApiClient>(config);  
  8.   
  9. var persons = await client.GetPersonsAsync();  
  10.   
  11. Console.WriteLine("GetPersonsAsync result:");  
  12. foreach (var item in persons)  
  13. {  
  14.     Console.WriteLine($"{item.Id}-{item.Name}");  
  15. }  
  16.   
  17. var person = await client.GetPersonAsync(1000);  
  18. Console.WriteLine("GetPersonAsync result:");  
  19. Console.WriteLine($"{person.Id}-{person.Name}");  
  20.   
  21.   
  22. var newPerson = new Person { Id = 999, Name = "999" };  
  23. var postResult = await client.AddPersonAsync(newPerson);  
  24. Console.WriteLine("AddPersonAsync result:");  
  25. Console.WriteLine($"{postResult.Id}-{postResult.Name}");  
  26.   
  27.   
  28. var editResult = await client.EditPersonAsync(1);  
  29. Console.WriteLine("EditPersonAsync result:");  
  30. Console.WriteLine($"{editResult}");  
  31.   
  32. var delResult = await client.DeletePersonAsync(1);  
  33. Console.WriteLine("DeletePersonAsync result:");  
  34. Console.WriteLine($"{delResult}");  
Here is the result,

 

Here is the source code you can find in my github page .
Summary

In this article, I showed you the basic usage of WebApiClient.

I hope this article can help you!