How to consume a RESTful Service in C# with Xamarin

Objective: Consume a RESTful service using C# and XAML in Xamarin with the help of NuGet packages.

You need to know: Basic C#, XAML, and you need to have a little experience with Xamarin.

Let’s begin:

1– Create a new project and replace the MainPage.xaml code with this one:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="**REPLACE THIS WITH THE NAME OF YOUR PROJECT**.MainPage">
	<StackLayout>
		<StackLayout Orientation="Horizontal">
			<Button Text="Add" Clicked="BtnAdd" />
			<Button Text="Delete" Clicked="BtnDelete" HorizontalOptions="EndAndExpand"/>
		</StackLayout>
		<ListView x:Name="LVMain">
			<ListView.ItemTemplate>
				<DataTemplate>
					<TextCell Text="{Binding Title}" />
				</DataTemplate>
			</ListView.ItemTemplate>
		</ListView>
	</StackLayout>
</ContentPage>

2– And the MainPage.xaml.cs code with this one:

using Xamarin.Forms;

namespace **REPLACE THIS WITH THE NAME OF YOUR PROJECT**
{
	public partial class MainPage : ContentPage
	{
		public MainPage()
		{
			InitializeComponent();
		}

		protected override void OnAppearing()
		{
			base.OnAppearing();
		}

		void BtnAdd(object sender, System.EventArgs e)
		{
		}

		void BtnDelete(object sender, System.EventArgs e)
		{
		}
	}

	public class Post 
	{
		public int Id { get; set; }
		public string Title { get; set; }
		public string Body { get; set; }
	}
}

Read the code from both files and put the name of your project where is indicated.

Run the app to make sure there are no problems.

You should see something like this:

 

3- Install the following NuGet packages in the PCL:

-Microsoft.Net.Http

 

-And Newtonsoft.Json

 

4- Add the following at the top of MainPage.xaml.cs

 using System.Collections.Generic; 
using System.Collections.ObjectModel; 
using System.Net.Http; 
using Newtonsoft.Json; 

 

Now it will look like this:

 

5- We are going to use a fake RESTful service from jsonplaceholder.typicode.com, so first we store the endpoint in MainPage.xaml.cs:

private const string URL = "https://jsonplaceholder.typicode.com/posts";

Now we create an instance of HttpClient:

private HttpClient _httpClient = new HttpClient();

And to fill the ListView we create an ObservableCollection:

private ObservableCollection<Post> _posts;

 

Your code should look like this:

 

6- Inside of OnAppearing method add the following code:

protected override async void OnAppearing()
        {
            var content = await _httpClient.GetStringAsync(URL);
            var posts = JsonConvert.DeserializeObject<List<Post>>(content);

            _posts = new ObservableCollection<Post>(posts);
            LVMain.ItemsSource = _posts;

            base.OnAppearing();
        }

(remember to make your method async)

  1. We send a HTTP GET request to the endpoint to get all posts and then we store them in “content”.
  2. We deserialize the string stored in “content” and then we put it in “posts”.
  3. We initialize the ObservableCollection and pass the “posts” object.
  4. We fill the ListView with the ObservableCollection.

Run the app and you should see something like this:

 

7– Inside the BtnAdd method add the following code:

async void BtnAdd(object sender, System.EventArgs e)
        {
            var randomNumber = new Random();
            var post = new Post() { Title = "Post: " + randomNumber.Next()};
            var content = JsonConvert.SerializeObject(post);
            await _httpClient.PostAsync(URL, new StringContent(content));

            _posts.Insert(0, post);
        }

(remember to make your method async)

  1. We create a new Post object.
  2. We serialize it.
  3. We send a HTTP POST request with the new Post object.
  4. We add it in our ListView.

Run the app and you should see something like this:

 

8– For the BtnDelete add the following code:

async void BtnDelete(object sender, System.EventArgs e)
        {
            var post = _posts[0];
            await _httpClient.DeleteAsync(URL + "/" + post.Id);
            _posts.Remove(post);
        }

(remember to make your method async)

  1. We get the first post in our ListView.
  2. We send a HTTP DELETE request for the first post in our ListView.
  3. We delete it from our ListView.

 

Run the app and you should see something like this:

 

Fin.

About the author

AezioX

Programmer


>