Learn how to call a REST API from your Ionic mobile application and mock it using Mockoon API mocking tools
In this guide, we will learn how to call an API endpoint from an Ionic mobile application using the Angular framework. If you already have an existing API that you want to use, you can skip the first step, in which we create a fake REST API endpoint using Mockoon.
During the development of your Ionic mobile application, you may need to mock an API that is not ready yet, or only partially available (see partial mocking with the proxy mode). For this, the easiest way is to create a mock API using a tool like Mockoon. (Read more about the benefits of API mocking).
To learn more about how to set up your first mock API with Mockoon, head over to the Getting started tutorial.
For the rest of the tutorial, we will use an array of fake blog posts. In Mockoon, create a
GET /posts API endpoint that returns an array of blog posts:
You can use the following JSON as the body returned by the endpoint:
Note that your fake mock server will be available at the following URL:
http://localhost:3000. This is the URL we will need to use in our Angular service.
After creating a mock API endpoint in Mockoon, you can now call it from your Ionic mobile application using an Angular service. To do so, we need to create a new "posts" service using Ionic's following command:
Then we will need to inject and use Angular's
HttpClient in our new service to be able to call our API:
We finally add a
getPosts method that we will call from our component and returns an Observable containing our list of posts:
Below is our service after putting all the pieces of code together:
Let's display our blog post titles in our "HomePage" component. We first need to inject our
PostsService and then assign our Observable returned by the
getPosts method so we can use it in the template:
We can now display our list of post titles using
ion_item elements. We will reuse the
div#container from the
home.page.html file created by the
ionic start command. We will use a simple
*ngFor directive combined with the
| async pipe to subscribe to our observable:
We can now see the result after running the
ionic serve command: