- Joined
- Nov 20, 2017
- Posts
- 261
- Solutions
- 1
- Reaction
- 29
- Points
- 137
C# Rest API Client sample code for login using HttpClient and IHttpClientFactory given login (post method) credentials (API key, username, password)
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
public class ApiClient
{
private readonly IHttpClientFactory _clientFactory;
public ApiClient(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public async Task<string> LoginAsync(string apiKey, string username, string password)
{
var request = new
{
ApiKey = apiKey,
Username = username,
Password = password
};
var client = _clientFactory.CreateClient();
var jsonRequest = JsonSerializer.Serialize(request);
var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.example.com/login", content);
if (response.IsSuccessStatusCode)
{
var jsonResponse = await response.Content.ReadAsStringAsync();
return jsonResponse;
}
else
{
throw new HttpRequestException($"Failed to login. Status code: {response.StatusCode}");
}
}
}
// Usage
public class Program
{
public static async Task Main()
{
var clientFactory = new HttpClientFactory();
var apiClient = new ApiClient(clientFactory);
string apiKey = "your_api_key";
string username = "your_username";
string password = "your_password";
try
{
var response = await apiClient.LoginAsync(apiKey, username, password);
Console.WriteLine(response);
}
catch (HttpRequestException ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
ApiClient
class is responsible for making the API call to the login endpoint using HttpClient.LoginAsync
method takes the API key, username, and password as input, serializes them into a JSON object, prepares the request content, and sends a POST request to the login endpoint.Program
class demonstrates how to use the ApiClient
by creating an instance, providing the credentials, and calling the LoginAsync
method to perform the login operation."https://api.example.com/login"
with the actual login endpoint URL."your_api_key"
, "your_username"
, and "your_password"
with the actual API key, username, and password values.