How To Consume RestAPI Using HttpClient In C#

Introduction

 
In this article, we will learn how to Consume RestAPI services using HttpClient. It is used for the Authentication and Authorization of users with LDAP Active Directory.
In C# we can consume RestAPI using the following ways,
  • HttpWebRequest or HttpWebResponse
  • WebClient
  • HttpClient
  • RestSharp Classes etc.
The best and most straightforward way to consume RestAPI is by using the HttpClient class.
 
In order to Consume RestAPI using HttpClient, we can use various methods like
  • ReadAsAsync
  • PostAsync
  • PutAsync
  • GetAsync
  • SendAsync etc. 
In this article, I used HttpClient to Consume RestAPI Services. In order to Consume Restful Services, first of all, we need to generate access token by providing the accessToken URL with a POST request as well as the headers such as apikey, Authorization & Content-Type. Here apikey, ClientID, and Client Secure which will be provided by the service provider, Authorization contains Client ID and Client Secure which can be encoded with Base64String and passed as encrypted value with Basic as prefix and Content-Type should be "application/x-www-form-urlencoded".
 
For example: Authorization = Basic AccessToken
 
In the body, we need to provide grant_type as client_credentials and scope as public with "x-www-form-urlencoded" value.
 
When we execute the POST request by providing all the required details as mentioned above, the access token will be generated.
 
We can use POSTMAN tool to test or generate the access token.
 
In this article, I am going to use four different methods as shown below.
  • EmployeeRegisteration
  • EmployeeSearch
  • GetSecretQuestions
  • GetCountryNames etc. 
In order to work with the above methods, each method contains URL endpoint with either GET/PUT/POST/DELETE requests, etc. From the above methods, we have two POST request and two GET requests, i.e. EmployeeRegisteration & EmployeeSearch are POST request and GetSecretQuestions & GetCountryNames are GET requests.
EmployeeRegisteration method contains headers like Content-type as application/json, apikey, and Authorization.
 
Here Authorization contains the generated token with Bearer as the prefix.
 
For Example Authorization = Bearer AccessToken
 
And we need to pass the Body with the JSON Data as raw.
 
When executed the EmployeeRegisteration method with POST request by providing all the required details or parameters we get the JSON response with 200 OK which means its successful. If it is unsuccessful then we will get different messages like 500 Internal Server Error or 400 Bad Request etc. If it is successful then we will get a JSON response with the complete information.
 
For remaining methods like EmployeeSearch, GetSecretQuestions, GetCountryNames, the headers will be the same only the Body with JSON Data changes according to the requirement.
 
Below is the code to understand the Consumption of RestAPI using HttpClient.
 

