{{announcement.body}}
{{announcement.title}}

Working With a REST API Using HttpClient

DZone 's Guide to

Working With a REST API Using HttpClient

In this article, see how to work with a REST API using HttpClient.

· Integration Zone ·
Free Resource

Woman working at a laptop

Introduction

In this article, we will learn how to consume REST API services using HttpClient. It is used for the authentication and authorization of users with LDAP Active Directory

In C#, we can consume a REST API in the following ways:

  • HttpWebRequest or HttpWebResponse
  • WebClient
  • HttpClient
  • RestSharp Classes

The best and most straightforward way to consume a REST API is by using the HttpClient class.

In order to consume a REST API using HttpClient, we can use various methods like:

  • ReadAsAsync
  • PostAsync
  • PutAsync
  • GetAsync
  • SendAsync

In this article, I used HttpClient to consume REST API services. In order to consume RESTful services,  we first need to generate an access token by providing the accessToken URL with a POST request as well as the headers such as API Key, Authorization and Content-Type.

You might also like:  Get Plenty of REST: REST API Tutorials

Here API Key, 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 an encrypted value with Basic as the 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 an "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 to test or generate the access token.

In this article, I am going to use two different methods:

  • EmployeeRegisteration
  • EmployeeSearch

In order to work with the above methods, each method contains a URL endpoint with either GET/PUT/POST/DELETE requests, etc. From the above methods, we have two POST requests: EmployeeRegisteration and EmployeeSearch.

The EmployeeRegisteration method contains headers like Content-type as application/json, API key, 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 it's 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 EmployeeSearch, the headers will be the same, and only the Body with JSON Data changes according to the requirement.

Below is the code to understand the consumption of a REST API using HttpClient.

GenerateAccessToken

Below is the code for the GenerateAccessToken Method.

C#
xxxxxxxxxx
1
89
 
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;   
13
static void Main(string[] args)  
14
        {  
15
            Program prm = new Program();  
16
            prm.InvokeMethod();  
17
              
18
         }  
19
public async void InvokeMethod()  
20
        {  
21
            Task<string> getAccessToken = GenerateAccessToken();  
22
            accessToken = await getAccessToken;  
23
  
24
            Task<EmployeeRegisterationResponse> registerResponse = EmployeeRegistration(accessToken);  
25
            registerUserResponse = await registerResponse;  
26
  
27
            Task<EmployeeSearchResponse> employeeSearchResponse = EmployeeSearch(accessToken);  
28
            empSearchResponse = await employeeSearchResponse;  
29
  
30
            Task<GetSecurityQuestionsResponse> getSecurityResponse = GetSecretQuestions(accessToken);  
31
            getSecurityQueResponse = await getSecurityResponse;  
32
  
33
            Task<GetCountryNamesResponse> getCountryNamesResponse = GetCountryNames(accessToken);  
34
            getCountryResponse = await getCountryNamesResponse;  
35
        }  
36
public async Task<string> GenerateAccessToken()  
37
        {  
38
            AccessTokenResponse token = null;  
39
  
40
            try  
41
            {  
42
                HttpClient client = HeadersForAccessTokenGenerate();  
43
                string body = "grant_type=client_credentials&scope=public";  
44
                client.BaseAddress = new Uri(accessTokenURL);  
45
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);  
46
                request.Content = new StringContent(body,  
47
                                                    Encoding.UTF8,  
48
                                                    "application/x-www-form-urlencoded");//CONTENT-TYPE header  
49
  
50
                List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();  
51
  
52
                postData.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));  
53
                postData.Add(new KeyValuePair<string, string>("scope", "public"));  
54
  
55
                request.Content = new FormUrlEncodedContent(postData);  
56
HttpResponseMessage tokenResponse = client.PostAsync(baseUrl, new FormUrlEncodedContent(postData)).Result;  
57
  
58
                //var token = tokenResponse.Content.ReadAsStringAsync().Result;    
59
                token = await tokenResponse.Content.ReadAsAsync<AccessTokenResponse>(new[] { new JsonMediaTypeFormatter() });  
60
            }  
61
  
62
  
63
            catch (HttpRequestException ex)  
64
            {  
65
                throw ex;  
66
            }  
67
            return token != null ? token.AccessToken : null;  
68
  
69
        }  
70
private HttpClient HeadersForAccessTokenGenerate()  
71
        {  
72
            HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = false };  
73
            HttpClient client = new HttpClient(handler);  
74
            try  
75
            {  
76
                client.BaseAddress = new Uri(baseUrl);  
77
                client.DefaultRequestHeaders.Accept.Clear();  
78
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));  
79
                client.DefaultRequestHeaders.Add("apikey", apikey);  
80
                client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(  
81
                         System.Text.ASCIIEncoding.ASCII.GetBytes(  
82
                            $"{clientId}:{clientSecret}")));  
83
            }  
84
            catch (Exception ex)  
85
            {  
86
                throw ex;  
87
            }  
88
            return client;  
89
        }  


EmployeeRegistration

Below is the code for EmployeeRegistration Method.

C#
xxxxxxxxxx
1
58
 
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
        }  
25
private HttpClient Method_Headers(string accessToken, string endpointURL)  
26
       {  
27
           HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = false };  
28
           HttpClient client = new HttpClient(handler);  
29
  
30
           try  
31
           {  
32
               client.BaseAddress = new Uri(endpointURL);  
33
               client.DefaultRequestHeaders.Accept.Clear();  
34
               client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
35
               client.DefaultRequestHeaders.Add("apikey", apikey);  
36
               client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);  
37
           }  
38
           catch (Exception ex)  
39
           {  
40
               throw ex;  
41
           }  
42
           return client;  
43
       }  
44
private string RegisterUserJson(string userName, string password, string firstName, string lastName, string emailAddress)  
45
       {  
46
           registerUserJSON =  
47
               "{"  
48
                      + "\"RegisterUserInfo\": {"  
49
                      + "\"username\": \"" + userName + "\","  
50
                      + "\"password\": \"" + password + "\","  
51
                      + "\"firstName\": \"" + firstName + "\","  
52
                      + "\"lastName\": \"" + lastName + "\","  
53
                      + "\"emailAddress\": \"" + emailAddress + "\","  
54
               + "},"  
55
       }";  
56
  
57
           return registerUserJSON;  
58
       }  


EmployeeSearch

Below is the code for EmployeeSearch Method.

C#
xxxxxxxxxx
1
55
 
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
       }  
26
private HttpClient Method_Headers(string accessToken, string endpointURL)  
27
       {  
28
           HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = false };  
29
           HttpClient client = new HttpClient(handler);  
30
  
31
           try  
32
           {  
33
               client.BaseAddress = new Uri(endpointURL);  
34
               client.DefaultRequestHeaders.Accept.Clear();  
35
               client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
36
               client.DefaultRequestHeaders.Add("apikey", apikey);  
37
               client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);  
38
           }  
39
           catch (Exception ex)  
40
           {  
41
               throw ex;  
42
           }  
43
           return client;  
44
       }  
45
private string SearchUserJson(string username, string application)  
46
        {  
47
            searchUserJson =  
48
            "{"  
49
                    + "\"searchUserFilter\": {"  
50
                    + "\"username\" : \"" + username + "\","  
51
                     
52
                  + "},"  
53
                 } ";  
54
            return searchUserJson;  
55
        } 


Thanks, and I hope this helps you!

Further Reading

A Few Great Ways to Consume RESTful APIs in C#

Invoking HTTP REST APIs With a Single Line of C# Code

Topics:
rest api ,integration ,httpclient ,consume rest api ,post ,postman

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}