How to Build Your First Ionic 6 App with API Calls

ionic-6-app-api-calls

You finally want to get started with cross platform app development and learned about the Ionic framework? Today is your days because we’ll go through building your first Ionic 6 application with HTTP Calls to The Movie Database!

Whether you are completely new to Ionic at all or have used other versions of Ionic before and now decided to get started with v 6, we go through all the basics to setup a new app, routing and even API calls to display async data inside our app.

ionic-6-app-api-calls

On top of the basics we will also implement infinite scroll so we can go through a paginated API response with ease.

If you want to get an even more detailed guide you can check out the Ionic Quickstart Guide, a free 46 pages PDF provided by the Ionic Academy!

At the bottom of this tutorial you will also find a full screencast covering all the steps and even more information.

Setting up Our Ionic 6 App

If you are new to Ionic you need to make sure you have Node.js the Node Package Manager installed but if you have worked with other web technologies before chances are pretty good you already got everything you need.

Otherwise quickly go through the Ionic environment setup.

To setup a blank project (blank meaning just an empty page) you can use the Ionic CLI so we end up with a fresh Ionic 6 project with Angular support (you could also use React or Vue, but the Ionic Academy is focused on Angular).

Once the project is created we cd (change directory) into the folder and also use the CLI, which basically uses the Angular CLI under the hood, to create new pages and a service for our app that we want to use later.

Now go ahead and run the commands below from your terminal:

This project now automatically uses Capacitor and not Cordova anymore, but more about that in the last chapter.

You can now directly bring up your app by running the following command inside your project:

This will open the browser with the preview of your app which will reload automatically once you change anything inside your project.

Speaking of project, we got a bunch of files and folders in here, let’s see what all of this means. We will focus on the src folder of our app since we don’t have to worry about the rest for now.

ionic-6-project-structure

App

This is the folder where we will make all the code changes that follow later in this tutorial. It already contains a home folder that’s basically a page like we created before, but I like to have all pages in their own pages folder so you can remove the home folder as well for now.

The pages folder contains the actual views/pages of our app, which means the element we will see on the screen. Right now we already got 2 pages in here, and each page you create with the CLI comes with 5 files:

  • *-routing.module.ts: An additional file that’s used with the Angular router – more on navigation soon
  • *.module.ts: The Angular module for a page. Each page is basically their own module (related to the Angular architecture) with imports and styling
  • *.page.html: The HTML markup for a page
  • *.page.scss: The styling for the specific page (more on global styling later)
  • *.page.spec.ts: An automatically added testing file for your page. Good if you want to set up automated unit tests
  • *.page.ts: The controller for a page that contains the Javascript code that manages the functionality

The services folder contains our previously created service – this is about structuring your app according to best practices and separating concerns between thew view and the actual data of your app. The service will take care of handling the API calls and simply return the data to our view later!

Assets

This folder contains all the images, fonts or whatever assets you need for your app later down the road.

Environments

From time to time your project might have a development, staging and production environment with different servers that your app targets. The environment folder helps to set up information for different environments so we can later simply build our Ionic app with a command line flag and it automatically takes the right values.

We can use it for our app to add our API URL and credentials.

Theme

This folder only contains the variables.scss that contains predefined color information from Ionic. We can always change this file and even use a tool like the Ionic Color Generator to create our own flavoured version of this file!

Outside of the folder we also got the global.scss in which we can write some SCSS that will be globally applied to our app – but we can also define it just for one page in their own styling files.

Other Files

The most relevant of the other files might be the index.html because just like with every other website, this file marks the entry point to our app! For now though we don’t need to change a thing in here so let’s now start to get into the actual code.

Routing, HTTP Calls & Environment

In Ionic Angular applications we use the Angular router to navigate to different pages of our app – pretty much like you would define different URLs for a regular website. You can also check out this additional guide about Angular routing in Ionic apps!

For all the connections inside your app you setup routing information upfront, so we can then easily navigate to those URLs.

