Refit Library Introduction and Setup In .NET

Dilakshan Antony Thevathas
4 min readFeb 21, 2023
Refit Library Introduction and Setup In .NET || AT Dilakshan || Dilakshan Antony Thevathas
Refit Library Introduction and Setup In .NET

Introduction

In a distributed system, it is common to have different microservices that communicate with each other over a network. One way to implement this communication is through RESTful APIs, which allow services to exchange data in a standardized way. However, consuming RESTful APIs can be a cumbersome process, requiring a lot of boilerplate code for making HTTP requests and handling responses. This is where Refit comes in — a type-safe HTTP client library for .NET that simplifies the process of consuming RESTful APIs.

In this article, we will show how to use Refit in a .NET solution to consume multiple APIs and integrate the results.

What is Refit?

Refit is a .NET package used to create type-safe, dynamic, and HTTP-based APIs. It enables programmers to create clear, simple code to use RESTful APIs.

Refit is built on top of the .NET HttpClient library, giving a simpler and more expressive interface for making HTTP requests.

Refit vs HttpClient

Refit vs HttpClient || Refit Library Introduction and Setup In .NET || AT Dilakshan || Dilakshan Antony Thevathas
Refit vs HttpClient

Refit

Provides a type-safe way to define an API using C# interfaces.

Generates a concrete implementation of an API interface at runtime.

Allows developers to define expected input and output types for each API endpoint.

Supports automatic serialization and deserialization of data.

Includes support for interceptors, allowing modification or logging of HTTP requests and responses.

Reduces the amount of boilerplate code required to work with an API.

HttpClient

Requires manually constructing HTTP requests.

Requires handling responses and deserializing JSON data manually.

Does not provide a built-in way to handle pagination, authentication, or other common features.

Requires manually handling serialization and deserialization of JSON data.

Does not provide a built-in way to intercept and modify HTTP requests and responses.

Can be verbose and repetitive when working with APIs.

Installation

Using the NuGet package manager console within Visual Studio run the following command:

NuGet\Install-Package Refit -Version 6.3.2

Goto NuGet package manager and Install Refit Package.

Setup

Example

We need some dependencies to run this example.

Refit

Refit.HttpClientFactory

In this example, we have a .NET solution that consists of three projects: StudentsProj.API, SubjectsProj.API, and StudentSubjectProj.API exposes RESTful APIs that allow you to retrieve data about students and subjects, respectively.

StudentSubjectProj.API is a project that depends on the other two projects and needs to consume their APIs to retrieve data about students and subjects and integrate them.

Solution architecture

The solution architecture is as follows:

Folder Structure || Refit Library Introduction and Setup In .NET || AT Dilakshan || Dilakshan Antony Thevathas
Folder Structure

The solution is structured into three projects: StudentsProj.API, SubjectsProj.API, and StudentSubjectProj.API.

The StudentsProj.API and SubjectsProj.API projects are responsible for managing students and subjects data, respectively.

The StudentSubjectProj.API project acts as an aggregator, providing a unified API to retrieve information about both students and subjects.

ISubjectsApiClient.cs (StudentSubjectProj.API → Clients)

using Refit;
using StudentSubjectProj.API.Models;

namespace StudentSubjectProj.API.Clients
{
public interface ISubjectsApiClient
{
[Get("/subjects")] // "/subjects" is endpoint of get all subjects in SubjectsProj.API Project
Task<IEnumerable<Subjects>> GetAllSubjects();
}
}

IStudentsApiClient.cs (StudentSubjectProj.API → Clients)

using Refit;
using StudentSubjectProj.API.Models;

namespace StudentSubjectProj.API.Clients
{
public interface IStudentsApiClient
{
[Get("/students")] // "/students" is endpoint of get all students in StudentsProj.API Project
Task<IEnumerable<Students>> GetAllStudents();
}
}

StudentSubjectRepository.cs (StudentSubjectProj.API → Repositories)

using StudentSubjectProj.API.Clients;
using StudentSubjectProj.API.Models;

namespace StudentSubjectProj.API.Repositories
{
public class StudentSubjectRepository : IStudentSubjectRepository
{
private readonly IStudentsApiClient studentsApiClient;
private readonly ISubjectsApiClient subjectsApiClient;

public StudentSubjectRepository(IStudentsApiClient studentsApiClient, ISubjectsApiClient subjectsApiClient)
{
this.studentsApiClient = studentsApiClient;
this.subjectsApiClient = subjectsApiClient;
}
public Task<IEnumerable<Students>> GetAllStudentsAsync()
{
return studentsApiClient.GetAllStudents();
}
public Task<IEnumerable<Subjects>> GetAllSubjectsAsync()
{
return subjectsApiClient.GetAllSubjects();
}
}
}

The StudentSubjectProj.API project has a StudentSubjectRepository class that depends on the IStudentsApiClient and ISubjectsApiClient interfaces.

These interfaces are defined in the StudentSubjectProj.API.Clients namespace and specify the endpoints to retrieve data from the StudentsProj.API and SubjectsProj.API projects.

The StudentSubjectRepository class uses the Refit library to generate the implementation of these interfaces, which enables it to make HTTP requests to the endpoints specified in the interfaces.

Program.cs (StudentSubjectProj.API)

using Refit;
using StudentSubjectProj.API.Clients;

... // other contents

// Set base URL for Refit -- StudentsProj.API
string studentsBaseUrl = "https://localhost:7183";
builder.Services.AddScoped<IStudentsApiClient>(x => RestService.For<IStudentsApiClient>(studentsBaseUrl));

// Set base URL for Refit -- SubjectsProj.API
string subjectsBaseUrl = "https://localhost:7021";
builder.Services.AddScoped<ISubjectsApiClient>(x => RestService.For<ISubjectsApiClient>(subjectsBaseUrl));

... // other contents

var app = builder.Build();

... // other contents

In the Program.cs file of the StudentSubjectProj.API project, the base URLs for the StudentsProj.API and SubjectsProj.API projects are set using the AddScoped method of the IServiceCollection interface.

The base URLs are then passed to the RestService.For method of the Refit library, which generates the implementations of the IStudentsApiClient and ISubjectsApiClient interfaces.

By using Refit, the StudentSubjectProj.API project can make HTTP requests to the StudentsProj.API and SubjectsProj.API projects without having to manually manage the HTTP request and response objects. This simplifies the code and makes it more readable.

In addition to simplifying the code, using Refit also provides other benefits.

For example, it automatically deserializes JSON responses into C# objects, which can save time and effort when working with APIs.

Refit also provides a strongly typed API, which can help catch errors at compile-time instead of at runtime.

Overall, using Refit can be a great way to simplify the code and make it more maintainable when working with APIs.

If you enjoy my content, please consider buying me a coffee to support my work: https://www.buymeacoffee.com/atdilakshan

--

--

Dilakshan Antony Thevathas

Hi! I'm Dilakshan. I'm a Software Engineer, and I believe in the great power of technology. My portfolio: https://atdilakshan.github.io/