Working With a REST API Using HttpClient
In this article, see how to work with a REST API using HttpClient.
Join the DZone community and get the full member experience.
Join For Free
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.
xxxxxxxxxx
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;
}
EmployeeRegistration
Below is the code for EmployeeRegistration Method.
xxxxxxxxxx
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;
}
EmployeeSearch
Below is the code for EmployeeSearch Method.
xxxxxxxxxx
public async Task<EmployeeSearchResponse> EmployeeSearch(string accessToken)
{
EmployeeSearchResponse employeeSearchResponse = null;
try
{
string searchUserEndPoint = "https://www.c-sharpcorner.com/Employeesearch";
string username = "KMOIZUDDIN", application = "C# CORNER";
HttpClient client = Method_Headers(accessToken, searchUserEndPoint);
string searchUserJson = SearchUserJson(username, application);
//client.BaseAddress = new Uri(searchUserEndPoint);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Uri.EscapeUriString(client.BaseAddress.ToString()));
request.Content = new StringContent(searchUserJson, Encoding.UTF8, "application/json");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage tokenResponse = await client.PostAsync(Uri.EscapeUriString(client.BaseAddress.ToString()), request.Content);
if (tokenResponse.IsSuccessStatusCode)
{
employeeSearchResponse = tokenResponse.Content.ReadAsAsync<EmployeeSearchResponse>(new[] { new JsonMediaTypeFormatter() }).Result;
}
}
catch (HttpRequestException ex)
{
}
return employeeSearchResponse;
}
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 SearchUserJson(string username, string application)
{
searchUserJson =
"{"
+ "\"searchUserFilter\": {"
+ "\"username\" : \"" + username + "\","
+ "},"
} ";
return searchUserJson;
}
Thanks, and I hope this helps you!
Further Reading
A Few Great Ways to Consume RESTful APIs in C#
Opinions expressed by DZone contributors are their own.
Comments