I have partnered with Milan Jovanovic for his course Pragmatic Clean Architecture and you can get 10% discount using my promo code: MUWAS
Empower your coding journey : Learn to confidently craft production-ready apps with the art of Clean Architecture
In today’s newsletter we are going to discuss:
What is Refit client library
How is it different than conventional HTTP client approach
How to use it in .NET 6.0
What is Refit client library
Refit client is a type safe library to make HTTP calls. It lets you define your API calls using C# interfaces.
For me it is fantastic instead of writing a lot of HTTP Client configuration code.
It is available in .NET, NET Core and Xamarin
How is it different than conventional approach
In conventional style we have to first configure HTTP client, setting base address, headers, serialization/deserialization. We write a lot of code for all this.
Refit allows us to do all this with a few lines of code making this experience more clean and less code.
How to use it in .NET 6.0
I have created a WEB API and its controller looks like this:
Let’s add a class library now which will act like a client and then we will communicate with API using Refit.
1/ Installing Refit Nuget Packages
Open Nuget package manager in your project and install Refit
package
2/ Define Interfaces for Communication
After installation of package define your interfaces
This Get
and Post
is coming from Refit, that is all we need to. Let’s see now how to send requests.
3/ Sending Requests to API
We have two ways to call these methods either with RestService
approach as demonstrated in code snippet or we can inject interface as well.
For better testing experience it is recommended to use injection approach because we can mock it.
Let’s see how to register refit service in Program file.
4/ How to add headers
We can add headers in two ways :
Over Interface [ Again and again for each interface]
Using Delegate Handler [ Set them once for all ]
Headers Style:
Delegate Handler Style:
Before moving to delegating handler let’s define our header name and values.
Now we can use it in like this:
Add delegating handler in RefitClent
service:
GitHub Demo Code
Get demo code of Refit Client at this GitHub Repository
I have deleted all of my in-active newsletter subscriber this week, if you are reading this newsletter then press love react just once so I would be sure that you are actively reading my newsletter.
Whenever you’re ready, there are 3 ways I can help you
Promote yourself to 6000+ subscribers by Sponsoring my Newsletter
Become a Patron and get access to 140+ .NET Questions and Answers
Subscribe my YouTube Channel where I would be publishing .NET stuff soon
Special Offers 📢 [ 10% Discount]
Ultimate ASP.NET Core Web API Second Edition - Premium Package
Use this promo code :- 9s6nuez to claim discount