What is the best practice to call web api from xamarin forms?

sagarsagar Member ✭✭

Hi, I am working on xamarin forms. Where I need to call WEB API, I know how to call API in xamarin forms, but I want to know what is the best way to call web API. Now I have followed MVVM architecture, I am calling my API in the code-behind file of a particular view, is it correct or I Should call in ViewModel? I want to know what is the best way?

Answers

  • JohnHardmanJohnHardman GBUniversity mod

    @sagar - Assuming that your are passing data between your app and the WebApi (regardless of direction), you are likely to want to do this in a data access layer, which will be utilised by your Model. The View Models should be getting data from the Model and passing data to the Model, rather than calling WebApis. But it all depends on how purist you want to be - many people seem to implement VVM rather than MVVM...

  • amirvenusamirvenus USMember ✭✭✭

    This is what I have learnt based on experience:

    Create a singleton class (a static instance) and put HttpClient in there and reuse as much as required throughout the code.

  • JarvanJarvan Member, Xamarin Team Xamurai

    I am calling my API in the code-behind file of a particular view, is it correct or I Should call in ViewModel?

    Call the api in viewmodel.

    You can try to use refit: https://xamgirl.com/consuming-a-restful-web-service-in-xamarin-forms-using-refit-part-1/

  • PenutButterJellyHeadPenutButterJellyHead USMember ✭✭✭

    I created an api service class to handle all the api calls for my app. That way you could utilize that api service wherever you have an api call and just pass the url as the parameter and return an object. Wherever your code is then calling your api service could then turn that response object into the structure you expect from the api call.

Sign In or Register to comment.