Consuming RestApi using HttpClient
Tags: restapi, consumerestapihttpclient, httpclient
Published: 2020-01-12 10:45:43

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 two different methods as shown below.
EmployeeRegisteration
EmployeeSearch 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.

<b>GenerateAccessToken</b>
 
Below is the code for the GenerateAccessToken Method.   
<pre>
class Program  
    {  
        string clientId = "a1s2d3f4g4h5j6k7l8m9n1b2v3c4";  
        string clientSecret = "z1x2c3v4b4n5m6l1k2j3h4g5f6d7s8";  
        string apikey = "o1i2u3y4t5r6e7w8q9a1s2d3f4g5h6j6k7l8";  
        string createNewUserJson;  
        string searchUserJson;  
        string accessToken;  
        EmployeeRegisterationResponse registerUserResponse = null;  
        EmployeeSearchResponse empSearchResponse = null;  
        GetSecurityQuestionsResponse getSecurityQueResponse = null;  
        GetCountryNamesResponse getCountryResponse = null;   
static void Main(string[] args)  
        {  
            Program prm = new Program();  
            prm.InvokeMethod();  
              
         }  
public async void InvokeMethod()  
        {  
            Task<string> getAccessToken = GenerateAccessToken();  
            accessToken = await getAccessToken;  
  
            Task<EmployeeRegisterationResponse> registerResponse = EmployeeRegistration(accessToken);  
            registerUserResponse = await registerResponse;  
  
            Task<EmployeeSearchResponse> employeeSearchResponse = EmployeeSearch(accessToken);  
            empSearchResponse = await employeeSearchResponse;  
  
            Task<GetSecurityQuestionsResponse> getSecurityResponse = GetSecretQuestions(accessToken);  
            getSecurityQueResponse = await getSecurityResponse;  
  
            Task<GetCountryNamesResponse> getCountryNamesResponse = GetCountryNames(accessToken);  
            getCountryResponse = await getCountryNamesResponse;  
        }  
public async Task<string> GenerateAccessToken()  
        {  
            AccessTokenResponse token = null;  
  
            try  
            {  
                HttpClient client = HeadersForAccessTokenGenerate();  
                string body = "grant_type=client_credentials&scope=public";  
                client.BaseAddress = new Uri(accessTokenURL);  
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);  
                request.Content = new StringContent(body,  
                                                    Encoding.UTF8,  
                                                    "application/x-www-form-urlencoded");//CONTENT-TYPE header  
  
                List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();  
  
                postData.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));  
                postData.Add(new KeyValuePair<string, string>("scope", "public"));  
  
                request.Content = new FormUrlEncodedContent(postData);  
HttpResponseMessage tokenResponse = client.PostAsync(baseUrl, new FormUrlEncodedContent(postData)).Result;  
  
                //var token = tokenResponse.Content.ReadAsStringAsync().Result;    
                token = await tokenResponse.Content.ReadAsAsync<AccessTokenResponse>(new[] { new JsonMediaTypeFormatter() });  
            }  
  
  
            catch (HttpRequestException ex)  
            {  
                throw ex;  
            }  
            return token != null ? token.AccessToken : null;  
  
        }  
private HttpClient HeadersForAccessTokenGenerate()  
        {  
            HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = false };  
            HttpClient client = new HttpClient(handler);  
            try  
            {  
                client.BaseAddress = new Uri(baseUrl);  
                client.DefaultRequestHeaders.Accept.Clear();  
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));  
                client.DefaultRequestHeaders.Add("apikey", apikey);  
                client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(  
                         System.Text.ASCIIEncoding.ASCII.GetBytes(  
                            $"{clientId}:{clientSecret}")));  
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
            return client;  
        } 
 </pre>


<b>EmployeeRegistration</b> 

 
Below is the code for EmployeeRegistration Method. 

<pre>
public async Task<EmployeeRegisterationResponse> EmployeeRegistration(string accessToken)  
        {  
            EmployeeRegisterationResponse employeeRegisterationResponse = null;  
            try  
            {  
                string createEndPointURL = "https://www.c-sharpcorner/registerUsers";  
                string username = "KhajaMoiz", password = "Password", firstname = "Khaja", lastname = "Moizuddin", email = "Khaja.Moizuddin@gmail.com";  
                HttpClient client = Method_Headers(accessToken, createEndPointURL);  
                string registerUserJson = RegisterUserJson(username, password, firstname, lastname, email);  
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Uri.EscapeUriString(client.BaseAddress.ToString()));  
                request.Content = new StringContent(registerUserJson, Encoding.UTF8, "application/json");  
                request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");  
                HttpResponseMessage tokenResponse = client.PostAsync(Uri.EscapeUriString(client.BaseAddress.ToString()), request.Content).Result;  
                if (tokenResponse.IsSuccessStatusCode)  
                {  
                    employeeRegisterationResponse = await tokenResponse.Content.ReadAsAsync<EmployeeRegisterationResponse>(new[] { new JsonMediaTypeFormatter() });  
                }  
            }  
            catch (HttpRequestException ex)  
            {  
  
            }  
            return employeeRegisterationResponse;  
        }  
private HttpClient Method_Headers(string accessToken, string endpointURL)  
       {  
           HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = false };  
           HttpClient client = new HttpClient(handler);  
  
           try  
           {  
               client.BaseAddress = new Uri(endpointURL);  
               client.DefaultRequestHeaders.Accept.Clear();  
               client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
               client.DefaultRequestHeaders.Add("apikey", apikey);  
               client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);  
           }  
           catch (Exception ex)  
           {  
               throw ex;  
           }  
           return client;  
       }  
private string RegisterUserJson(string userName, string password, string firstName, string lastName, string emailAddress)  
       {  
           registerUserJSON =  
               "{"  
                      + "\"RegisterUserInfo\": {"  
                      + "\"username\": \"" + userName + "\","  
                      + "\"password\": \"" + password + "\","  
                      + "\"firstName\": \"" + firstName + "\","  
                      + "\"lastName\": \"" + lastName + "\","  
                      + "\"emailAddress\": \"" + emailAddress + "\","  
               + "},"  
       }";  
  
           return registerUserJSON;  
       }  
</pre>

Thanks & I hope this helps you.