In the current age of microservices, we have communication between different processes across a wide variety of hosts and platforms. At other times, we integrate with 3rd party libraries, downloading information and metadata that may be necessary for our current application. On some of those occasions, we need to interact with a REST API.

Wouldn’t it be nice if when interacting with REST APIs, we could allow the compiler to help us out? what if we could create a type safe way of interacting with a REST api, and do away with HttpClient, and other unopinionated abstractions? This is what Refit, “The automatic type-safe REST library for .NET Core, Xamarin, and .NET”, can do for us.

What is Refit?

Refit is essentially a wrapper. It uses the HttpClient, and turns it’s API into an opinionated API. Written by Paul Betts, it is an API that fits exactly your needs. It was heavily inspired by Retrofit; a similar idea for Android and Java.

Let’s take an example. The UK’s food standards agency has a lot of open and public apis for consumption. One such API is the UK food hygiene rating data API. The API allows you to query the local authorities within the area, and their acceptance ratings.

An HttpClient Example

A typical call to this REST API would be:

We could then deserialise this into something like the following:

This could be achieved by using Newtonsoft.Json:

Here we are reading the content of the response as a string. We are then using the JsonConvert class to deserialise the string data into the POCO class “LocalAuthoritiesResult”.

Refit Example

The main problem with the previous code is that the actual request strings are hard coded. Not only that, but the HTTP method of interaction with the api is also signified by a method call.

Refit can make this much simpler and straightforward. It can give you an API that reads well, and is not hiding any details of what you are actually interacting with.

This is the same example as before, but now we have turned out API into a type safe version. To use this API, we would do the following:

Summary

Refit is a fantastic tool to allow you to create interfaces out of your APIs, and consume them at runtime. This is not a new idea, such things as Retrofit have been around for some time.

I think that the simplicity and the quick setup of Refit, along with it’s type safe approach, should be the go to tool for anything concerning REST apis.

Hope this helps.