An Overview On Named Clients:
- In HttpClientFactory, the Named Clients technique is useful when an application has a requirement to consume multiple external API's.
- In the Named Client approach HttpClienFactory produces the HttpClient object specific to the domain.
- So if our requirement to consume multiple external domains then HttpClientFactory generates HttpClient object per domain based on their registration in a startup.cs file.
- So each external API domain needs to be registered in the startup.cs file with a specific 'Name' to that HttpClient.
- This name will be passed to HttpClientFactory to produce a HttpClient object with the specified configuration in the startup.cs file
- Here we have a configuration object to set time out for the expiration of the HttpClient object.
Click here to learn more about an overview of HttpClientFactory
Basic Implementation Sample On HttpClientFactory Using HttpRequestMessage Object
Test 3rd Party API's:
So to understand and implement a sample on HttpClientFactory using the named technique we need to have external APIs. So were are going to use freely hosted rest APIs for a developer to use and learn like below:
JSONPlaceholder:
https://jsonplaceholder.typicode.com/
Dummy Rest API:
http://dummy.restapiexample.com/
Create A .Net Core Sample:
Let's create a .net core sample web API project that will consume the external APIs. We can use IDE like Visual Studio 2019(VS that supports 3.0 plus .net core) Or Visual Studio Code.
Register Named HttpClients:
- On registering HttpClient will specify a name to the HttpClient. Along with specifying the name of HttpClient, we can also specify some configuration like 'BaseAddress', 'DefaultRequestHeaders', 'DefaultRequestVerion', 'Timeout'.
- 'BaseAddress' means domain of the third-party, API we need to consume, if specify the 'BaseAddress' on registering HttpClient then we no need to specify the domain or fully qualified URL at the Controller on making an API call.
- 'DefaultRequestHeaders' we also can configure any default headers that need to specify on making an API call. If we want we can specify the header in controllers also, but headers will override these 'DefaultRequestHeaders'.
- 'TimeOut' to specify the lifetime of the HttpClient. Means HttpClient will not be destroyed immediately after serving request it will live up to lifetime specified to utilize the server resource efficiently.
Startup.cs:
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddHttpClient("DummyRestApi",(client)=>{ client.BaseAddress = new Uri("http://dummy.restapiexample.com"); }); services.AddHttpClient("JsonPlaceholder",(client) => { client.BaseAddress = new Uri("https://jsonplaceholder.typicode.com"); }); }In the above code snippet, we can observe HttpClient has been registered with names like 'DummyRestApi', 'JsonPacleholder'. Configured both clients with respective API domains.
Inject IHttpClientFactory Service:
To consume System.Net.Http.IHttpClientFactory service we need to inject it. So as the first step let's create a TestController.cs file and inject IHttpClienFactory into it.
Controllers/TestController.cs:
using System.Net.Http; using Microsoft.AspNetCore.Mvc; namespace NamedFacotryApp.Controllers { [ApiController] [Route("[controller]")] public class TestController : ControllerBase { private readonly IHttpClientFactory _httpClientFacotry; public TestController(IHttpClientFactory httpClientFactory) { _httpClientFacotry =httpClientFactory; } } }
Get Action Method:
Now we will create an HttpClient object from HttpClientFactory using registered HttpClient names with the predefined configuration that is in Startup.cs file. Since the domain of external API is already registered in Startup.cs file in the controller level on invoking a specific endpoint, we can provide a relative endpoint as input URL to the HttpRequestMessage object will be enough.
Let's install NewtonSoft.Json Nuget for effective serialization and deserialization of API JSON result.
CLI Command:
dotnet add package Newtonsoft.Json
PackageManager:
Install-Package Newtonsoft.Json
So first let's consume 'DummyRestAPI' and the endpoint looks as below.
So now let's create a model object to capture the JSON result from the external API in the above screenshot.
Now let's create an Employee model object as follows:
Models/Employee.cs:
using Newtonsoft.Json; namespace NamedFacotryApp.Models { public class Employee { [JsonProperty(PropertyName = "id")] public string Id { get; set; } [JsonProperty(PropertyName = "employee_name")] public string EmployeeName { get; set; } [JsonProperty(PropertyName = "employee_salary")] public string EmployeeSalary { get; set; } [JsonProperty(PropertyName = "employee_age")] public string EmplyeeAge { get; set; } [JsonProperty(PropertyName = "profile_image")] public string ProfileImage { get; set; } } }Here we are using Newtonsoft.Json.JsonProperty attribute to match the properties with the external API response.
From the above image, we can observe a collection of employee data reside inside of another result object, so to serialize we need to create a new object that holds a collection of employees like in the image.
Models/DummyResult.cs:
using System.Collections.Generic; using Newtonsoft.Json; namespace NamedFacotryApp.Models { public class DummyResult { [JsonProperty(PropertyName = "status")] public string Status { get; set; } [JsonProperty(PropertyName="data")] public List<Employee> Data { get; set; } } }Now we will see how we can create a HttpClient object from HttpClientFactory using the Named Client technique. Let's create an action method that fetches all employee records as follows:
Controllers/TestController.cs:
using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using NamedFacotryApp.Models; using Newtonsoft.Json; namespace NamedFacotryApp.Controllers { [ApiController] [Route("[controller]")] public class TestController : ControllerBase { private readonly IHttpClientFactory _httpClientFacotry; public TestController(IHttpClientFactory httpClientFactory) { _httpClientFacotry = httpClientFactory; } [HttpGet] [Route("all-employees")] public async Task<IActionResult> GetEmployees() { var request = new HttpRequestMessage(HttpMethod.Get, "/api/v1/employees"); var client = _httpClientFacotry.CreateClient("DummyRestApi"); var response = await client.SendAsync(request); if(!response.IsSuccessStatusCode) { return NoContent(); } var responseString = await response.Content.ReadAsStringAsync(); DummyResult result = JsonConvert.DeserializeObject<DummyResult>(responseString); return Ok(result); } } }
- (Line-26) "DummyRestApi" name of the HttpClient registered at the Startup.cs file. Using the same name we have to create a HttpClient object from the HttpClientFactory service.
- (Line-24) Since we have registered our "DummyRestApi" domain as a configuration in Startup.cs file, here for HttpRequestMessage object passing partial API endpoint is enough. Because this HttpRequestMessage object will be used as an input parameter to the HttpClient object created by the "DummyRestApi" name which contains configurations like domain, default request headers, etc.
- (Line-28) HttpClient object has an asynchronous method name 'SendAsync' which will trigger the API call. This method takes the input parameter as a HttpRequestMessage object which has all the configuration for the API call.
For a better understanding of the named client technique lets create one more get action method that fetches data from 'JsonPalceHolder'(external free API). We will use the 'Post' endpoint from the 'JsonPlaceHolder'.The below image shows the basic idea of the 'Post' endpoint payload.
Let's create a model object that used to deserialize the JSON payload.Models/Post.cs:
namespace NamedFacotryApp.Models { public class Post { public int UserId { get; set; } public int Id { get; set; } public string Title { get; set; } public string Body { get; set; } } }Now let's do the implementation of the get action method for invoking external API call as follows:
Controllers/TestController.cs:
using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using NamedFacotryApp.Models; using Newtonsoft.Json; namespace NamedFacotryApp.Controllers { [ApiController] [Route("[controller]")] public class TestController : ControllerBase { [HttpGet] [Route("user-posts")] public async Task<IActionResult> GetUserPosts() { var request = new HttpRequestMessage(HttpMethod.Get, "/posts"); var client = _httpClientFacotry.CreateClient("JsonPlaceholder"); var response = await client.SendAsync(request); if (!response.IsSuccessStatusCode) { return NoContent(); } var responseString = await response.Content.ReadAsStringAsync(); List<Post> result = JsonConvert.DeserializeObject<List<Post>>(responseString); return Ok(result); } } }(Line-21) Using 'JsonPlaceholder' name value creating the HttpClient object from the HttpClientFactory.
Now let's run the application and checks the output as below:
Hereby observing two endpoints that use the named client technique helps in creating the HttpClient object from the HttpClientFactory services.
Support Me!
Buy Me A Coffee
PayPal Me
Wrapping Up:
Hopefully, I think this article delivered some useful information about the Named Client Technique Of HttpClientFactory. I love to have your feedback, suggestions, and better techniques in the comment section below.
This is great, step by step explanation.
ReplyDelete