Angular 12 Setup Mock API and consume and return data


In this post, You will learn how to create a Simple mock api to return json data in Angular application without creating backend API

Some times, We want to test data components using API code, if there is no backendcode,

This tutorials explains about How to create a Backend REST API for mock data which returns json object in Angular application

First Create a angular application

First check angular cli or not using ng -version

C:\Users\Kiran>ng --version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 12.0.1
Node: 14.17.0
Package Manager: npm 7.11.1
OS: win32 x64

Angular: undefined
...

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.1200.1 (cli-only)
@angular-devkit/core         12.0.1 (cli-only)
@angular-devkit/schematics   12.0.1 (cli-only)
@schematics/angular          12.0.1 (cli-only)
typescript                   3.6.3

if Angular cli is installed, use npm install @angular/cli command to install it.

Next, Create an angular application using ng new command

B:\githubwork\angular-mock-api-json>ng new
? What name would you like to use for the new workspace and initial project? no
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? CSS
CREATE no/angular.json (3015 bytes)
CREATE no/package.json (1064 bytes)
CREATE no/README.md (1048 bytes)
CREATE no/tsconfig.json (783 bytes)
CREATE no/.editorconfig (274 bytes)
CREATE no/.gitignore (604 bytes)
CREATE no/.browserslistrc (703 bytes)
CREATE no/karma.conf.js (1419 bytes)
CREATE no/tsconfig.app.json (287 bytes)
CREATE no/tsconfig.spec.json (333 bytes)
CREATE no/src/favicon.ico (948 bytes)
CREATE no/src/index.html (288 bytes)
CREATE no/src/main.ts (372 bytes)
CREATE no/src/polyfills.ts (2820 bytes)
CREATE no/src/styles.css (80 bytes)
CREATE no/src/test.ts (743 bytes)
CREATE no/src/assets/.gitkeep (0 bytes)
CREATE no/src/environments/environment.prod.ts (51 bytes)
CREATE no/src/environments/environment.ts (658 bytes)
CREATE no/src/app/app-routing.module.ts (245 bytes)
CREATE no/src/app/app.module.ts (393 bytes)
CREATE no/src/app/app.component.html (23809 bytes)
CREATE no/src/app/app.component.spec.ts (1045 bytes)
CREATE no/src/app/app.component.ts (206 bytes)
CREATE no/src/app/app.component.css (0 bytes)
√ Packages installed successfully.
    Directory is already under version control. Skipping initialization of git.

json-server for Backendless REST API using JSON

json-server is an express based web server that has all REST API operations using JSON as database.

It helps UI developer to prototype or mock REST API’s using JSON file as a backend database.

It allows to setup and run REST API server in 5 minutes without coding and helps developer to test UI components.

JSON-server features

  • Any changes to object will update database json file
  • It also provides pagination data during list of items
  • Provides authentication to add security
  • Customize Routes using routes option --routes
  • Add middleware code to apply business logic using --middlewares
  • It is easier and integrate in 5 minutes
  • Validations like 404 and duplicate are supported
npm install --save json-server

Next create a folder api under project directory.

Create a database.json in api

{
users:[]
}

Either we can insert dummy data or use faker npm library

faker npm library generates dummy data

faker.js is an npm library for generating fake real time data First install faker to angular app

npm install faker --save

Next, Insert dummy data using javascript code

  • Create an users database which holds list of user information
  • using for loop insert 100 users with fake data and push to an array of users
  • We have users array object in database string.
  • Convert this object to json string using JSON.stringfy funciton
  • We have to create a database.json using writeFile method of fs module
  • writeFile accepts file path, json object, encoding and callback
  • callback throws an error if json file not created.

Here is InsertIntoDB.js which creates database.json file

var faker = require('faker');
var fs = require('fs');

var database = { users: [] };

for (var i = 1; i <= 100; i++) {
    database.users.push({
        id: i,
        name: faker.name.findName(),
        email: faker.internet.email(),
        username: faker.commerce.userName,
        password: faker.commerce.password,
    });
}

var json = JSON.stringify(database);
fs.writeFile('api/database.json', json, 'utf8', (err) => {
    if (err) { console.error(err); return; };
    console.log("database.json created");

});

let’s configure npm scripts for below things in package.json

  • insert: this generates faker data in json string and creates database.json
    "insert": "node ./api/InsertIntoDB.js",
  • server: let’s configure json-server to start server and input database file is included
   "server": "json-server --watch ./api/database.json"

