Consuming a RESTful Web Service in Xamarin Forms using Refit (Part 1)

In Xamarin Forms there are several ways to consume restful web services, could be by using the Microsoft Http Libraries or third party libraries like Refit, RESTSharp, PortableRest, etc.

In this article, I’m going to show you step by step how to interact with a rest api using Refit.

This will be a series of articles covering the following:

  • Part 1: Getting started 
  • Part 2: Structuring your project 
  • Part 3: Structuring your project to consume multiple APIs 

Getting Started

Let’s code Step by Step

1- Install the package

  The first thing we are going to do is to install the Refit Package.

If you are using:

  • Shared project or .NET Standard

  Install the latest version of Refit  (4.0.1 > )

  • PCL

The latest version of Refit (4.0.1) supports .NET Standard, so you will need to install an older version that doesn’t require it, as 2.4.1 or a minor version.

2- Choose an API to consume (Optional)

If you have an API already you can skip this step, but if you just want a test API this article shows some good options https://devlinduldulao.pro/5-public-apis-for-practicing-rest-in-your-xamarin-forms/, for this article will use the second one https://makeup-api.herokuapp.com of this list which basically returns a list of makeup products.

As you can see in the website of this API, the url to consume the makeup list products is http://makeup-api.herokuapp.com/api/v1/products.json?brand=maybelline

Which basically is a GET.

3- Extra project config 

Permissions (Android Only)

In your Android Manifest add the internet permission.

Http cleartext web services (iOS Only)

If you are trying to consume a web service that is a cleartext HTTP, make sure to enable ArbitraryLoads in your Info.plist, check a good reference of how to do it here https://iosdevcenters.blogspot.com/2016/02/transport-security-has-blocked.html.

4-Create an Interface

In our project let’s create a new interface called IMakeUpApi, in this interface, we will add all our API calls, for example:

Let’s analyze what we have here:

In this case, we are going to return a string because we don’t know the structure of the JSON, so we will return a JSON string, in case you know it you can add your object type directly.

Also, as you saw previously the complete URL was http://makeup-api.herokuapp.com/api/v1/products.json?brand=maybelline but I’m just taking the changing part (Relative Url) of this to add it to the interface.

5-Create a method to do the request

As you can see here, I’m using the common part of the URL (Base API URL) as a parameter in the RestService class static method to get an instance that implements our interface internally. After we get this instance we are doing the request by accessing the method we previously defined.

If you put a breakpoint and run your project you will see it returns a JSON with all the products.

6-Create a new model class

We are going to copy this JSON into an online tool to get the C# model class structure, we will use https://jsonutils.com/ (You can use any other tool you want).

Now we are going to create a new class in our project and copy this model.

7-Change the actual returning type (string) for the class type we just created

Note: I’m adding List<MakeUp> instead of just MakeUp because if you check the JSON it is a List.

Now, if you run your project with a breakpoint again you will see the list.  

CONGRATULATIONS!!!

At this point, you have done your first request using refit :), but let’s see what else we can do with it.

– PASSING PARAMETERS 

In Refit there are two ways to pass parameters:

1- Query string

Passing parameters by using query string is really simple, and it can be done dynamically.

