top of page

Consume Web API with C# HttpClientFactory

Updated: Jun 12, 2022



Sometimes we need to integrate an external API into our code even as a backend service and not just the frontend integrating with the UI components.

We may need to modify such data before it is presented or do some bits of filtering or whatever we want as long as it’s in the scope of access we have to such third-party web APIs.

HttpClient is an already made library in .Net that makes this task easy to achieve without having to do many configurations or setups to start consuming Web APIs.

Let’s have a walkthrough on a simple use case.

I have used a free API endpoint in my case https://api.publicapis.org/entries No keys are needed.

Ready for use and integration, you can also use it for testing in your case or simply google for other free APIs that you can use if you just want something different.

However, This is more than sufficient for this tutorial.

You can start off by creating a simple ASP.Net Core Web API project


Create an API project

Give your project a name

You can choose 5.0 so we don’t have to manually plug-in swagger for testing


Open the Web API link and copy everything like this


Navigate back to Visual Studio and Create a Models Folder in your API Project and add a C# Class

Go to Edit -> Paste Special -> Paste JSON as classes

All the models for that API should be generated for you once that is done.

You should have a RootObject for your main model which you’ll be using, You can rename that to what suits you. I renamed mine to DataModel


API Model



Create the extra folders and C# Classes and Interface that would be needed


Interface



Using IHttpClientFactory


Why not use HttpClient? HttpClient is intended to be instantiated once and reused throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads.

Why use IHttpClientFactory? HttpClientFactory provides you with HttpClient objects but takes responsibility for managing the resources that the clients can use up. Think of it as “connection pooling for Web Services.


Service Implementation


First, we call the endpoint by initializing the HttpRequestMessage Object and passing the necessary parameters which HttpMethod.Get to specify we want to get data just like we’ll do in a regular API Controller. and set the result to an HttpResponse.

If the status code is 200, that means we got data back.

Then we use the ReadFromJsonAsync method which is from the System.Net.Http.Json Namespace to format the response without having to use JsonConvert to deserialize the object result.

Then we return the data.

Add the D.I Services

Here we add Dependency Injection


Controller





Let’s test


Here goes our data


You can get the source code here https://github.com/JiboGithub/HttpClientWebApp




Source: Medium


The Tech Platform

0 comments

Σχόλια


bottom of page