Consuming a web API using a typed HttpClient — .NET Core

Cheranga Hatangala
May 19, 2019 · 4 min read
Image for post
Image for post
Image courtesy by

Introduction

In these days, it’s almost impossible to implement a decent system without implementing or consuming a web API.

Alright, so what’s the big deal?

Well, as developers we would like to write beautiful, functioning code. So when we saw HttpClient was implementing IDisposable interface, we used it within an using statements because that’s the sensible (A.K.A — best practice) thing to do. But… boy we were wrong! 😆

Behold..here comes .NET Core 2.1

Well starting from .NET Core 2.1 Microsoft saw this becoming a real problem and introduced HttpClientFactory . As per the name, it’s a factory which we can use to create HttpClient instances without worrying about disposables, DNS changes and all that drama.

Create a class library

Let’s create a class library because in reality we’ll implement this logic in a separate class library. To test the functionality we’ll implement integration tests.

Image for post
Image for post

Install the golden nuggets!

Well not really 😄 but we are going to need the below mentioned nuget libraries.

Create the model class “Todo”

This class is pretty straight forward and simple, you can just create it by just looking at the returned JSON from the API.

Create the service abstraction

We’ll implement the service abstraction as an interface.

Implement the service abstraction

Alright, let’s implement it now.

Register the dependencies

For this I would like to separate the dependency registrations to a separate class called Bootstrapper .

Implement integration tests

Add a test project to the solution and let’s write some integration tests. I am using XUnit as the test framework.

Conclusion

We have now successfully created a service, which actually uses an HttpClient to consume an API. But as earlier we don’t want to worry about all the challenges which we had to deal before.

Cheranga

.NET, .NET Core, C#, ASP.NET Core, Architecture and Design

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store