How to Use API Design Patterns in Xamarin Forms?

In this blog, we will be going to talk about the web API design pattern in xamarin forms.

If you make an application using xamarin and you need to bind the data in the user side and store the data in the database, then you can call the web API.

To create a xamarin application that consumes web APIs, you need an HTTP Client to send HTTP requests and receive HTTP response.

Liquid Web Managed Word Press

How to create a project and calling the Web API using Xamarin forms?

Step 1: – First create a new project for xamarin to follow the steps below:

  1. First select the cross-platform from the left side menu.
  2. Then select Mobile-app (Xamarin.Forms).
  3. Then select the directory to put the project in location.
  4. After declare the unique name of your project and then click OK.
Fig 1. Create a xamarin project

5. Select the blank template.

6. Selecting your one or more platform depending on your requirement.

7. And then press ok.

Fig 2: Select the template and platform.

Step 2: After creating the project, create three folders for MVVM.

  1. Model
  2. View
  3. ViewModel

1) Model:

Create the class for table and tables property to add in the model folder. Model classes are non-visual classes.

Therefore, the model is often thought of as representing the app’s domain model, which usually includes a knowledge model along with side business and validation logic.

Example of the Model Class:

Class Name:Login.cs

namespace ApiCalling.Model
{
Public class Login
{
Public int L_Id {	get;	set;}
Public string User_Name {get; set;}
Public string Email {	get; set;}
Public string Password {	get; set;}
}
}

View:

There are multiple pages in your mobile application, at that time to store all the design pages in a single folder. This folder name is view folder.

You can easily find out the design page.

Avoid enabling and disabling UI elements within the code-behind. Ensure those view models are responsible for defining logical state changes that affect some aspects of the view’s display, like whether a command is out there, or a sign that an operation is pending.

Therefore, enable and disable UI elements by binding to seem at model properties, rather than enabling and disabling them in code-behind.

Example of View:

View name:Page1.xaml

<?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="ApiCallingWithXamrin.View.Page1">
    <ContentPage.Content>
        <StackLayout>
            <Label Text="Welcome to Xamarin.Forms!"
                VerticalOptions="CenterAndExpand" 
                HorizontalOptions="CenterAndExpand" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

ViewModel:

There are many events, functionality, the method needed in your mobile application. 

In this scenario, you can use this folder. Because you can store all the class you have created the event and implement the method for any control.  

Keep the UI responsive with asynchronous operations. Mobile apps should keep the UI thread unblocked to enhance the user’s perception of performance.

Therefore, within the view model, use asynchronous methods for Input / Output operations and lift events to asynchronously notify views of property changes.

Centralize data conversions in a conversion layer. It’s also possible to use converters as a separate conversion layer that sits between the view model and therefore the view.

This can be necessary, as an example, when data requires special formatting that the view model doesn’t provide.

How to bind ViewModel in the View?

Keep view models and views independent. Specifically, don’t reference view types, like Button and ListView, from view models.

By following the principles outlined here, view models are often tested in isolation, therefore reducing the likelihood of software defects by limiting the scope.

ViewModel binds with a view using the binding context of this code below.

Example:

  public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            this.BindingContext = new MainPageViewModel();
        }
   }

Step 4:

Now install the NuGet Package for managing HTTP requests and managing data.

Follow these steps for adding the Nuget packages below: 

  1. Right-click on solution explorer and select Manage NuGet Packages.
  2. Then First click on the browser and search the NewTonSoft.Json and then install the packages.
Fig 3: Install the packages for HTTP

Step 5:

After installing the packages, you can call Web API using the HTTP method.

There are five methods of HTTP below.

1) GET – This operation is employed to retrieve data from the online service.

2) POST – This operation is employed to make a replacement item of knowledge on the online service.

3) PUT – This operation is employed to update an item of knowledge on the online service.

4) PATCH – This operation is employed to update an item of knowledge on the online service by describing a group of instructions about how the item should be modified. This verb isn’t utilized in the sample application.

5) DELETE – This operation is employed to delete an item of knowledge on the online service.

Note: You can use only public API.

How to call web API using the HTTP Client?

Public async void Registration()
{
var httpclient=new HttpClient();
var response =await httpClient.GetstringAsync(“(API)”);(Call the API and fetch the data)
var registration=JsonConverter.DeserilizeObject<List<Login>>(response);
(Convert the data in Json Formate.)
Listregistration.ItemSource=registration;

}

Example of Web API Calling:

View Page: Newtestpage.xaml

