C#, CSharp, Library, Programming, REST

Refit as HTTP client

This post is dedicated to my colleague – Łukasz (his blog in Polish).

Today I would like to introduce Refit library (GitHub repo). It is described as The automatic type-safe REST library for .NET Core, Xamarin and .NET.

In Refit the interface with methods mapped to API actions is declared. I will use HNapi (Hacker News unofficial API). The sample below shows how to add GET requests.

    public interface IHnapi
    {
        [Get("/item/{id}")]
        Task<Item> GetItem(int id);

        [Get("/news?page={pageId}")]
        Task<IEnumerable<Item>> GetPage(int pageId);
    }

Important part is that each method has to return Task or IObservable. If you will not do this then running the app will end with exception.

Create the client is simple:

        this.hnapi = RestService.For<IHnapi>("http://node-hnapi.herokuapp.com/");

So as you can see on this very short example, implementing the client is very simple. The spillover is usage of RestService class which is static.

I was using this solution in multiple projects. It works fine, even in big, complex solutions.

Quality

The documentation is fine. Also- it is up-to-date, so you do not need to worry about that something will not work if you will follow the samples.

Code quality comparison between Flurl and Refit can be found here.

Demo code

Full demo code is available on GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *