How to use Refit to consume APIs in ASP.NET Core

By FoxLearn 12/31/2024 2:59:41 AM   89
Refit is a powerful library designed to streamline API consumption in .NET, .NET Core, and Xamarin.

It allows you to define API endpoints as C# interfaces, removing the need for manual HTTP request creation and response parsing. By using Refit, developers can make their code cleaner, more efficient, and easier to maintain.

In this guide, we'll implement two applications: a Contact API and a client application to consume this API.

The Contact API will consist of the following components:

  • Contact: A model class representing contact data.
  • IContactRepository: An interface for interacting with the contact repository.
  • ContactRepository: A class implementing the IContactRepository interface to handle data retrieval.
  • ContactsController: An API controller exposing the Contact API to clients.

The client application will use Refit to access the Contact API and display contact records in the console.

What is Refit?

Refit is a type-safe, fast REST library for .NET that simplifies connecting to RESTful web services. It allows you to define REST API operations as C# interfaces, eliminating boilerplate code. Refit automatically handles HTTP requests and responses, making API interactions simpler and more efficient.

With Refit, instead of manually creating HTTP requests, you just define an interface with the necessary API operations, and Refit generates the corresponding HTTP calls for you.

Configuring HTTP Client with Refit

To begin using Refit, configure an HTTP client instance that connects to the API. Refit handles tasks like serializing requests and deserializing responses, minimizing manual code. Here's a comparison of manual HTTP calls versus using Refit:

Manual HTTP Request:

string baseAddress = "http://localhost:59904/";
HttpClient _client = new HttpClient();
_client.BaseAddress = new Uri($"{BaseUrl}");
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await _client.GetAuthors(url);

Using Refit:

string baseAddress = "http://localhost:59904/";
var endpoint = RestService.For<IAuthorService>(baseAddress);
var contacts = await endpoint.GetAuthors();

As seen, Refit simplifies the code by automatically managing the HTTP calls.

Implementing the API in ASP.NET Core

In Visual Studio, create a new ASP.NET Core Web API project targeting .NET 8.0. Ensure that the "Use controllers" box is checked.

Define the Contact Model

public class Contact
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
}

Create the Repository

The ContactRepository stores and retrieves contact data (using a list for simplicity). It implements the IContactRepository interface, which provides methods to get a single contact or all contacts.

public interface IContactRepository
{
    Contact GetContact(int id);
    List<Contact> GetContacts();
}

public class ContactRepository : IContactRepository
{
    private readonly List<Contact> contacts = new List<Contact>
    {
        new Contact { Id = 1, FirstName = "Lucy", LastName = "Hynh", Address = "11/3 ABC Road, Chicago, USA", Phone = "334-7748-533" },
        new Contact { Id = 2, FirstName = "John", LastName = "Smith", Address = "12/1 ABC Road, New York, USA", Phone = "344-2245-654" }
    };

    public Contact GetContact(int id) => contacts.SingleOrDefault(c => c.Id == id);
    public List<Contact> GetContacts() => contacts;
}

Create the API Controller

The controller exposes endpoints to retrieve contact data.

[Route("api/[controller]")]
[ApiController]
public class ContactsController : ControllerBase
{
    private readonly IContactRepository _contactRepository;
    public ContactsController(IContactRepository contactRepository)
    {
        _contactRepository = contactRepository;
    }

    [HttpGet]
    public async Task<List<Contact>> Get() => await Task.FromResult(_contactRepository.GetContacts());

    [HttpGet("{id}")]
    public async Task<Contact> Get(int id) => await Task.FromResult(_contactRepository.GetContact(id));
}

Creating the Client Application

In Visual Studio, create a new Console App project targeting .NET 8.0.

Next, Install the Refit NuGet package using the following command:

PM> Install-Package Refit

Define the interface to interact with the Contact API using Refit annotations.

[Headers("Accept: application/json", "Content-type: application/json")]
public interface IContactService
{
    [Get("/api/contacts")]
    Task<List<Contact>> GetContacts();
}

public class Contact
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
}

In the Program.cs file, use Refit to fetch and display contact data:

string baseAddress = "http://localhost:59904/";
var contactsAPI = RestService.For<IContactService>(baseAddress);
var contacts = await contactsAPI.GetContacts();

foreach (var contact in contacts)
{
    Console.WriteLine($"{contact.Id} | {contact.FirstName} | {contact.LastName}");
}

Run both the API and client applications. The console client will display contact information retrieved from the API.

Refit simplifies consuming REST APIs in .NET applications by automating many tasks and reducing boilerplate code. It works by mapping HTTP operations to C# interfaces, making code cleaner, more maintainable, and easier to work with.