For example, as you can see in the URL (http://makeup-api.herokuapp.com/api/v1/products.json?brand=maybelline) of our test API there are some parameters that we can change by in the query string for example brand=maybelline.

So to pass this parameter dynamically using Refit the result would be something like this:

And we will pass the string parameter when doing the request:

2- Body

Passing parameters in request body is almost the same, we can send the request as JSON content and form post.

JSON: We will add a new attribute called [Body] and we will pass the class model (it will deserialize/serialize the JSON to this class internally)

Form post: just add BodySerializationMethod.UrlEncoded

And we will pass the object when doing the request:

Note: This endpoint doesn’t exist in the makeUp API, just made it up to show the concept.

– ADD HEADERS

In Refit there are two ways to add headers:

1- Static

If you have a header that won’t change you can set it static by adding the attribute [Headers] and passing the headers.

2- Dynamic

You will pass it as any another parameter, just make sure to pass the attribute Header next with the header name as value.

And that’s all for now, you can check the full source code here:

https://github.com/CrossGeeks/RefitXamarinFormsSample/tree/Part1-GettingStarted

Happy coding! 🙂

You may also like

17 Comments

  1. My URL is redirected to another URL, and then I do this tutorial. My question is: is it possible to do this redirection with Refit?
    I’ve tried this way:

    On Interface:

    public interface IWebService
    {
    [Get(“/”)]
    Task GetUrl();
    }

    And the fuction:

    async Task CallApi()
    {
    var nsAPI = RestService.For(“http://www.app.mysite.com.br”);

    HttpResponseMessage sugars = await nsAPI.GetUrl();
    }

    I don’t know is if this Get on interface is corrected, because my url didn’t has parameters, it’s only the domain (like this http://www.app.mysite.com.br)

    Anyway this tutorial is great, trank you!

  2. What version of Xamarin.Forms are you using? What happens is that I get errors in compilation when installing Refit

  3. Hi Charlin,

    Thanks for the article. I’ve found it while was looking for some info about real life practice with Xamarin(.Forms) + .NetStandard project (which is not single, but most advisable code sharing option).

    I checked GitHub code linked from the article and found that you used a Shared Project, not .NetStandard, but you probably can shed some light on the current (as of May 2018) state of Xamarin + .NetStandard development.

    What I do is:
    1. Use Visual Studio for Mac 2017 (community) with all the stuff updated from the stable channel
    2. Create new solution using default template: [Multiplatform->App->Forms App] for both iOS and Android with .NetStandard library for shared code
    3. Verify, that the solution is buildable/cleanable (without any errors/warnings)
    4. Add the latest Refit package (it’s 4.4.17 as of now)
    5. Build the solution in Debug mode. Result is:
    4 x MSB3277 warnings
    1 x MSB3276 warning
    1 x MT0109 warning
    (the warnings are mostly about unresolvable conflicts between different versions of Microsoft.CSharp and System.Net.Http)
    6. Archive the solution for publishing in Release mode (e.g. for Android). Result is:
    The same warnings as above plus one MSB4018 error: The “ResolveLibraryProjectImports” task failed unexpectedly.

    So, my questions are:
    – is migration from PCL to .NetStandard still ongoing in the .NET world (and particularly in Xamarin world) which is causing a lot of unresolvable dependencies?
    – is it better to use Shared Project as of now due to above issues (and will Shared Project help in this case)?
    – do you have any other recomendations/suggestions on how to structure brand-new solution for Android+iOS xplat application using Xamarin in 2018?

    Hope my comment isn’t too long 🙂 Looking forward for your reply.

    Thanks in advance,
    Dmitry.

    1. Hi Dmitry, It should work in .Net standard (I did the sample in Shared project, because When I created it there was not .Net standard support for Mac), did you try delete the bin/obj folder before build it?
      Regarding your questions:
      – You should use .Net Standard
      – For structure a new project I recommend you to use a Framework and then structure it based on that framework, in this article I mention some options (https://xamgirl.com/learning-xamarin-forms-personal-recipe/), also in the Prism example I have a sample.

      Maybe I can write an article about Prism + .NetStandard + Refit, let me see if I can do it this week 🙂

  4. i have followed each and every step of yours, but i am not getting any response in the form of JSON. can you please tell me , what should i do ?
    i am getting null in variable in CallApi() ?
    HELP NEEDED !!!

  5. Hi Charlin,

    Thank you for the clarification.

    I managed to compose a solution’s skeleton which produces no warnings/errors at build time and seems to be stable enough.

    The solution contains .NetStandard project, as you suggest. Though, I choose to use Xamarin.Native for certain reasons.

    Also, I did not find a way to use Refit with no warnings at build time. I filed an issue on GitHub (https://github.com/reactiveui/refit/issues/482). There is said, the warning is not an issue, but I choose to use RestSharp for now (keeping Refit in mind, for future usage).

    Finally, one note regarding error MSB4018 (ResolveLibraryProjectImports failed).
    The issue is already reported here https://developercommunity.visualstudio.com/content/problem/248692/archive-for-publishing-fails-for-android-project-a.html
    I found simple workaround: a solution must be built just before archiving for publishing (if it was previously cleaned).

    1. Here is an update regarding Refit.

      Refit 4.4.17 supports .NetStandard1.4 and has a direct dependency on particular version of System.Net.Http. This leads to System.Net.Http versions compatibility issue mentioned above.

      Now, Refit 4.5.6 is released. This version supports .NetStandard2, and there is no direct dependency on System.Net.Http. As a result, it can be used in .NetStandard2 projects without compatibility issues.