Here is package.json file

{
  "name": "angular-mock-api-json",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test",
    "insert": "node ./api/InsertIntoDB.js",
    "server": "json-server --watch ./api/database.json"

  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~12.0.1",
    "@angular/common": "~12.0.1",
    "@angular/compiler": "~12.0.1",
    "@angular/core": "~12.0.1",
    "@angular/forms": "~12.0.1",
    "@angular/platform-browser": "~12.0.1",
    "@angular/platform-browser-dynamic": "~12.0.1",
    "@angular/router": "~12.0.1",
    "faker": "^5.5.3",
    "json-server": "^0.16.3",
    "rxjs": "~6.6.0",
    "tslib": "^2.1.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.0.1",
    "@angular/cli": "~12.0.1",
    "@angular/compiler-cli": "~12.0.1",
    "@types/jasmine": "~3.6.0",
    "@types/node": "^12.11.1",
    "jasmine-core": "~3.7.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "typescript": "~4.2.3"
  },
  "_id": "no@0.0.0"
}

Next run the above code using npm run command to create a database

npm run insert

This creates an file in database.json in api folder.

Start json server using npm run command

npm run server
B:\githubwork\angular-mock-api-json>npm run server

> no@0.0.0 server
> json-server --watch ./api/database.json


  \{^_^}/ hi!

  Loading ./api/database.json
  Done

  Resources
  http://localhost:3000/users

  Home
  http://localhost:3000

  Type s + enter at any time to create a snapshot of the database
  Watching...

This starts server and accesable at http://localhost:3000/users

By Default, This provides different api’s aviable

URL   HTTP Method Type   Description
/users GET List of Users
/users/{id} GET Retrieve User by Id
/users POST Create an user object
/users/{id} PUT Update an user object by Id
/users/{id} PATCH Update an user object with partial properties by Id
/users{id} DELETE

if any changes made to user object using POST,PUT,PATCH,DELETE request, JSOn-server updates database.json instantly.

Angular Example to consume Mock Data

There are couple of steps to Consume REST API in angular application. Frontend apps communicate with Backend apps or REST API using HTTP Connection @angular/common/http provides HttpClient class

HttpClient is component user to connect and issue HTTP request to REST API.

Before using HttpClient, You have to import HttpClientModule

Setup HttpClientModule into module

Import HttpClientModule into angular app.module.ts.

All the classes and services aviable in this module are accessed across all components of app.module.ts

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

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

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

First Create an Interface model for user data. You can choose [interface or class for model] (/angular-model-class-interface)

export interface User {
    id: number;
    name: string;
    email: string;
    username: string;
}

Let’s first create a component app.component.ts In Angular Component:

  • Created an User Array object

  • Initialize the User array with empty array in constructor if you skipped this step, you will get an error Property 'users' has no initializer and is not definitely assigned in the constructor.ts(2564)

    You can check more information how to fix this error

  • Inject HttpClient in constructor to use HttpClient class methods

  • Make an http get request using HttpClient.get

  • get API returns response in JSON object and convert to Typescript User object.

  • In html template file, using ngFor loop iterate users object and displays to UI.

  • In scss file, add css styles for alternative table row color. app.component.ts:

import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { User } from './model/User';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  users: User[];
  title = 'angular-crud-mock-api';

  constructor(private http: HttpClient) {
    this.users = [];
    this.getUsers();

  }
  getUsers() {
    console.log('calling')
    this.http.get('http://localhost:3000/users')
      .subscribe(res => this.users =
        res as User[]);
  }

}

app.component.html:

<h1>Users List</h1>
<table style="width:100%">
  <tr>
    <th>id</th>
    <th>username</th>
    <th>email</th>
  </tr>
  <tr *ngFor="let user of users!">
    <td>{{user.id}}</td>
    <td>{{user.name}}</td>
    <td>{{user.email}}</td>
  </tr>

</table>

app.component.scss:

table {
    border-collapse: collapse;
    width: 100%;
    th,
    tr {
      border: 1px solid #ccc;
    }
    th,
    td {
      text-align: left;
    }
  
    tr:nth-child(even) {
      background-color: #f0f0f0;
    }
}

This examples call mock REST API’s and display it in table

Output Angular Fake REST API consume example

Conclusion

To Summarize, We learned A Step By Step tutorial for Create an angular application with cli Add json-server for mock API server add faker for dummy data for CRUD API write a package.json script for insert data into database json and start json server add httpClientModule and consume Mock API in angular app component.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.