GenerateAccessToken

 
Below is the code for the GenerateAccessToken Method.   
  1. class Program  
  2.     {  
  3.         string clientId = "a1s2d3f4g4h5j6k7l8m9n1b2v3c4";  
  4.         string clientSecret = "z1x2c3v4b4n5m6l1k2j3h4g5f6d7s8";  
  5.         string apikey = "o1i2u3y4t5r6e7w8q9a1s2d3f4g5h6j6k7l8";  
  6.         string createNewUserJson;  
  7.         string searchUserJson;  
  8.         string accessToken;  
  9.         EmployeeRegisterationResponse registerUserResponse = null;  
  10.         EmployeeSearchResponse empSearchResponse = null;  
  11.         GetSecurityQuestionsResponse getSecurityQueResponse = null;  
  12.         GetCountryNamesResponse getCountryResponse = null;   
  1. static void Main(string[] args)  
  2.         {  
  3.             Program prm = new Program();  
  4.             prm.InvokeMethod();  
  5.               
  6.          }  
  1. public async void InvokeMethod()  
  2.         {  
  3.             Task<string> getAccessToken = GenerateAccessToken();  
  4.             accessToken = await getAccessToken;  
  5.   
  6.             Task<EmployeeRegisterationResponse> registerResponse = EmployeeRegistration(accessToken);  
  7.             registerUserResponse = await registerResponse;  
  8.   
  9.             Task<EmployeeSearchResponse> employeeSearchResponse = EmployeeSearch(accessToken);  
  10.             empSearchResponse = await employeeSearchResponse;  
  11.   
  12.             Task<GetSecurityQuestionsResponse> getSecurityResponse = GetSecretQuestions(accessToken);  
  13.             getSecurityQueResponse = await getSecurityResponse;  
  14.   
  15.             Task<GetCountryNamesResponse> getCountryNamesResponse = GetCountryNames(accessToken);  
  16.             getCountryResponse = await getCountryNamesResponse;  
  17.         }  
  1. public async Task<string> GenerateAccessToken()  
  2.         {  
  3.             AccessTokenResponse token = null;  
  4.   
  5.             try  
  6.             {  
  7.                 HttpClient client = HeadersForAccessTokenGenerate();  
  8.                 string body = "grant_type=client_credentials&scope=public";  
  9.                 client.BaseAddress = new Uri(accessTokenURL);  
  10.                 HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);  
  11.                 request.Content = new StringContent(body,  
  12.                                                     Encoding.UTF8,  
  13.                                                     "application/x-www-form-urlencoded");//CONTENT-TYPE header  
  14.   
  15.                 List<KeyValuePair<stringstring>> postData = new List<KeyValuePair<stringstring>>();  
  16.   
  17.                 postData.Add(new KeyValuePair<stringstring>("grant_type""client_credentials"));  
  18.                 postData.Add(new KeyValuePair<stringstring>("scope""public"));  
  19.   
  20.                 request.Content = new FormUrlEncodedContent(postData);  
  21. HttpResponseMessage tokenResponse = client.PostAsync(baseUrl, new FormUrlEncodedContent(postData)).Result;  
  22.   
  23.                 //var token = tokenResponse.Content.ReadAsStringAsync().Result;    
  24.                 token = await tokenResponse.Content.ReadAsAsync<AccessTokenResponse>(new[] { new JsonMediaTypeFormatter() });  
  25.             }  
  26.   
  27.   
  28.             catch (HttpRequestException ex)  
  29.             {  
  30.                 throw ex;  
  31.             }  
  32.             return token != null ? token.AccessToken : null;  
  33.   
  34.         }  
  1. private HttpClient HeadersForAccessTokenGenerate()  
  2.         {  
  3.             HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = false };  
  4.             HttpClient client = new HttpClient(handler);  
  5.             try  
  6.             {  
  7.                 client.BaseAddress = new Uri(baseUrl);  
  8.                 client.DefaultRequestHeaders.Accept.Clear();  
  9.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));  
  10.                 client.DefaultRequestHeaders.Add("apikey", apikey);  
  11.                 client.DefaultRequestHeaders.Add("Authorization""Basic " + Convert.ToBase64String(  
  12.                          System.Text.ASCIIEncoding.ASCII.GetBytes(  
  13.                             $"{clientId}:{clientSecret}")));  
  14.             }  
  15.             catch (Exception ex)  
  16.             {  
  17.                 throw ex;  
  18.             }  
  19.             return client;  
  20.         }  
EmployeeRegistration 
 
