DEV Community

Khaja Moizuddin
Khaja Moizuddin

Posted on • Edited on

Consuming RestApi using HttpClient

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.

GenerateAccessToken

Below is the code for the GenerateAccessToken Method.

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 getAccessToken = GenerateAccessToken();  
            accessToken = await getAccessToken;  
  
            Task registerResponse = EmployeeRegistration(accessToken);  
            registerUserResponse = await registerResponse;  
  
            Task employeeSearchResponse = EmployeeSearch(accessToken);  
            empSearchResponse = await employeeSearchResponse;  
  
            Task getSecurityResponse = GetSecretQuestions(accessToken);  
            getSecurityQueResponse = await getSecurityResponse;  
  
            Task getCountryNamesResponse = GetCountryNames(accessToken);  
            getCountryResponse = await getCountryNamesResponse;  
        }  
public async Task 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> postData = new List>();  
  
                postData.Add(new KeyValuePair("grant_type", "client_credentials"));  
                postData.Add(new KeyValuePair("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(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;  
        } 
 
EmployeeRegistration Below is the code for EmployeeRegistration Method.
public async Task 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(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;  
       }  

Thanks & I hope this helps you.

Top comments (0)