Forum Xamarin.Forms

Best approach calling API using Refit

PekkachuPekkachu USMember ✭✭

Hi guys

I would like to know what is the best way or most efficient way to consume a RESTful API in a enterprise XF project using Refit.

I have built an existing app before using this way but I am not very proud of the code and I'd like to rewrite it from scratch, with better code and layering all the components, currently I am stuck with the data access layer.

I am using a singleton class where I put my http clients to reuse them, I am also using the native HttpClient (from Android and iOS) inside Xamarin Forms 4.1, is it ok to still keep using OkHttpclient?

I also use PRISM for MVVM and navigation.

Maybe someone has a current project that deals with consuming API using Refit and a good and clean way to use it? All the examples just show the basic usage

var loginService = RestService.For<ILoginService>(_httpClient);

Tagged:

Answers

  • JarvanJarvan Member, Xamarin Team Xamurai

    Tutorial about How to properly consuming REST API using Refit in Xamarin:

    https://medium.com/@shanmugasanthosh/how-to-properly-consuming-rest-api-using-refit-in-xamarin-38848c50b0af

  • ledragonledragon Member ✭✭✭

    @Pekkachu Hi there, Would be interested to know how you went about using a singelton for httpclient. Do you have a repo you could post?

    Thanks in advance

  • PekkachuPekkachu USMember ✭✭
    edited November 2019

    @ledragon said:
    @Pekkachu Hi there, Would be interested to know how you went about using a singelton for httpclient. Do you have a repo you could post?

    Thanks in advance

    @ledragon said:
    @Pekkachu Hi there, Would be interested to know how you went about using a singelton for httpclient. Do you have a repo you could post?

    Thanks in advance

    Hi ledragon, sorry for the late reply

    I am no expert but currently this is the way i approach it

    Inside my singleton class (shortened for example purposes)

    `public sealed class Singleton : BindableBase
    {
    private Singleton ()
    {
    InitData ();
    }

    public static HttpClient ApiClient;
    
    public void GenerateApiHttpClient ()
    {
        ApiClient = new HttpClient ()
        {
            BaseAddress = new Uri (AppSettings.WebApiUri),
            Timeout = TimeSpan.FromSeconds (8)
        };
    
        ApiClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue ("Basic", Convert.ToBase64String (Encoding.UTF8.GetBytes (CREDENTIALS)));
    }
    

    }`

    In production we use 2 HttpClients (one handles Login as it uses a different uri, and the other one handles api calls) but for this example i will use just one

    After we login succesfully we call GenerateApiHttpClient() for the client to initialize using AppSettings data (endpoint and basic auth for the service)

Sign In or Register to comment.