Contact Us

How to read data from an API using Ionic 6

 - 
May 19, 2022
How to read data from an API using Ionic 6

Hello everyone! In this tutorial we will have a look into how we can get data from a Rest API using Ionic 6 and Angular. This article is for those who are just starting with the Ionic framework. We will go through everything you need to know to start sending HTTP requests from your Ionic application to an API and retrieve data and then display it in the screen.

Ionic is one of the best and the most populat cross-platform mobile app development framework created by Max Lynch, Ben Sperry, and Adam Bradley in 2013. It is actually based on Angular. It contains everything you need to build great mobile applications. We use Cordova or Capacitor in order to generate Android and IOS mobile apps.

Ionic uses almost all the concepts provided by Angular framework such as Observables, RxJS, Promises, HttpClientModule… It has a very big library of built-in components that make it easy for you to build a professional mobile application.

Setting up a new Ionic 6 application

Before creating the Ionic project, you need to install Ionic in your computer, you can do that using npm command line. Just make sure you have the latest version of node js installed in your computer :

npm install -g ionic

Now that you installed Ionic let’s create our Ionic 6 project. Setting up an Ionic 6 project is not difficult at all, you will need to run a single command to create the project.

ionic start readDataFromApi blank –type=angular

In order to serve your Ionic project run the following command

ionic serve

You need to wait a little bit for the project to be fully running. Once the project is running the browser will be automatically opened and go to http://localhost:8080/ and there you can see your application.

What is Rest API ?

Rest API stands for Representational state transfer Application Programming Interface, is a very powerful tool that is used to get, add, edit and delete data in the database. Almost every website in the internet have a database that holds its content. To get this data to the page and show it to the visitors we need an intermediate between the database and the browser. The Rest API plays the role of the intermediate between the database and the browser.

Using this powerful tool we can retrieve all or some specific data we need to display on our website or our mobile application. 

Our goal in this article is to show you how to fetch data from this Rest API and then display it to the users.

How does an API Rest work ?

Rest API is essentially the intermediate between the client (browser) and the server. The client side makes a request to the server side and then using Rest API the server will send back data over the HTTP protocol. The data received from the server will be used to load the content of the webpage.

Let’s take a look into a real life example. OMDD is an open source movies API which we can use to retrieve data about movies. If you take a look into their website you will notice that they suggest a test link to see data coming back from the API. 

Click on the following link and you will see data about a movie.

http://www.omdbapi.com/?i=tt3896198&apikey=ffb23b0

This data contains everything related to the movie such as its title, year, Runtime…

If we want to analyse the link, you can see that the first part is actually the link of the API provider http://www.omdbapi.com. Then we can add some parameters to the URL such as APIKey in our case which is the key to access the API apikey=ffb23b0, if you want to access their API you need to have an apiKey.

How to read HTTP Data with Ionic ?

Now that you understood the Rest API and how it really work, let’s dive into our main subject and see how to read HTTP Data with Ionic. In the first part of this article we setted an Ionic 6 project. In order to read API data go to the app.module.ts file in your Ionic project and add HttpClientModule to the imports array.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { HttpClientModule } from  '@angular/common/http';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, HttpClientModule],
  providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
  bootstrap: [AppComponent],
})
export class AppModule {}

Now, go to the home.page.ts file and add to the parameters of constructor the http service like so private http: HttpClient

import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor(private http: HttpClient) {}

}

In order to read data we need the get() method provided by the http service that we imported in our constructor.

import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor(private http: HttpClient) {
    this.readDataFromAPI();
  }

  readDataFromAPI() {
    this.http.get('http://www.omdbapi.com/?i=tt3896198&apikey=ffb23b0').subscribe((data) => {
      console.log(data);
    }, (err) => {
      console.log(err);
    })
  }

}

As you can see we read data from the URL passed to the get() method and we log it to the console. Go ahead and run your application and open the console section in your browser to see the data.

Read data from an API Result

How to stock data in the database with Rest API

A rest API can be used to achieve a lot of functionalities not just retrieving data, we can actually add data to the database, edit data and delete it from the database.

Let’s have a look into how we can achieve that using Ionic.

The best practice when you are using Ionic/Angular and you have many methods that communicate to your Rest API is to create a service and put all your functions in there.

  • The first function is the get() method that we just saw in the previous section of this article.
  • The second method is post() and we use it to add an object to the database, it takes two parameters. The first one is the URL to the API and the second is the actual object you want to add to the database.
  • The third method is put() which is used to edit data in the database. It takes two parameters as well the URL and the edited object you want to add in the database. When using this function you will need to pass the id of the object you want to edit. You can pass it with the URL.
  • The last function we are using here is delete() which is self explanatory. It takes a single parameter which is the link with the id of the object we want to delete.

Conclusion

Rest APIs are really powerful and you can use them in many use cases and with different web and mobile technologies. In this article we learnt how to get, add, edit and delete data from the database using a Rest API and Ionic. The same way you can apply it in other technologies with some differences in the code.

If you need a web or mobile application for your business, take a look to our Mobile development and Web development services.

Web Design Services

Looking for a web design agency to bring your business online and build the website you need to get more high quality clients ?
GrowYourBusiness.tech agency is ready to help you build your beautiful looking website.

Latest Blogs

We are a team of creative thinkers and problem solvers dedicated to expanding the limits of what is possible by helping brands achieve their goals.

Social Media

Copyright © 2021 Grow Your Business. All rights reserved.
crossmenu