large JSON Object

Test your Angular App with a Local Mock API JSON Server

Ever wanted to test your front end will a fully functional fake REST API before connecting it to your actual backend? Well now you can in 30 seconds with this nifty npm package – so let’s get started.

In your Angular app install the json-server.

npm install -D json-server

In package.json include the following json-server command in the "scripts" block:

... 
"scripts": {   
  ...   
  "test": "ng test",    
  "lint": "ng lint",   
  "e2e": "ng e2e",    
  "json-server": "json-server --watch db.json --port 3004"  
}, 
...

Create a db.json file in your root directory with the following contents:

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}

Next write a simple GET request to fetch the only "post" object in the database.

import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {tap} from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  constructor(private httpClient: HttpClient) {}

  ngOnInit(): void {
    this.httpClient.get('http://localhost:3004/posts/1')
       .pipe(tap(console.log)).subscribe();
  }
}

Time to serve your Angular app and fake REST API! In two separate terminal windows start your Angular development server and the JSON server.

ng serve
npm run json-server

If you open the console of your Angular app you’ll see that the data was fetched and is ready to use!

fake REST API GET request success
fake REST API GET request success

I highly recommend you look through the official documentation of this package as there’s so much more you can do with this fake REST API tool. Happy prototyping!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.