Consuming RESTful Services In Xamarin.Forms - Part One

Introduction

In this article, we are going to learn how to consume a RESTful service in Xamarin.Forms PCL application. Xamarin.Forms is used to build cross-platform mobile applications by using C# and XAML.

Targeted Audience

People with basic knowledge of C#, XAML, and the basics of Xamarin.Forms.

If you are going to build your first application, then please read this article before implementing API in your project.

What are RESTful Services?

Representational State Transfer (REST) is an architectural style that specifies constraints such as the uniform interface, that if applied to a web service, induces desirable properties such as performance, scalability, and modifiability that enable services to work best on the Web.

Using RESTful Service in Xamarin.Forms

For this example, we are going to use a fake RESTful service in our application. To use a fake RESTful Service in your application, just search for “JsonPlaceholder” and open the first link.

Link - https://jsonplaceholder.typicode.com/

Now, we have to find an end point to use in our application.

Scroll down on the JSON Placeholder page and you will find the resources.
Xamarin

These are all the end points. You can use them in your application. In this example, we are going to use "/posts" end point. So, click on the link and you will see JSON result. Then, copy the link of the end point to use it in our application.

After hitting the "/posts" end point, you can see the results as shown below.

Xamarin

We are going to use this end point in our application.

Now, we have to convert this JSON into C# class. So, we are going to use an easy way to convert JSON to C# by using “Json2csharp”. Open this link and paste your end point there. You will see that this will automatically generate a C# class from JSON, as shown below.

Xamarin

So, copy the link and class code. We are going to use these in our application. Now, open Visual Studio and make a Xamarin.Forms project.

Now, paste the class code and URL in your xaml.cs file.

Xamarin
In order to consume a web service, you have to add two packages to your project.

Now, add these two packages to every project in the solution.

  • JSON
  • Net.Http 

In order to add these, follow the path:

Right click on solution -> Manage NuGet Package for solution.

Xamarin

Now, search for Newtonsoft.Json, check all the projects and install the package in solution.

Xamarin

Similarly, search for second package “Microsoft.Net.Http” and install it in all projects of the solution.

Xamarin

Now, add the following namespace of packages on top of your xaml.cs file.

  • using System.Net.Http;
  • using Newtonsoft.Json;

Also add a namespace for ObservableCollection which we are using in our project.

  • using Collections.ObjectModel; 

Now, make a simple list on your XAML page. And in this list we will show the list of posts coming from our Service.

XAML

  1. <ListView x:Name="Post_List">  
  2.       <ListView.ItemTemplate>  
  3.           <DataTemplate>  
  4.               <TextCell Text="{Binding title}" Detail="{Binding body}"></TextCell>  
  5.           </DataTemplate>  
  6.       </ListView.ItemTemplate>  
  7.         
  8.   </ListView>  

Here, you see that in XAML we declare a List View and bind its title and body to theText cell of a List View.

Back to xaml.cs file, override on appearing method and write some code to get the list of posts.

Code 

  1. using System.Collections.Generic;  
  2. using System.Net.Http;  
  3. using Xamarin.Forms;  
  4. using Newtonsoft.Json;  
  5. using System.Collections.ObjectModel;  
  6.   
  7. namespace XamarinApp3  
  8. {  
  9.   
  10.     public class Post  
  11.     {  
  12.         public int userId { get; set; }  
  13.         public int id { get; set; }  
  14.         public string title { get; set; }  
  15.         public string body { get; set; }  
  16.     }  
  17.   
  18.   
  19.     public partial class MainPage : ContentPage  
  20.     {  
  21.         private const string url = "https://jsonplaceholder.typicode.com/posts";  
  22.         private HttpClient _Client = new HttpClient();  
  23.         private ObservableCollection<Post> _post;  
  24.   
  25.         public MainPage()  
  26.         {  
  27.               
  28.             InitializeComponent();  
  29.           
  30.         }  
  31.   
  32.         protected override async void OnAppearing()  
  33.         {  
  34.             var content = await _Client.GetStringAsync(url);  
  35.             var post = JsonConvert.DeserializeObject<List<Post>>(content);  
  36.             _post = new ObservableCollection<Post>(post);  
  37.             Post_List.ItemsSource = _post;  
  38.             base.OnAppearing();  
  39.         }  
  40.     }  
  41. }  

Line by line explanation of code

This is the complete code for your xaml.cs file. Here, you see that all the namespaces are added. Class code is also here. We can also make a separate class for post. But for this example, I pasted the class code in this file because we are not using this class in other files.

After the class code, our URL is placed, then the object of HttpClient is made and initialized, and after this, we made an observable collection. This collection is initialized later in on appearing method and is assigned to our list view which is made in our XAML file.

Now, in the appearing Method, we use object of our HttpClient() and pass URL in it. After this, we deserialized the content coming from our request and then initialized our observable collection. After this, we set item source of our list to the observable collection.

Output

Xamarin

Here, you will see the list of posts coming from our Service.

Title and body of all posts are shown.

Note

*In part-II of this article, we’ll continue and learn to add and delete these posts.


Similar Articles