Connecting To A Remote Database in Xamarin Forms

A common question, especially for those new to Xamarin, who may be coming from a web background, is how do I connect to a remote database from my mobile app? Working with a client application is different than a server based application, as you don’t have direct access to any server based resources, such as a database. In this case, you need a way to accept requests from a client and pass them on to a database.

REST based API

The most common way to achieve this, is via a REST based API. An API is like a webpage, but instead of a user viewing it and seeing HTML, a mobile application or other client, connects to it, sends it commands and receives data back from it, most commonly JSON formatted data.

A REST API allows you to make HTTP calls to it, and receive data back. For example, we could send

GET https://api.domain.com/v1/products/1

This might return something similar to this

{
    "id": "91D87ACA-3C91-4AC2-A806-C82B074DD7C9",
    "name": "Xamarin Monkey"
}

When you want to add data, you use a POST request, and send data in the body of the request.

POST https://api.domain.com/v1/products

{
    "name": "Xamarin Shirt"
}

If you want to see how to create an API and database in Azure, have a look at

If you want to read up more on REST API’s and how they work, take a look at Representational state transfer or use a search engine to search for more articles or videos.

HttpClient

Assuming you have followed the above articles or already have an API, now lets look at how we would connect to that database from Xamarin.

Note: HttpClient is designed to be reused, hence create one instance of HttpClient and reuse it, in your app.

If we want to make a GET request, we would use:

var uri = "https://api.domain.com/v1/products/1";

HttpClient client = new HttpClient();
var response = await client.GetAsync(uri);

If we want to make a POST request we would use:

var uri = "https://api.domain.com/v1/products";
var content = new StringContent("{\"name:\":\"Xamarin Shirt\"}");
HttpClient client = new HttpClient();
var response = await client.PostAsync(uri, content);

And if we want to add a header, such as an authentication header, we could do:

client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "my_access_token");

client.Headers.Add("key", "value"); // For any other types of headers.

Using JSON.NET, we can also easily convert a JSON response, into an object. Lets say the API returns this JSON:

{
    "id": "91D87ACA-3C91-4AC2-A806-C82B074DD7C9",
    "name": "Xamarin Monkey"
}

We then create this model in our Xamarin project.

public class Product
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

Then, when we receive a response from the API, we use JSON.NET to convert it to the object.

var product = JsonConvert.Deserialize<Product>(response.Content);

As you saw when I did a POST above, I typed out the string. If you want to convert a model/object to a JSON string, we can also use JSON.NET to do this as well.

var product = new Product() { Name = "Xamarin Shirt" };
var json = JsonConvert.Serialize(product);

Why Not Directly Connect To A Database?

You may be wondering why you couldn’t just connect directly to a database from your mobile app? The main reasons are:

Security

You don’t want your mobile client apps to have a database connection string with a username and password in it. It opens your database up to anyone. You can create a user with read only permissions and only allow access to certain tables, but they could still see all data in these tables. On an API, you can implement additional security checks and have authentication based on OAuth or an existing user management system.

Performance

Database connections weren’t designed to go over high latency connections. It is likely your database connection would keep dropping, forcing you to reconnect every time.

Control

With an API you can control the flow of data to and from your database. You can implement rate limiting, and monitoring of all of your requests. If you need to change business logic, or even what database or resources are used via each API request, you can do this on the server, without having to redeploy a mobile app.

Resources

With an API, you reduce the need for server resources. While you may have to setup another server to handle an API, the REST API is designed to be stateless and efficient. Scaling to many users in the future is easier with an API.

Microsoft MVP | Xamarin MVP | Xamarin Certified Developer |
Exrin MVVM Framework | Xamarin Forms Developer | Melbourne, Australia

Related Posts

Leave A Comment?