<?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="ApiCallingWithXamrin.View.newtestPage">
    <ContentPage.Content>
        <StackLayout>
            <!-- Place new controls here -->
            <Button Text="Click Me For Api Data" FontSize="20" FontAttributes="Bold" TextColor="Blue"
           HorizontalOptions="Start" Command="{Binding GetData}"
           VerticalOptions="StartAndExpand" />
            <Label Text="Api Data" FontSize="20" FontAttributes="Bold" 
           HorizontalOptions="Start"
           VerticalOptions="StartAndExpand" />
            <ScrollView>
                <ListView ItemSelected="{Binding itemlistbind}"       
                HasUnevenRows="True">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell>
                                <StackLayout Spacing="2" Orientation="Vertical">
                                    <Label Text="{Binding id}" FontSize="18" LineBreakMode="NoWrap" Margin="10,0,0,0"/>
                                    <Label Text="{Binding email}" FontSize="8" LineBreakMode="NoWrap" Margin="10,0,0,0"/>
                                    <Label Text="{Binding first_name}" FontSize="18" LineBreakMode="NoWrap" Margin="10,0,0,0"/>
                                    <Label Text="{Binding last_name}" FontSize="18" LineBreakMode="NoWrap" Margin="10,0,0,0"/>
                                    <Label Text="{Binding avatar}" FontSize="18" LineBreakMode="NoWrap" Margin="10,0,0,0"/>
                                    <BoxView HeightRequest="1" WidthRequest="1" Color="Black"/>
                                </StackLayout>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </ScrollView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

View page class file: newtestfile.cs

Binding the ViewModel class in view using BindingContext.

using ApiCallingWithXamrin.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace ApiCallingWithXamrin.View
{
	[XamlCompilation(XamlCompilationOptions.Compile)]
	public partial class newtestPage : ContentPage
	{
		public newtestPage ()
		{
			InitializeComponent ();
            this.BindingContext = new ApiData();
        }
	}
}

Model class: ListDataModel.cs

All tables and property define in this classes. There are three class and property defined in ListDataModel.cs.

using System;
using System.Collections.Generic;
using System.Text;

namespace ApiCallingWithXamrin.Model
{
    public class Datum
    {
        public int id { get; set; }
        public string email { get; set; }
        public string first_name { get; set; }
        public string last_name { get; set; }
        public string avatar { get; set; }
    }

    public class Ad
    {
        public string company { get; set; }
        public string url { get; set; }
        public string text { get; set; }
    }

    public class ListDataModel
    {
        public int page { get; set; }
        public int per_page { get; set; }
        public int total { get; set; }
        public int total_pages { get; set; }
        public List<Datum> data { get; set; }
        public Ad ad { get; set; }
    }
}

ViewModel class File: ApiDataViewModel.cs

Calling the web API code in this ApiDataViewModel.cs.

using ApiCallingWithXamrin.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net.Http;
using System.Text;
using System.Windows.Input;
using Xamarin.Forms;

namespace ApiCallingWithXamrin.ViewModel
{
    public class ApiDataViewModel :BaseContext
    {
        public ICommand GetData { get; private set; }

        public ApiData()
        {
            GetData = new Command(Data);
        }

       private List<Datum> lstview1;
        public List<Datum> itemlistbind
        {
            get { return lstview1; }
            set { lstview1 = value;OnPropertyChanged(); }
        }
        private async void Data(object obj)
        {
            try
            {
                var httpClient = new HttpClient();
                var response = await httpClient.GetStringAsync("https://reqres.in/api/users?page=2");
                var abc = JsonConvert.DeserializeObject<ListDataModel>(response);
                if (abc != null)
                {

                    itemlistbind = abc.data;
                }
            }catch(Exception e)
            { }
        }
    }
}

Conclusion

We went through a lot here, and most of it was related to the project setup. But the large, big point of all this is often that you simply can invoke web services fairly easily by: using System.Net.Http.HttpClient.

And there are two ways you will get data and quick and straightforward way by using functions directly off of HttpClient and how that gives more functionality by using HttpRequest and HttpResponse in combination with HttpClient.

You Might Like-

Don't miss out!
Learn How to 10X Your Blog Traffic
Invalid email address
Give it a try. You can unsubscribe at any time.

A Seasoned technocrat with years of experience building technical solutions for various industries using Microsoft technologies. Wish sharp understanding and technical acumen, have delivered hundreds of Web, Cloud, Desktop and Mobile solutions and is heading the technical department at Mobile Application Development Company – iFour Technolab Pvt. Ltd.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.