Consuming a RestApi with Refit & Xamarin.Forms

In this article, we will see together how to make a call to an Api Rest.
A very common action, and therefore very often used. So to do things right, I will show you how to use the Nuget Refit

Setting up the nuget(s)

At first, we download, obviously, the nuget Refit.

If you want to know more about Refit :
The automatic type-safe REST library for .NET Core, Xamarin and .NET.
Heavily inspired by Square’s Retrofit library, Refit turns your REST API into a live interface.

github.com/reactiveui/refit

Tip: If it is not already done, think of installing the nuget Newtonsoft.Json, it will be useful


Setting up our model(s)

Step 1 – Select an API

Now that the nuget is ready, i need an API.
For this example, i will be using FreeToGame Api.

We’ll have access to the API through this link freetogame.com/api/

Api is selected, let get the json and create our model.

Step 2 – Transform json to models.cs

Firstly we’ll get the list of games.

[
  {
    "id": 1,
    "title": "Dauntless",
    "thumbnail": "https://www.freetogame.com/g/1/thumbnail.jpg",
    "short_description": "A free-to-play, co-op action RPG with gameplay similar to Monster Hunter.",
    "game_url": "https://www.freetogame.com/open/dauntless",
    "genre": "MMORPG",
    "platform": "PC (Windows)",
    "publisher": "Phoenix Labs",
    "developer": "Phoenix Labs, Iron Galaxy",
    "release_date": "2019-05-21",
    "freetogame_profile_url": "https://www.freetogame.com/dauntless"
  },
  {
    "id": 2,
    "title": "World of Tanks",
    "thumbnail": "https://www.freetogame.com/g/2/thumbnail.jpg",
    "short_description": "If you like blowing up tanks, with a quick and intense game style you will love this game!",
    "game_url": "https://www.freetogame.com/open/world-of-tanks",
    "genre": "Shooter",
    "platform": "PC (Windows)",
    "publisher": "Wargaming",
    "developer": "Wargaming",
    "release_date": "2011-04-12",
    "freetogame_profile_url": "https://www.freetogame.com/world-of-tanks"
  },

(...)

To transform it into a model usable in my solution, I will use the tool QuickType.

Paste the json , and get your model ! That’s all !

Now you just have to create the new class FreeToPlayGameModel.cs in your solution.

Setting up our service

Nuget ✅

Model ✅

It’s time to create our service.

Inside the Services folder, we will create an interface IFreeToPlayApi.cs and also a class called BaseFreeToPlayApi.cs.
Our interface will contain the url path to get from the API the list of free to play games. Our Base file will contain BaseUrl of our API.

   public interface IFreeToPlayApi
    {
        [Get("/games?sort-by=alphabetical")]
        Task<List<FreeToPlayGameModel>> GetF2PAsync();
    }
  internal class BaseFreeToPlayApi
    {
        public static string BaseUrl => "https://www.freetogame.com/api";
    }

Creating the code behind

For the rest, it is very simple.
The ui will be in the Main.xaml, a button, a list, some data to display and it’s gone

 public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            button_getf2p.Clicked += Button_getf2p_Clicked; ;
        }

        private async void Button_getf2p_Clicked(object sender, EventArgs e)
        {
            try
            {
                var apiClient = RestService.For<IFreeToPlayApi>(BaseFreeToPlayApi.BaseUrl);
                var listF2P = await apiClient.GetF2PAsync();
                StacklayoutListF2P.ItemsSource = listF2P;
            }

            catch (Exception ex)
            {
                Console.WriteLine("Oups " + ex.Message);
            }
        }
    }
    <StackLayout BackgroundColor="#121212">
        <Button
            x:Name="button_getf2p"
            BackgroundColor="#931F21"
            CornerRadius="10"
            Text="GetList"
            TextColor="#FFFFFF" />
        <CollectionView
            x:Name="StacklayoutListF2P"
            Margin="10"
            x:DataType="models:FreeToPlayGameModel">
            <CollectionView.ItemsLayout>
                <GridItemsLayout
                    HorizontalItemSpacing="10"
                    Orientation="Vertical"
                    Span="2"
                    VerticalItemSpacing="10" />
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Frame
                        Margin="0"
                        Padding="5"
                        HasShadow="True">
                        <Frame.Background>
                            <LinearGradientBrush>
                                <GradientStopCollection>
                                    <GradientStop Offset="0" Color="#22FFFFFF" />
                                    <GradientStop Offset="1" Color="#44FFFFFF" />
                                </GradientStopCollection>
                            </LinearGradientBrush>
                        </Frame.Background>
                        <StackLayout>
                            <Image Source="{Binding Thumbnail}" />
                            <Label Text="{Binding Id, StringFormat='Id :{0}'}" TextColor="White" />
                            <Label Text="{Binding Developer, StringFormat='Developer :{0}'}" TextColor="White" />
                            <Label Text="{Binding Title, StringFormat='Title :{0}'}" TextColor="White" />
                        </StackLayout>
                    </Frame>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </StackLayout>

Result

And so, with Refit we can very easily (and with very little code) consume an api !

Now it’s your turn

You can find the source code of the presented sample on my github.
See you next time ! 👋

2 thoughts on “Consuming a RestApi with Refit & Xamarin.Forms

Leave a Reply

Your email address will not be published.