Data communication is one of the most vital components when working on
client
machines, mostly to access/store sensitive data onto 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 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:
- Understanding of JSON Object Mapper.
- Knowledge of REST Web API.
- Knowledge of ASP.NET MVC5.
- 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.
Let's begin now.
Step 1
Create new C#.NET Console Application project and name it "AccessGetRESTWebApi".
Step 2
Create target JSON object mappers for request/response objects as according to ASP.NET MVC - REST Web API GET Method server side solution.
Step 3
Install "Newtonsoft.Json" & "Microsoft.AspNet.WebApi.Client" NuGet libraries.
Step 4
Create "GetInfo" method without parameters in "Program.cs" file and replace the following code in it:
- ...
- public static async Task<DataTable> GetInfo()
- {
-
- DataTable responseObj = new DataTable();
-
-
- using (var client = new HttpClient())
- {
-
- client.BaseAddress = new Uri("https://localhost:44334/");
-
-
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
-
-
- HttpResponseMessage response = new HttpResponseMessage();
-
-
- response = await client.GetAsync("api/WebApi").ConfigureAwait(false);
-
-
- if (response.IsSuccessStatusCode)
- {
-
- 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 the third step I have called 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
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 too much of a lazy person (😁😋) to create a complex JSON mapper for my response, so, I simply used "DataTable"
structure.
Step 5
Now, create "GetInfo" method with request query parameters as a Key Value pair string in "Program.cs" file and replace the following code in it:
- ...
- public static async Task<DataTable> GetInfo(string requestParams)
- {
-
- DataTable responseObj = new DataTable();
-
-
- using (var client = new HttpClient())
- {
-
- client.BaseAddress = new Uri("https://localhost:44334/");
-
-
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
-
-
- HttpResponseMessage response = new HttpResponseMessage();
-
-
- response = await client.GetAsync("api/WebApi?" + requestParams).ConfigureAwait(false);
-
-
- if (response.IsSuccessStatusCode)
- {
-
- 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 the third step I have combined my request query
parameters with the API URL and
called the GET type REST Web API and finally, after successfully receiving a database 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 converted the entire key value pair into
string which I have attached with my GET type REST web API.
Step 6
In "Program.cs" file "Main" method write the following line of code to call the GET type REST Web API method with and without request query parameters:
- ...
-
- DataTable responseObj = Program.GetInfo(requestObj).Result;
- ...
-
- List<KeyValuePair<string, string>> allIputParams = new List<KeyValuePair<string, string>>();
- string requestParams = string.Empty;
-
-
- allIputParams.Add(new KeyValuePair<string, string>("salesChannel", "Online"));
- allIputParams.Add(new KeyValuePair<string, string>("priority", "M"));
-
-
- requestParams = new FormUrlEncodedContent(allIputParams).ReadAsStringAsync().Result;
-
-
- 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 storing 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.
Step 7
If you execute the provided solution, you will be able to see the following, but, you will need to execute the ASP.NET MVC - REST Web API GET Method
server side solution first:
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 learned 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 also learned to utilize "HttpClient" library to consume REST Web
APIs, to convert URL parameters into Key Value pair, to call GET type REST web API with and without request
query URL parameters and finally, about desiralizing REST
web API response directly into "DataTable" structure.