facebook
Bob at Genuitec
Virtual evangelist at large. The face of Genuitec often appearing in graphics. Pen-name for our more shy writers of content.
Posted on Oct 20th 2017 Often, when developing Angular applications, you do not have the backing REST APIs ready for testing. To avoid having to digress into developing web services, or being blocked, waiting for your back end team to provide them, you can use JSON server to provide a “fake” API. This article will show you how to use Angular IDE and JSON Server to set up your API with minimal effort.

What is JSON Server?

JSON Server is an npm package that allows you to create an API, backed by a simple database. It is created for front end developers who need a quick backend for prototypes and mock-ups.

Creating an Angular Project

In the new Angular project wizard, enter `JsonandAngular4` as the project name. fake-angular-api-ss-1 Click Finish to complete the creation of a new Angular 4 project. In the Terminal+ view, you can see commands being executed by Angular CLI. After the installation of all the modules is complete, we are now ready to continue with development.
On a remote dev team? Try CodeTogether—it’s free!
  • Live share IDEs & coding sessions
  • See changes in real time
  • Cross-IDE support for VS Code, IntelliJ & Eclipse
  • Guests join from Browser or IDE
  • End-to-end source encryption
  • www.codetogether.com

Installing JSON Srver with Existing Angular project

Angular IDE has a terminal view from which we can execute commands. So from the menu, select Window, then Show View and then click Terminal+. In the opened terminal, type the following command. `npm install -g json-server` fake-angular-api-ss-2 This results in JSON Server being installed globally. Now, add the following command to the `scripts` section in the `package.json` file, to run the JSON server: `”json-server”: “json-server –watch db.json –port 3004″` The script section of the `package.json` file will look like this:
{
 "name": "jsonand-angular4",
 "version": "0.0.0",
 "license": "MIT",
 "scripts": {
 "ng": "ng",
 "start": "ng serve",
 "build": "ng build",
 "test": "ng test",
 "lint": "ng lint",
 "json-server": "json-server --watch db.json --port 3004",
 "e2e": "ng e2e"
 },

Starting the Angular App & JSON Server

Starting the Angular App

There is a server view in Angular IDE, as shown in the image below. To open it – Window > Show View > Server. Right click on your project (here `Jsonandangular4`). Angular IDE serves the application on `localhost port 4200` by default, so open http://localhost:4200 in your browser to see the running app – there isn’t much to see right now, of course. fake-angular-api-ss-3

Starting the JSON Server and creating the db.json file

In the Terminal+ view (ensure you have the correct project selected) run the following command: `npm run json-server` fake-angular-api-ss-4 This executes the command against the json-server property we added to our package.json earlier, and starts the JSON server at port 3004. If you open http://localhost:3004 in your browser, you can see that our JSON server is now running successfully. The JSON server automatically creates a `db.json` file in your current directory. Recall we specified that filename as one of the arguments in the `json-server` property. If you open db.json it will look like this – this is the default database created by JSON Server. Of course, you could manually create and/or edit this file too.
{
 "posts": [
 {
 "id": 1,
 "title": "json-server",
 "author": "typicode"
 }
 ],
 "comments": [
 {
 "id": 1,
 "body": "some comment",
 "postId": 1
 }
 ],
 "profile": {
 "name": "typicode"
 }
}

Connecting the Angular 4 App with the REST API

Now that we have our Fake REST API ready, let’s write some code to communicate with the API. We need the `@angular/http` package to work with the HTTP client. Angular IDE would have already downloaded the npm package when we created the project. Now import `HttpModule` into our application module (`src/app/app.module.ts`) and add `HttpModule` to the `imports` array in the `@NgModule()` decorator. The code in app.module.ts will look like this:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HttpModule } from '@angular/http';



@NgModule({
 declarations: [
 AppComponent
 ],
 imports: [
 BrowserModule,
 HttpModule
 ],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }
Now we will create a `Dunebook` class under the `app/src` folder, which will represent the object structure. fake-angular-api-ss-5 fake-angular-api-ss-6 Add the following code to `src/app/dunebook.ts`:
export class Dunebook { 
  id: number; 
  title: string;  
  author: string; 
}
Now we will update our template file, `app.component.html`:
<button (click)="getDunebooksData()">Get Data</button> 
<pre>{{DunebookList | json}}</pre>
And finally, update the `app.component.ts` with the following code:
import { Component } from '@angular/core';
import { Dunebook } from './Dunebook';
import { Http } from '@angular/http';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
 dunebookList: Dunebook[];

constructor(private http: Http) { }
 getDunebookData() {
 this.http.get('http://localhost:3004/posts')
 .subscribe(res => this.dunebookList =
 res.json() as Dunebook[]);
}

}
Let’s understand the code snippet above. First, we imported the HTTP client, available as the `Http` service in the `@angular/http` package, and injected it via dependency injection into a constructor. Then we are calling our API using the GET method. As the Angular `Http` service is an `Observable`, we need to subscribe to it in order to receive the response. Now if we click the button, we will receive post information in JSON format from the API. Open `http://localhost:4200` in your browser and you will see a screen like below. fake-angular-api-ss-7 After clicking the `Get Data` button, you will see output like this: fake-angular-api-ss-8 We have now successfully connected our Angular app to the JSON REST API. This is a rather basic example, which used only a simple query. However, JSON Server does support more complicated APIs as well, including the ability to search the database, obtain ranged or sorted results, manage relationships, and more. You can even use JSON Server as a static file server, or write a small amount of JavaScript to generate the data programmatically – the ability to create alternate routes to your data is also handy – see the JSON Server page for a detailed list of its abilities. For everything beyond the REST API, remember to use Angular IDE or MyEclipse to make your life easier.