In our app we need 2 routes:

  • /movies – Navigate to our first page which should display a list of trending movies
  • /movies/:id – We want to be able to show the details for one movie so we add a param :id to the route that we can dynamically resolve

We also need to connect the according page (more specific: the module of the page) to the route so Angular knows how to resolve a specific route. We supply this information using loadChildren which actually only gets a string to the module path.

This means we are not really importing another module here therefore the pages are using lazy loading and will only be loaded once we navigate there!

To setup our routing information open our src/app/app-routing.module.ts and change it to:

By making this change we have also disconnected the home page which was initially in the project (and which you might have deleted already at this point).

Now the app will load our movies page as the first page, great! You should also notice this change in your running ionic serve instance already.

ionic-6-movies-initial-page

Tip: If you want to get a better feeling for how your app will look on a real device you can also run ionic lab instead of serve but you have to install the package upfront:

/Tip End

We also need to apply another change to our app as we want to make HTTP calls and therefore need to import another Angular module for making those requests.

For this we just need to add the HttpClientModule to our main module file and add it to the array of imports like this inside our src/app/app.module.ts:

If your app needs some static information like API endpoints, it’s a good place to add them to the already existing environment file, so in our case we can open the src/environments/environment.ts and insert:

At this point you should make sure you got an API key – if not, simply create an account for The Movie database and request one for free!

One you got that, add the key to your environment and move on.

Now it’s a good idea to prepare the logic of your app before you dive into the actual UI creation, so let’s quickly implement our API interaction.

Making HTTP Requests

An Angular service is simply a class that you can inject into other components which gives access to certain methods that you define.

In our case, we want to prepare two functions to call the API:

  • getTopRatedMovies(): This will return an ApiResult like object with all results and some meta information for our pagination
  • getMovieDetails(): This will retrieve the detailed information for one object in the database, which is a very common API pattern

Both functions will return an Observable which is like a Promise on steroids. No serious, it’s like a stream of events that we can subscribe to. Explaining this concept would take another post so for now let’s use it and keep in mind that both of our functions are async – they won’t return the API data immediately.

Now go ahead and change your src/app/services/movie.service.ts to:

Be careful with the notation here, because I am using template literals which allows us to include variables in a string by using the ${...} syntax.

If you don’t use the right backticks, you will simply get the whole string but the variables won’t be injected.

With our logic in place, we are now ready to finally create some Ionic pages!

Listing Popular Movies

We implemented all API calls inside a service so we can now inject it into our page.

A page is mostly like the default Angular component, but an Ionic page already comes with its own module file so the router can lazy load the page.

You can think of a page as the representation for one view in you app, like a home screen or user profile – and we navigate between different pages.

For now we want to load all popular movies when our page is initialised, for which we use the ngOnInit() Angular lifecycle event that’s called upon page creation.

In there we call the getTopRatedMovies() function of our service and add all resulting objects to our local movies variable using the spread operator – otherwise we would push an object, but of course we want the single objects inside our array here.

To support pagination we keep track of the currentPage and increment it inside loadMore() to then run our loading logic again.

Don’t mind the optional event variable for now – we’ll talk about that later again.

Now go ahead and change the src/app/pages/movies/movies.page.ts to:

Before we start the HTTP call we also display an Ionic component from code, which is the loading indicator.

For everyone new to Ionic in general: Welcome to your first Ionic components!

We can use components both from code and also to create our view as we will see next. And because these Ionic components usually return a Promise we need to use async/await to correctly handle the flow of events.

Let’s move on to the template of our page now.

A page can be separated in 3 areas: Header, content, footer.

In our case we don’t want a footer so we only define the header area with a title and the content with our actual elements for the movie list.

For our list we use an iteration over the movies object from our class, so Angular creates one ion-item for every movie.

At the same time, we attach a routerLink to the item which allows us to later navigate to a details page by appending the id to the URL – matching what we defined in the beginning in our app routing!

