C#.NET - Access POST Type REST Web API Method

Introduction

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

Today, I shall be demonstrating the consumption of POST type REST Web API method without any API authorization using the ASP.NET REST Web API platform.

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.

Let's begin now.

Step 1. Create a new C#.NET Console Application project and name it "AccessPostRESTWebApi".

Step 2. Create target JSON object mappers for request/response objects as according to ASP.NET MVC - REST Web API POST Method server side solution.

Step 3. Install "Newtonsoft.Json" & "Microsoft.AspNet.WebApi.Client" NuGet libraries.

Step 4. Create the "PostInfo" method in the "Program.cs" file and replace  the following code in it4

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

    // Creating an HttpClient instance.
    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 of HttpResponseMessage.
        HttpResponseMessage response = new HttpResponseMessage();

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

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

    return responseObj;
}

In the above code, I am using the "HttpClient" library to consume/access the POST type REST Web API method. The code is quite straightforward; 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 the content default header as JSON type; and in the third step, I have posted my request object and called the POST type REST Web API. Finally, after successfully receiving a database on my request query data, I deserialized the response into my target object mapper. Notice that I have used the "DataTable" structure to map my response data. I could have created a target complex JSON object mapper then deserialized it, but, instead I have used "DataTable". You can use either option, since my response JSON object is complex and I am a lazy person (😁😋), I simply used the "DataTable" structure to create a complex JSON mapper for my response.

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

 // 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 a "DataTable" structure.

Step .6

Conclusion

In this article, you learned to consume the POST type REST Web API method without any API authorization using ASP.NET REST Web API platform. You also learned to utilize the "HttpClient" library to consume REST Web APIs and finally, you learned about desiralizing REST web API response directly into "DataTable" structure.


Similar Articles