Ionic Backends

Integrating a Backend with Ionic



·

I often see questions like “How do I use PHP/MySQL in Ionic?” or “Does Ionic work with X backend?” – these are reasonable questions, but it indicates a big misconception as to how integrating a backend with Ionic works. The technology that is used on the backend is completely irrelevant, as the backend and the Ionic front end exist in totally independent spaces.

Ionic does not integrate directly with your backend, it just communicates with it. In order to enable Ionic to integrate with a backend, your backend will need to implement some kind of API that the Ionic application can make HTTP requests to.

Depending on your background, this particular method of integrating a backend into the front end may be unfamiliar. If we take the example of using PHP and MySQL – in a normal website environment you would likely have various PHP files that handle the front end and the back end, i.e:

  • index.php
  • posts.php
  • profile.php

Within the index.php file you would likely have some code that deals with backend stuff like pulling in some data from a database, and some code that will handle outputting something to the browser:

$mysqli = new mysqli("localhost", "username", "password", "database");
$query = "SELECT * FROM table";
$dbresult = $mysqli->query($query);
 
while($row = $dbresult->fetch_array(MYSQLI_ASSOC)){

	echo $row['name'];

}

It is common to define the HTML for pages directly in the PHP files, so you could have this file render out all of the HTML required for the page, and inject any server side stuff you need right in there as well.

When dealing with client side JavaScript applications like Ionic the same concept does not apply – the backend and the frontend are completely separated.

How Do You Integrate a Backend With Ionic?

The way in which we integrate Ionic with a backend is through HTTP requests. The backend, whatever it is built with, must provide some kind of API that we can interact with through HTTP requests.

Ionic Backend

As the diagram above shows, there is no direct integration between the front end and backend – they each exist in their own little bubble. If you were building a backend in PHP, you don’t implement any PHP code in your Ionic application. The way in which the frontend and backend integrate is basically through sending messages to each other, like:

  • Give me all the posts for this user
  • Create a new user with these details
  • Create a new message for this user

When Ionic makes these requests to the backend through hitting a particular URL with an HTTP request, it does not care how that process is actually implemented on the backend or what technology it uses, it is only interested in the response (which is typically provided as JSON data).

If I wanted to retrieve some data from a backend, I might make a GET request in Ionic like this:

this.http.get('https://mywebsite.com/api/getUsers').map(res => res.json()).subscribe((data) => {
    console.log(data);
});

In this case, I would be expecting that the https://mywebsite.com/api/getUsers URL would output a list of users in JSON format. Again, it doesn’t matter whether those users are being pulled from a MySQL database, a text file, or anything else – all that matters to Ionic is that it receives a JSON response in the end.

If I were sending some data to be stored in the backend then I would probably make a POST request that contains that data (and if necessary, headers containing authorisation information).

I like to use the Reddit API for examples because it doesn’t require any kind of authorisation to access and it clearly demonstrates how this works. If you go to the following URL in your browser:

https://www.reddit.com/r/gifs/new/.json?limit=10

You will see a massive JSON string containing data about the GIFs in the gifs subreddit. This gives us all the information we need, but we have no idea how that data is stored on the backend or how it’s being retrieved. We don’t care though, and Ionic doesn’t care, all we are interested in is that JSON data.

If I wanted to pull that data into an Ionic application, all I would have to do is:

this.http.get('https://www.reddit.com/r/gifs/new/.json?limit=10').map(res => res.json()).subscribe(data => {
    console.log(data);
});

An Example of a PHP/MySQL Backend

The Reddit API is a great way to illustrate the concept, but how do we create our own API like this? There are different ways you can implement your API, but the basic idea is that sending a HTTP request to a specific URL will provide some data as a response.

Let’s go through a really simple example of how you might implement this with a PHP application. In the example I showed previously, we looked at a PHP file that would echo our the names from a table. How could we go about turning that into our own little API that we could use?

All you would need to do is create a file like the following:

$mysqli = new mysqli("localhost", "username", "password", "database");
$query = "SELECT * FROM table";
$dbresult = $mysqli->query($query);

while($row = $dbresult->fetch_array(MYSQLI_ASSOC)){

    $data[] = array(
        'name' => $row['name']
    );
}

if($dbresult){
    $result = "{'success':true, 'data':" . json_encode($data) . "}";              
}
else {
    $result = "{'success':false}";
}

echo $result;

This fetches the data from the database as before, but afterward it builds that data into a JSON object. Then the JSON object is just output by PHP at the end of the file. If we were to access this file through the browser, perhaps like this:

https://mywebsite.com/api/names.php

We would see that data output as a JSON string to the browser. Just like in the Reddit example, if we then wanted to pull that data into an Ionic application we could just do this:

this.http.get('https://mywebsite.com/api/names.php').map(res => res.json()).subscribe(data => {
    console.log(data);
});

Integrating Any Backend with Ionic

The basic process for integrating any backend into Ionic can be described as follows:

  • Create an API for your backend that accepts HTTP requests
  • To add data to your backend, send an HTTP request from Ionic to the API with that data
  • To retrieve data from your backend, send an HTTP request from Ionic to the API requesting that data

Of course, you need to be conscious of security concerns. The example we implemented above would allow anyone to visit that URL and see the list of names. Similarly, if you were providing a URL for updating a user’s account details you would need to add some kind of check to make sure that the user making the request is the one who owns the account. This is typically done through the use of some kind of authorisation token sent along in the headers of the HTTP requests, but that’s too big of a topic to get into in this post.

Summary

Hopefully, this article has illustrated why the question of what kind of backends is Ionic compatible with isn’t really the correct question to ask, but it does come from an understandable thought process. Ionic and any backend it may integrate with live in completely different worlds, and they communicate using the same language: HTTP requests and JSON.

What to watch next...

  • Ruben Maestre

    As always, great article Josh! Maybe you can make a second part, where you can explain the POST action? A GET seems easy (with your help šŸ˜‰ ), but a POST is more difficult because you have to create the data in Ionic, and then POST it. Can you give an example? And how do you use header for authorisation? Thanks!

    • Especimen

      I have an example with a mailer library on PHP. Are you interested?