Within the item we define some information using the different slots of an Ionic component, which basically allow us to inject our own HTML.

Since Ionic 4 components are built using Stencil (yeah, they actually created that tool as well!) so they are standard web components – you could import them basically everywhere on the web! These components also use the Shadow DOM API and are living outside the scope of your regular DOM elements.

That means also standard styling will sometimes not affect these components like it was possible in previous versions!

In order to get information into these components we can inject certain parts of HTML into their slots that are defined on these elements – you can see how their implementation looks like on the example of the ion-item we used here.

Explaining the whole shadow DOM concept and styling would be a bit too much at this point – read my free Ionic Quickstart Guide for a more detailed explanation!

In the beginning we add an avatar image, and we need to construct the path to the image because the API only returns a relative poster_path.

Additionally we display title and release data, using the Angular datepipe to directly transform the date string into just the year.

At the end of the item we also add a badge, just to get abetter feeling for all the possible Ionic components that we can use!

With all of that information continue with the src/app/pages/movies/movies.page.html and change it to:

At this point you should be able to see a list of popular movies inside your Ionic app preview!

ionic-movies-preview

Oh, we even trigger a load when we scroll down?

Yes, because we also added the ion-infinite-scroll component after our list!

Whenever we reach a certain distance from the end of our current list, this component calls the function we defined for the ionInfinite event.

This will increment our page number, start a reload and to correctly end the loading, we added the event?.target.complete(); block in our loading function. On top of that, we can also disabled the infinite scroll component from there if we reach the end of the pagination.

We got that infinite scroll pretty easy, and that’s just what Ionic does: Make your life a lot easier.

Creating a Details Page

Ok enough of background information, let’s put some more work into the details page of our app. We have implemented a route and we also created a button (our ion-item acts as a button) that passed an ID with the route so the details page will be open, but we need to get access to the ID!

With early Ionic versions we could easily pass whole objects to new pages, this is now not a best practice anymore. Instead, we pass only small chunks of information (like an ID) with the URL because otherwise you would end up with a huge JSON stringified term inside the URL which isn’t really something we want to have.

To get access to this ID field (that we already defined inside our routing in the beginning!) we can use the ActivatedRoute and its properties, so we inject it into our details page.

After we extract the ID from the params we can make another call to our service (that we injected through the constructor again) and get the detailed movie information for whatever ID we got.

Nothing really new so let’s add the following code to our src/app/pages/movie-details/movie-details.page.ts:

We also add another function to open a potential homepage, but that’s just plain Javascript so far!

Now we just need to create a view based on the JSON information of the API. It always helps to log() out the info you got so you see keys that you can use to display some values.

In our case we use the Ionic card component and add the image and some items with information and icons

Icons?

Yes, Ionic apps have a dependency to Ionicons by default, a great free icon set that was created by the Ionic team as well, which comes in pretty handy in many cases.

On another note, we also have to add an ion-back-button to the header of that page in order to get a nice little back arrow to our previous movie list page. We also set a defaultHref for that button which allows us to use it correctly even if we just refresh the details page in the browser!

Now finish your details view by changing your src/app/pages/movie-details/movie-details.page.html to:

And with this code in place you can navigate between your movie list and details page, and the information inside the view is populated based on the JSON data from the API – what a great success!

Teardown

While it was a straight forward experience to build our first Ionic 6 app there are so many things we haven’t talked enough about.

UI patterns like Tabs and side menu, CSS variables, responsive layout and PWA to just name a few on the side of Ionic and Angular.

And we haven’t even touched the Capacitor side of things to actually build this app into a real native mobile app – check out the video below for a glimpse at that!

If you want to learn how to develop Ionic apps as fast as possible and get them to the iOS & Android app stores quickly you can join the Ionic Academy today and enjoy step-by-step video courses and join our private community today.

And of course I (Simon) am also present inside to answer all your questions all the time 🙂

You can also find a video version of this guide below to see my style of teaching Ionic in action!