DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited on

Simplifying HTTP Calls with Refit

Refit is an open-source library for .NET that simplifies creating REST-based HTTP calls. It automatically generates HTTP clients from interfaces, making REST API calls much easier and cleaner. Refit also handles JSON serialization and deserialization and allows adding headers and parameters easily. In this example, we’ll see how to configure Refit to perform a GET request and retrieve data from an API.

Libraries:

To use the Refit library, install the following NuGet package in your project:

Install-Package Refit
Enter fullscreen mode Exit fullscreen mode

Example Code:

using Refit;
using System;
using System.Threading.Tasks;

namespace RefitExample
{
    // Defining the interface that represents the API
    public interface IJsonPlaceholderApi
    {
        [Get("/posts/{id}")]
        Task<Post> GetPostAsync(int id);
    }

    // Class to map the response
    public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            // Creating the API client using Refit
            var apiClient = RestService.For<IJsonPlaceholderApi>("https://jsonplaceholder.typicode.com");

            // Making a GET request to retrieve a post
            var post = await apiClient.GetPostAsync(1);

            // Displaying the data in the console
            Console.WriteLine($"Title: {post.Title}\nContent: {post.Body}");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In this example, we use Refit to define an interface representing the API jsonplaceholder.typicode.com. The interface IJsonPlaceholderApi defines a method GetPostAsync that makes a GET request to the /posts/{id} endpoint. Refit takes care of automatically creating the HTTP client and making the request. In the Main method, we instantiate the API client with RestService.For, make a GET request to retrieve a post, and display the results in the console.

Conclusion:

Refit makes HTTP calls simpler and more intuitive, removing the need to write repetitive code for handling requests. It simplifies integration with REST APIs by offering an interface-driven approach that improves code readability and maintainability.

Source code: GitHub

Top comments (1)

Collapse
 
jangelodev profile image
João Angelo

Hi Juarez Júnior,
Top, thanks for sharing.