Refit

About Refit: the automatic type-safe REST library for .NET Core, Xamarin and .NET.

GitHub Repo stars is one of the most powerful and performant REST client libraries in the .NET ecosystem.

Unlike other widely used libraries, Refit has been using a concept of automatic source code generation of the REST client at development time (build time) for years. This reduces runtime overhead, increases performance and improves reliability.
For this purpose, Refit used to use so-called stubs, but now Refit uses source code generators).

The documentation of Refit is excellent.

Info Link
License GitHub
Downloads Nuget
Latest Version GitHub release (latest by date)
Issues GitHub issues
Contributors GitHub contributors

Samples

Refit uses interfaces to describe a REST API. It uses the information in the interface at build time to generate the REST client using the source code generators.

public interface IMyTaskAPI
{
    [Get("/tasks")]
    Task<List<TaskApiModel>> GetAllTasks();

    [Get("/tasks/{id}")]
    Task<TaskApiModel?> GetTask(int id);

    [Post("/tasks")]
    Task<TaskApiModel> AddTask(TaskApiCreateModel taskModel);

    [Patch("/tasks/{id}")]
    Task<TaskApiModel?> UpdateTask(int id, TaskApiUpdateModel taskModel);

    [Delete("/tasks/{id}")]
    Task<TaskApiModel?> DeleteTask(int id);

    [Put("/tasks/{id}/status/complete")]
    Task<TaskApiModel?> MarkTaskAsCompleted(int id);

    [Put("/tasks/{id}/status/uncomplete")]
    Task<TaskApiModel?> MarkTaskAsUncompleted(int id);

    // Remarks: you can/should add 'CancellationToken cancellationToken = default' to all parameters to support cancellation
}

The generated client then contains the instance methods to communicate with the API. All REST communication, serialization and deserialization is abstracted by Refit.

IMyTaskAPI taskApi = RestService.For<IMyTaskAPI>("my-rest-api.com");

// Get single task
TaskApiModel? task = await taskApi.GetTask(123);

// Get all tasks
List<TaskApiModel> tasks = await taskApi.GetAllTasks();

// add new task
TaskApiCreateModel newTask = new TaskApiCreateModel { Title = "Buy flowers" };
TaskApiModel? addedTask = await taskApi.AddTask(newTask);

Remarks

Refit has a built-in dependency injection support, required package Refit.HttpClientFactory:

services
    .AddRefitClient<IMyTaskAPI>()
    .ConfigureHttpClient(c => c.BaseAddress = new Uri("my-rest-api.com"));
Pros

  • Extremely simple yet powerful REST Client.
  • Extremely efficient through source code generators.
  • Enormously expandable and thus suitable for both very simple and enormously complex scenarios.

Cons

  • Source code generators are considered to be complex (if you have to debug deeper into Refit).
  • An interface is always needed, thus not much but still more than one line of code is necessary.

Full Sample

See the full sample on GitHub: https://github.com/BenjaminAbt/dotnet.rest-samples