As a developer, one of the essential tasks you may undertake is communicating with external APIs, be it REST or any other web service. Refit is a type-safe REST client for .NET Core that makes it easier for you to build robust APIs. In this article, we'll look at what Refit is, how it works, and how you can use it to build APIs.

What is Refit?

Refit is an open-source library that simplifies the process of consuming REST APIs by generating a client-side proxy for you. It allows you to define your RESTful API in an interface and then use this interface to call the API methods. Refit handles the serialization and deserialization of data, and it provides type-safe parameters and responses.

How does Refit work?

Refit uses the System.Net.Http.HttpClient class to make HTTP requests to the API. It creates an implementation of the interface you define that uses HttpClient to make the requests. Refit provides a set of attributes that you can use to specify the HTTP method, the URL, the headers, and the body of the request. Refit then generates the code that maps the attributes to the corresponding HTTP requests.

Refit also uses Newtonsoft.Json or System.Text.Json for serialization and deserialization. You can specify the serializer you want to use by setting the request's content type to application/json or any other supported media type.

How to use Refit?

To use Refit, you need to follow these steps:

  1. Add the Refit NuGet package to your project.
dotnet add package Refit
  1. Define your API interface.
public interface IUserApi { 

[Get("/api/users/{userId}")] 
Task<User> Getr(int userId); 

[Post("/api/users")] 
Task Create([Body] User user); 

[Put("/api/users/{userId}")] 
Task Update(int userId, [Body] User user); 

[Delete("/api/users/{userId}")] 
Task Delete(int userId);
 }
  1. Create an instance of the Refit RestService using the HttpClient and the API interface.
var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddRefitClient<IUserAPI>()
    .ConfigureHttpClient(config =>
    {
        config.BaseAddress = new Uri(Routes.User);
    });

Note: IUserAPI is the interface representing your API methods, and Routes.User is the base URL for your API.

 

  1. Use Dependency injection
 public class MyDIService: IMyDIService
 {
        private readonly IUserAPI _userAPI;
        private readonly ILogger<MyDIService> _logger;

        public MedicalTreatmentService(
            IUserAPI userAPI,
            ILogger<MyDIService> logger)
        {
            _userAPI= userAPI;
            _logger = logger;
        }

...

}
  1. Call the API methods using the API interface.
var user = await api.GetUser(1); 
var newUser = new User { 
FirstName = "John", 
LastName = "Doe", 
Email = "john.doe@example.com"
}; 

await api.CreateUser(newUser); 
var updatedUser = new User { 
Id = 1, FirstName = "John", 
LastName = "Smith", 
Email = "john.smith@example.com", 
}; 
await api.UpdateUser(1, updatedUser); 
await api.DeleteUser(1);

 

Conclusion

Refit is a powerful library that simplifies the process of consuming REST APIs. It provides a type-safe and easy-to-use interface for communicating with external APIs. With Refit, you don't have to worry about the low-level details of HTTP requests and responses. You can focus on building your application and let Refit handle the rest. Try Refit if you're looking for a way to consume REST APIs in .NET Core.

 

List of resources related to Refit and .NET Core:

  1. Refit GitHub Repository

  2. Refit Documentation

  3. Microsoft Docs: Getting Started with Refit

  4. HttpClient in .NET Core

Decor image
Decor image
Decor image