Below is the code for EmployeeRegistration Method. 
  1. public async Task<EmployeeRegisterationResponse> EmployeeRegistration(string accessToken)  
  2.         {  
  3.             EmployeeRegisterationResponse employeeRegisterationResponse = null;  
  4.             try  
  5.             {  
  6.                 string createEndPointURL = "https://www.c-sharpcorner/registerUsers";  
  7.                 string username = "KhajaMoiz", password = "Password", firstname = "Khaja", lastname = "Moizuddin", email = "Khaja.Moizuddin@gmail.com";  
  8.                 HttpClient client = Method_Headers(accessToken, createEndPointURL);  
  9.                 string registerUserJson = RegisterUserJson(username, password, firstname, lastname, email);  
  10.                 HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Uri.EscapeUriString(client.BaseAddress.ToString()));  
  11.                 request.Content = new StringContent(registerUserJson, Encoding.UTF8, "application/json");  
  12.                 request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");  
  13.                 HttpResponseMessage tokenResponse = client.PostAsync(Uri.EscapeUriString(client.BaseAddress.ToString()), request.Content).Result;  
  14.                 if (tokenResponse.IsSuccessStatusCode)  
  15.                 {  
  16.                     employeeRegisterationResponse = await tokenResponse.Content.ReadAsAsync<EmployeeRegisterationResponse>(new[] { new JsonMediaTypeFormatter() });  
  17.                 }  
  18.             }  
  19.             catch (HttpRequestException ex)  
  20.             {  
  21.   
  22.             }  
  23.             return employeeRegisterationResponse;  
  24.         }  
  1. private HttpClient Method_Headers(string accessToken, string endpointURL)  
  2.        {  
  3.            HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = false };  
  4.            HttpClient client = new HttpClient(handler);  
  5.   
  6.            try  
  7.            {  
  8.                client.BaseAddress = new Uri(endpointURL);  
  9.                client.DefaultRequestHeaders.Accept.Clear();  
  10.                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  11.                client.DefaultRequestHeaders.Add("apikey", apikey);  
  12.                client.DefaultRequestHeaders.Add("Authorization""Bearer " + accessToken);  
  13.            }  
  14.            catch (Exception ex)  
  15.            {  
  16.                throw ex;  
  17.            }  
  18.            return client;  
  19.        }  
  1. private string RegisterUserJson(string userName, string password, string firstName, string lastName, string emailAddress)  
  2.        {  
  3.            registerUserJSON =  
  4.                "{"  
  5.                       + "\"RegisterUserInfo\": {"  
  6.                       + "\"username\": \"" + userName + "\","  
  7.                       + "\"password\": \"" + password + "\","  
  8.                       + "\"firstName\": \"" + firstName + "\","  
  9.                       + "\"lastName\": \"" + lastName + "\","  
  10.                       + "\"emailAddress\": \"" + emailAddress + "\","  
  11.                + "},"  
  12.        }";  
  13.   
  14.            return registerUserJSON;  
  15.        }  
EmployeeSearch
 
Below is the code for EmployeeSearch Method. 
  1. public async Task<EmployeeSearchResponse> EmployeeSearch(string accessToken)  
  2.        {  
  3.            EmployeeSearchResponse employeeSearchResponse = null;  
  4.            try  
  5.            {  
  6.                string searchUserEndPoint = "https://www.c-sharpcorner.com/Employeesearch";  
  7.                string username = "KMOIZUDDIN", application = "C# CORNER";  
  8.                HttpClient client = Method_Headers(accessToken, searchUserEndPoint);  
  9.                string searchUserJson = SearchUserJson(username, application);  
  10.                //client.BaseAddress = new Uri(searchUserEndPoint);  
  11.                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Uri.EscapeUriString(client.BaseAddress.ToString()));  
  12.                request.Content = new StringContent(searchUserJson, Encoding.UTF8, "application/json");  
  13.                request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");  
  14.                HttpResponseMessage tokenResponse = await client.PostAsync(Uri.EscapeUriString(client.BaseAddress.ToString()), request.Content);  
  15.                if (tokenResponse.IsSuccessStatusCode)  
  16.                {  
  17.                    employeeSearchResponse = tokenResponse.Content.ReadAsAsync<EmployeeSearchResponse>(new[] { new JsonMediaTypeFormatter() }).Result;  
  18.                }  
  19.            }  
  20.            catch (HttpRequestException ex)  
  21.            {  
  22.   
  23.            }  
  24.            return employeeSearchResponse;  
  25.        }  
  1. private HttpClient Method_Headers(string accessToken, string endpointURL)  
  2.        {  
  3.            HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = false };  
  4.            HttpClient client = new HttpClient(handler);  
  5.   
  6.            try  
  7.            {  
  8.                client.BaseAddress = new Uri(endpointURL);  
  9.                client.DefaultRequestHeaders.Accept.Clear();  
  10.                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  11.                client.DefaultRequestHeaders.Add("apikey", apikey);  
  12.                client.DefaultRequestHeaders.Add("Authorization""Bearer " + accessToken);  
  13.            }  
  14.            catch (Exception ex)  
  15.            {  
  16.                throw ex;  
  17.            }  
  18.            return client;  
  19.        }  
  1. private string SearchUserJson(string username, string application)  
  2.         {  
  3.             searchUserJson =  
  4.             "{"  
  5.                     + "\"searchUserFilter\": {"  
  6.                     + "\"username\" : \"" + username + "\","  
  7.                      
  8.                   + "},"  
  9.                  } ";  
  10.             return searchUserJson;  
  11.         }  
GetSecretQuestions
 
