Consume Any Web API From Within Your C# Applications Using AKSoftware.WebApi Library

Introduction

 
Nowadays, Web API is the main part of each solution we build. We see cloud apps are everywhere and they are a wonderful solution if compared with a normal Windows application and a local SQL Server database. Now, users can access their data anywhere they are, from any device. Web API is the main concept of the cloud applications so clients such as Windows, Android, iOS or web application are just consuming those APIs to access online resources, or creating a new one.
 
In this article, I'm going to show you how to consume any web API and make GET, POST  requests very easily from within your C# client applications (UWP, WPF, WinForms, Xamarin, Unity.....etc.) using AKSoftware.Webapi library from NuGet Packages instead of using an instance of HttpClient class. 
 
I will make a simple .NET Core console application to consume a Products API that I have built already to get a list of products via a GET request and add a new product via a POST request.
 
Here is the GET request's result that the API returns.
 
Consume Any Web API From Within Your C# Applications Using AKSoftware.WebApi Library
 
So, let's get started and see how to access that product and add a new one using AKSoftware.WebApi:
 
First of all, create a new console application as follows.
 
Consume Any Web API From Within Your C# Applications Using AKSoftware.WebApi Library
 
Then, after creating the project, go to "Manage NuGet Packages" to install the required library.
 
Consume Any Web API From Within Your C# Applications Using AKSoftware.WebApi Library 
 
Consume Any Web API From Within Your C# Applications Using AKSoftware.WebApi Library
 
Now, things are ready and it's the time of coding. Using AKSoftware.WebApi will reduce a huge amount of code in making requests and getting the responses from and to the API as well as serializing and deserializing objects from C# objects into JSON objects and vice versa. 
 
In the beginning, we should create the models we need. In our example, we need a Product class that has the same properties that the JSON result has in addition to another class. We will call it ProductsResponse because the result of the GET request that we have doesn't return a collection of Products directly. It returns an object that has two properties - one called Count that holds the number of products that the GET returned and the second property is called Products which is an array of Products. So we will create these two classes as below.
  1. public class Product  
  2. {  
  3.   
  4.        public int ID { getset; }  
  5.   
  6.        public string Name { getset; }  
  7.   
  8.        public string Description { getset; }  
  9.   
  10.        public decimal Price { getset; }  
  11.   
  12.        public DateTime ProductionDate { getset; }  
  13.   
  14. }  
and the other class is called ProductResponse.
  1. public class ProductResponse  
  2. {  
  3.   
  4.         public int Count { getset; }  
  5.   
  6.         public Product[] Products { getset; }  
  7.   
  8. }  
The class's properties must be the same properties in the JSON result, otherwise, you will need to serialize and deserialize the objects manually. 
 
Now, we are ready to access the results. So, go to the program.cs file and add the following namespaces.
  1. using System.Threading.Tasks;  
  2. using AKSoftware.WebApi.Client;   
Then, let's make a GET request to get all the products and print them in our Console app. We can achieve that by writing the following method (The code is self-explained).
  1. // Create a function that prints all the products   
  2. async static Task getProductsAsync()  
  3. {  
  4.     // Create a new instance of from the service client that will get the products from the API   
  5.     ServiceClient client = new ServiceClient();  
  6.   
  7.     // Send a get request to the API using GetAsync<> method and specify the type that you will receive   
  8.     var response = await client.GetAsync<ProductResponse>("https://localhost:44388/api/products");  
  9.   
  10.     // Iterate over the products in the response and print each ID Name and Price   
  11.     foreach (var item in response.Products)  
  12.     {  
  13.         Console.WriteLine($"-{item.ID} | {item.Name} | {item.Price}");  
  14.     }  
  15. }  
In the previous method, we used the GetAsync<ProductResponse> and passing the URL of the API to get the products, then we iterated over the products array that is existing in the response object to print some details about each product.
 
Now, we will create a post method to make a POST request to our API in order to add a new product.
  1. // Create a method to make a post request to add a new product   
  2. async static Task postProductAsync()  
  3. {  
  4.      // Create a new instance of from the service client that will get the products from the API   
  5.      ServiceClient client = new ServiceClient();  
  6.   
  7.      // Create a new instance from the product class   
  8.      Product product = new Product  
  9.      {  
  10.           ID = 100097,  
  11.           Name = "New Product",  
  12.           Description = "The Description of the product",  
  13.           Price = 85.88m,  
  14.           ProductionDate = new DateTime(2019, 3, 19)  
  15.       };  
  16.   
  17.        // Send the a POST request to the API with our new product   
  18.        var addedProduct = await client.PostAsync<Product>("https://localhost:44388/api/products", product);  
  19.   
  20.        // Check if the producted is added   
  21.        if (addedProduct != null)  
  22.            Console.WriteLine("Product has been added");  
  23.        else  
  24.            Console.WriteLine("Error inserting the product");   
  25. }  
In the method above, we created a new instance from the product class then we made a POST request to our API to insert that product to the database using the PostAsync<Product> and passing the URL of the API as well as the product instance. 
 
After creating the get and post methods, we still need to call those methods from the main method.
  1. static void Main(string[] args)  
  2. {  
  3.        // Call the get method  
  4.        getProductsAsync();  
  5.   
  6.       // call the post method   
  7.        postProductAsync();  
  8.   
  9.        // Just in order to finishing the application before we press any key  
  10.        Console.ReadKey();   
  11. }  
Now our demo is totally ready after debugging this is the result that we got,
 
Consume Any Web API From Within Your C# Applications Using AKSoftware.WebApi Library
 
So, we have got all the products just in a simple function call and we can manipulate them the way we want like calculating the total price or any other processing depending on our project requirements, as well as we have added a new product the same way.
 

Conclusion

 
AKSoftware.WebApi  is very easy to use and it reduces a great number of code lines in order to achieve the communication between your C# client and the Web API that you are dealing with, in addition to what we have mentioned above you can use the same library to make PUT and DELETE request and even calling a protected resources in the API via access token using GetProtected<>, PostProtected<>, PutProtected<> and DeleteProtected<>. 
 
Hope you found it a useful article and got the benefits you want, thanks for reading.


Recommended Free Ebook
Similar Articles