Header Ads

C#.NET: Access GET 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 based on business requirement.

Today, I shall be demonstrating consumption of GET type REST Web API method without any API authorization with and without request query URL parameters using 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 GET Method solution as server side.

Download Now!

Let's begin now.

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

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

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

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

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

                // HTTP GET
                response = await client.GetAsync("api/WebApi").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 GET type REST Web API method without passing any request parameters in the API URL. First I have initialized my base url from ASP.NET MVC - REST Web API GET Method server side solution, secondly, I have initialized content default header as JSON type, at third step I have call the GET type REST Web API and finally, after successfully receiving all data from the server because I am not passing any request query parameter, I have deserialized 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 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) Now, create "GetInfo" method with request query parameters as a Key Value pair string in "Program.cs" file and replace following code in it i.e.

...
        public static async Task<DataTable> GetInfo(string requestParams)
        {
            // Initialization.
            DataTable responseObj = new DataTable();

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

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

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

               // HTTP GET
               response = await client.GetAsync("api/WebApi?" + requestParams).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 again using "HttpClient" library to consume/access GET type REST Web API method and passing request query parameters in the API URL format. First I have initialized my base url from ASP.NET MVC - REST Web API GET Method server side solution, secondly, I have initialized content default header as JSON type, at third step I have combine my request query parameters with the API URL and call the GET type REST Web API and finally, after successfully receiving data base on my request query data, I then deserialize the response into "DataTable" structure in order to map my response data. Know that I have first converted my request query data into Key Value pair and then convert the entire key value pair into string which I have attach with my GET type REST web API.

6) In "Program.cs" file "Main" method write following line of code to call the GET type REST Web API method with and without request query parameters i.e.

...
     // Call REST Web API without parameters.
     DataTable responseObj = Program.GetInfo().Result;
...
     // Initilization.
     List<KeyValuePair<string, string>> allIputParams = new List<KeyValuePair<string, string>>();
     string requestParams = string.Empty;

     // Converting Request Params to Key Value Pair.
     allIputParams.Add(new KeyValuePair<string, string>("salesChannel", "Online"));
     allIputParams.Add(new KeyValuePair<string, string>("priority", "M"));

     // URL Request Query parameters.
     requestParams = new FormUrlEncodedContent(allIputParams).ReadAsStringAsync().Result;

     // Call REST Web API with parameters.
     responseObj = Program.GetInfo(requestParams).Result;
...

In the above lines of code, I am simply calling my GET type REST web API method without passing any request query parameters and store my response as "DataTable" structure. Then I first convert my request query parameters into Key Value pair, then, I convert my request query parameters into string and then finally, I call my GET type REST web API method with input request query data and store my response as "DataTable" structure.
7) If you execute the provided solution, you will be able to see following, but, you will need to execute the ASP.NET MVC - REST Web API GET Method server side solution first i.e.
If you debug the code and look into flowing piece of code then you will see that request query parameters are properly converted for URL parameter passing using key value pair conversion.

Conclusion

In this article, you will learn to consume GET type REST Web API method without any API authorization with and without request query URL parameters using ASP.NET REST Web API platform. You will also learn to utilize "HttpClient" library to consume REST Web APIs, you will learn to convert URL parameters into Key Value pair. You will also learn to call GET type REST web API with and without request query URL parameters and finally, you will learn about desiralizing REST web API response directly into "DataTable" structure.

No comments