Refit – The Retrofit of .NET

Refit Tutorial - The Retrofit of .NET

Last Updated on September 29, 2023 by Aram

Refit is a REST library in .NET that allows you to handle and manage API calls in a clean way, It leverages the interfaces and attributes at its core that would translate to to RESTful APIs.

With many features including type-safe serializing and mapping for requests and responses, interceptors through delegating handlers, dynamic replacement, swift integration with the HttpClientFactory, simple usage of the interface with Dependency Injection.

Refit is inspired by one of the most popular libraries in Java/Android – Retrofit by Square.

If you are coming from a Java backend or native Android development background, you will surely know how Retrofit revolutionized the API integrations in these technologies.

With the brilliant concept of live interfaces and the simplicity of API building that was brought by Retrofit, henceforth, Refit was born.

With the rising popularity of Refit being inspired by Retrofit, now it is known as the Retrofit of .NET.

Being built on top of .NET Standard, Refit can be used within different technologies under .NET ecosystem.

In this tutorial, we will be using Refit in a windows desktop application to connect to RESTful APIs which we built previously using ASP.NET Core Web API 7

Clone this project from my GitHub Account.

We need to make sure it is being hosted locally side-by-side with the Windows Desktop application, so we can test our Refit implementation with the different endpoints provided by this RESTful API.

You can find the source code for this tutorial under my GitHub account as well.

So let’s start the tutorial to learn Refit in .NET

Create a new project and choose Windows Forms App:

Choose a path and name for the project, then choose .NET 7


Note: .NET 8 will be officially announced in the major Dotnet Conf 2023 event which is taking placing virtually from the 14th until the 16th of November, 2023.

There will be a huge announcements and updates for the whole .NET ecosystem and beyond, so stay tuned for the upcoming big event.


Now let’s get back to our tutorial.

Once you create the project, you should see a new form.

Leave the design part till the end.

Let’s start with building our requests and responses that will be used to communicate with the REST API using Refit

Requests

Create a new folder with name Requests, add the below classes:

LoginRequest

TaskRequest

Responses

Now let’s create a folder for responses and include the below classes in it:

BaseResponse

TaskResponse

TaskResponseWrapper

TokenResponse

Interfaces

One of the key and core features of refit, is the live interfaces.

Why is it live?

Because it allows the use of Refit Attributes to decorate each method to make it match the associated API endpoint.

So you will end up with a rich interface that binds to the API you are trying to connect with.

Refit’s ITasksApi interface

Let’s import the Nuget package for Refit and add the below interface:

As you can see it has different types of endpoints with concise attributes decorating each method.

To have a proper architecture that would adhere to the SOLID principles we will have interfaces as abstractions for the different functions or use cases that we are trying to cover in this tutorial.

So we will have an interface for users and another one for tasks

ITaskService

IUserService

IAuthTokenStore

Services

The services include the implementation for the interfaces

TaskService

UserService

Stores

We will use an Authentication Store to manage the storage and retrieval of token .

To guarantee JWT token security, ideally the store should be connected to the Windows PasswordVault which is a safe place to store credentials , which includes the JWT

But for the sake of this tutorial, however, we will be caching the tokens in memory.

Add the below class to a new folder with name Stores:

AuthTokenStore

Handlers

This is for Refit to intercept the request prior to calling any endpoint, here we will include the authorization header as Bearer and pass the acces token

we will provide the access token from the Authentication store.

Add the below class to the Handlers folder:

AuthHeaderHandler

Program.cs

Here are the different setup details for your program.cs

Note that you will need to import Nuget Packages for Microsoft.Extensions.DependencyInjection and Microsoft.Extensions.Hosting

Also you will need the package Refit.HttpClientFactory to be able to use Retrofit’s Delegating Handler with the HttpClientFactory through DI.

Also take a note when you run the tasks api project, check the port number so you can configure it in the tasks app program.cs, as you can see below:

Forms

Here comes the UI design part, let’s start by designing our forms to make them ready for their code behind.

Create Folder with name Forms, and add the below forms to it:

Login Form

Here is the final design for the login screen

This is the code behind the login form:

Tasks Form

An this is how should the tasks form appear.

And here are the different functions that are bound to the tasks management events:

Your final project folder structure should be like this:

project-folders-structure

Testing the App

Now that we have glued all the pieces together, time has come to test our work

First, as mentioned previously in this tutorial we need to have the TasksApi Project running on localhost

So head to the TasksApi project and let’s make sure it is running:

Now switch back to the tasks app, and hit F5

As a first open for the app, you should see the login screen:

to test the failing part, Enter wrong credentials

Now let’s test the passing part, once you press on Login, you will be redirected to the tasks dashboard screen:

Let’s try to add a task:

And delete a task

Now pressing logout, you will be redirected to the login screen

There you go.

You have learned how to build a very simple desktop application in .NET 7 that swiftly connects to some RESTful APIs, under localhost.

Exercises

Of course this is not the complete app, there are still some components to be enhanced and more functions to be added.

Here are some stuff that you can do to try yourself to complete its functions, improve on it and get your hands dirty with Refit and .NET.

You can integrate with more endpoints, like Update Task and Get User Profile, just follow the same pattern to bind the Refit interface with the new endpoints

You can include silent refresh for access tokens in the AuthHeaderHandler, where you can check the token expiry ahead of time and do a silent refresh, by calling the refresh token endpoint, before the current access token expires.

Currently , the TaksApi doesn’t return the Expiry time with the token response, you can work on including that as well and then in the Tasks App you can retrieve it and validate it.

Also, you might want to look into storing the token response in the PasswordVault,. currently is it being stored in memory, it is not the best experience since each time the app started it will ask the user for credentials to login.

From the PassordVault, you can have a better persistence while ensuring your JWT is securely stored away from the lurking villains!

Summary

In this tutorial we learned how to implement Refit in .NET, we built a very simple tasks management app using Windows Forms, and connected to an existing RESTful APIs built using ASP.NET Core Web API Technology.

We learned how Refit can simplify connecting the client to REST APIs, with the different features like live interfaces and attributes, integration with HttpClientFactory, interceptors through delegating handlers, type-safe auto serializing and mapping to strongly-typed objects.

These are just a few of the amazing features of Refit, you can always explore further.

Make sure to do the above exercises to better understand how Refit is helping you build online services in a simple way.

Links to useful references in the below section.

References

Official Refit documentation on Github

Great read about Refit with Scott Hanselman

This tutorial’s source code

TasksApi source code

TasksApi Project Complete Tutorial

Learn .NET and C#

Here are some tutorials and articles from my blog to help your learn .NET and C#

Your Quick Guide to Pattern Matching in C#

12 Shorthand Operators in C# Every Developer Should Know About

Introduction to .NET Releases And Updates

13 Libraries in ASP.NET Core Every Developer Should Know About

A Quick Guide to Learn ASP.NET Core Web API

Collaborations

I am always open to discuss any protentional opportunities and collaborations.

Check this page to learn more about how we can benefit each other.

Bonus

Sharing with you this wonderful music from the baroque era, where you can lavish your ears with brilliant melodies with the complete 6 Brandenburg Concertos by J.S. Bach

Enjoy your time coding and listening.

One Comment on “Refit – The Retrofit of .NET”

  1. Nice post!
    Just to let any readers know that there’s another tool, built on top of Refit and called Apizr (www.apizr.net), aiming to provide built in management for retry, priority, auth, connectivity, data cache, data map and so on. Everything you said about Refit is still true with Apizr actually, but much more could be done the easy way and without the boilerplate. And yes I’m the owner of it but anyway, it could be good to know 🙂

Leave a Reply