Header Ads

C#.NET: Access POST type REST Web API Method

Data communication is one of the most vital component when working on client machines, mostly to access/store sensitive data onto cloud servers. Any method type POST or GET of REST Web API can be used for data communication between client machines and cloud servers base on business requirement.

Today, I shall be demonstrating consumption of POST type REST Web API method without any API authorization using C#.NET Console Application.


Prerequisites:

Following are some prerequisites before you proceed any further in this tutorial:
  1. Understanding of JSON Object Mapper.
  2. Knowledge of REST Web API.
  3. Knowledge of ASP.NET MVC5.
  4. Knowledge of C# Programming.
The example code is being developed in Microsoft Visual Studio 2019 Professional. The sample sales data is taken randomly from the internet. I have used  ASP.NET MVC - REST Web API POST Method solution as server side.

Download Now!

Let's begin now.

1) Create new C#.NET Console Application project and name it "AccessPostRESTWebApi".  
2) Create target JSON object mappers for request/response objects as according to ASP.NET MVC - REST Web API POST Method server side solution.
3) Install "Newtonsoft.Json" & "Microsoft.AspNet.WebApi.Client" NuGet libraries.
4) Create "PostInfo" method in "Program.cs" file and replace following code in it i.e.

...
        public static async Task<DataTable> PostInfo(RequestObj requestObj)
        {
            // Initialization.
            DataTable responseObj = new DataTable();

            // Posting.
            using (var client = new HttpClient())
            {
                // Setting Base address.
                client.BaseAddress = new Uri("https://localhost:44371/");

                // Setting content type.                 
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // Initialization.
                HttpResponseMessage response = new HttpResponseMessage();

               // HTTP POST
               response = await client.PostAsJsonAsync("api/WebApi", requestObj).ConfigureAwait(false);

               // Verification
               if (response.IsSuccessStatusCode)
               {
                  // Reading Response.
                  string result = response.Content.ReadAsStringAsync().Result;
                  responseObj = JsonConvert.DeserializeObject<DataTable>(result);
               }
            }

            return responseObj;
        }
...

In the above code, I am using "HttpClient" library to consume/access POST type REST Web API method. The code is quite straight forward i.e. first I have initialized my base url from ASP.NET MVC - REST Web API POST Method server side solution, secondly, I have initialized content default header as JSON type, at third step I have post my request object and call the POST type REST Web API. Finally, after successfully receiving data base on my request query data, I deserialize the response into my target object mapper. Notice that I have used "DataTable" structure to map my response data. I could have create target complex JSON object mapper then deserialize it, but, instead I have used "DataTable". You can use your either option, since, my response JSON object is complex and I am a lazy person (😁😋) to create complex JSON mapper for my response, so, I simply use "DataTable" structure.

5) In "Program.cs" file "Main" method write following line of code to call the POST type REST Web API method i.e.


...
     // Initialization
     RequestObj requestObj = new RequestObj { Priority = "M", SalesChannel = "online" };

     // Call REST Web API.
     DataTable responseObj = Program.PostInfo(requestObj).Result;
...

In the above lines of code, I am simply calling my POST type REST web API with input request query data and storing my response into as "DataTable" structure.
6) If you execute the provided solution, you will be able to see following i.e.


Conclusion

In this article, you will learn to consume POST type REST Web API method without any API authorization using C#.NET Console Application. You will also learn to utilize "HttpClient" library to consume REST Web APIs and finally, you will learn about desiralizing REST web API response directly into "DataTable" structure.

3 comments: