At the beginning of my journey using Xamarin.Forms I was a little bit confused about how to start consuming RESTful web services using Xamarin.Forms.
So I wanted to show you a quick way on How to consume a JSON API using Xamarin.Forms
The first step will be to create a new Xamarin.Forms shared project, we are going to be using a free JSON API called fixer which helps us on the process of getting foreign exchange rates.
We are going to display a list of foreign currencies based on a US dollar and for that we are going to use this url:
Before we start coding let me present you a pretty handful web tool so we can create our .NET models based on a JSON object and it is: http://json2csharp.com/ using this tool we are going to get some help on the process.
1.- Create our models based on the JSON object returned, add a new class with this two objects:
2.- Download foreach project (in this case iOS/Android) this 3 packages (Newtonson JSON, SQL.NET PCL and SQLiteNetExtensions ( not necessary ) ):
3.- Add our WebApi, that is going to handle the HTTP request to the JSON API (In this case only a GET method):
4.- The ViewModel that is going to connect the Remote Data with the UI and it is going to notify the UI that we are working on something that we don't know how long is going to take...
5.- Finally the UI, it is a simple ListView with an TextCell binded to our
public List<Currency> CurrencyList that is inside our ViewMode and an Activity Indicator just to let the user know that something is happening.
5.1.- Don't forget to set the BindingContext of the View!
At the end you'll have something like this:
So, What's next?
On the next tutorial I am going to show you how to add a Local Database using SQLite so we can use our small app without using internet connection. Stay tuned!
Please don't hesitate to ask any questions! As always here is the GitHub repository if you need an extra hand:
Subscribe to My two cents on Xamarin
Get the latest posts delivered right to your inbox