Below is the code for GetSecretQuestions Method.  
  1. public async Task<GetSecurityQuestionsResponse> GetSecretQuestions(string accessToken)  
  2.       {  
  3.           GetSecurityQuestionsResponse getSecurityQueResponse = null;  
  4.           try  
  5.           {  
  6.               string getSecurityQuestionEndPoint = "https://www.c-sharpcorner.com/secretquestions";  
  7.   
  8.               HttpClient client = Method_Headers(accessToken, getSecurityQuestionEndPoint);  
  9.               //client.BaseAddress = new Uri(searchUserEndPoint);  
  10.               HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, Uri.EscapeUriString(client.BaseAddress.ToString()));  
  11.               //request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");  
  12.               HttpResponseMessage tokenResponse = await client.GetAsync(Uri.EscapeUriString(client.BaseAddress.ToString()));  
  13.               if (tokenResponse.IsSuccessStatusCode)  
  14.               {  
  15.                   getSecurityQueResponse = tokenResponse.Content.ReadAsAsync<GetSecurityQuestionsResponse>(new[] { new JsonMediaTypeFormatter() }).Result;  
  16.               }  
  17.           }  
  18.           catch (HttpRequestException ex)  
  19.           {  
  20.   
  21.           }  
  22.           return getSecurityQueResponse; //  
  23.       }  
  1. private HttpClient Method_Headers(string accessToken, string endpointURL)  
  2.         {  
  3.             HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = false };  
  4.             HttpClient client = new HttpClient(handler);  
  5.   
  6.             try  
  7.             {  
  8.                 client.BaseAddress = new Uri(endpointURL);  
  9.                 client.DefaultRequestHeaders.Accept.Clear();  
  10.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  11.                 client.DefaultRequestHeaders.Add("apikey", apikey);  
  12.                 client.DefaultRequestHeaders.Add("Authorization""Bearer " + accessToken);  
  13.             }  
  14.             catch (Exception ex)  
  15.             {  
  16.                 throw ex;  
  17.             }  
  18.             return client;  
  19.         }  
GetCountryNames
 
Below is the code for GetCountryNames Method.  
  1. public async Task<GetCountryNamesResponse> GetCountryNames(string accessToken)  
  2.         {  
  3.             GetCountryNamesResponse getCountryNamesResponse = null;  
  4.             try  
  5.             {  
  6.                 string getSecurityQuestionEndPoint = "https://www.c-sharpcorner.com/secretquestions";  
  7.   
  8.                 HttpClient client = Method_Headers(accessToken, getSecurityQuestionEndPoint);  
  9.                 //client.BaseAddress = new Uri(searchUserEndPoint);  
  10.                 HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, Uri.EscapeUriString(client.BaseAddress.ToString()));  
  11.                 //request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");  
  12.                 HttpResponseMessage tokenResponse = await client.GetAsync(Uri.EscapeUriString(client.BaseAddress.ToString()));  
  13.                 if (tokenResponse.IsSuccessStatusCode)  
  14.                 {  
  15.                     getCountryNamesResponse = tokenResponse.Content.ReadAsAsync<GetCountryNamesResponse>(new[] { new JsonMediaTypeFormatter() }).Result;  
  16.                 }  
  17.             }  
  18.             catch (HttpRequestException ex)  
  19.             {  
  20.   
  21.             }  
  22.             return getCountryNamesResponse; //GetCountryNames  
  23.         }  
  1. private HttpClient Method_Headers(string accessToken, string endpointURL)  
  2.        {  
  3.            HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = false };  
  4.            HttpClient client = new HttpClient(handler);  
  5.   
  6.            try  
  7.            {  
  8.                client.BaseAddress = new Uri(endpointURL);  
  9.                client.DefaultRequestHeaders.Accept.Clear();  
  10.                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  11.                client.DefaultRequestHeaders.Add("apikey", apikey);  
  12.                client.DefaultRequestHeaders.Add("Authorization""Bearer " + accessToken);  
  13.            }  
  14.            catch (Exception ex)  
  15.            {  
  16.                throw ex;  
  17.            }  
  18.            return client;  
  19.        }  

Conclusion

 
In this article, we learned how to Consume Restful Services using HttpClient.
 
Thanks & I hope this helps you.