The perfect mock REST backend for your Angular app

F.Laurens
letsboot
Published in
2 min readSep 6, 2017

--

Usually, when you start with Angular, you want to connect to a backend. But often the backend is developed while your working on the frontend. For those who need a quick fully functioning REST backend with mock data, this “json-server” will make it happen!

Sponsored by letsboot.com

What we will do today:

  1. json-server installation
  2. Create a JSON file with mock data
  3. Run it
  4. Use the backend in your Angular application
Subscribe to our Youtube channel

json-server installation

First, you need to install a json-server. You can do it globally (-g) with npm:

npm install -g json-server

Create a JSON file with mock data

In the root folder of your application, create a file with the extension .json. Inside you can add a set of data with several fields:

Run it

Run the json-server in a terminal and launch the JSON file. The option watch (shortcut: -w) allows to reload automatically the browser when the JSON file is modified:

json-server --watch myJSONfile.json

Open your browser at the indicated URL. You can find this information in your terminal:

Screen shot from my terminal after running the json-server command

You can try to test the different paths to see how the data are displayed:

http://localhost:3000/pictureshttp://localhost:3000/authorhttp://localhost:3000/comments

Use the backend in your Angular application

If you have an Angular application, you can use this backend in your service.

Set an URL variable to the localhost url, then use it in your CRUD functionalities for instance:

That’s it! You installed a json-server, created a set of mock data and run it!

Sort, Add, Search, Filter, Delete and Update

The json-server supports so many features, that I’m often tempted to use it in production. But of corse we don’t ;-)… Still you should know about the power your backend developers won’t get done that quickly:

Basics:

GET    /pictures
GET /pictures/1
POST /pictures
PUT /pictures/1
PATCH /pictures/1
DELETE /pictures/1

Searching:

GET /pictures?q=view (full-text search)
GET /pictures?title=A%20natural%20view&author=Lisa
GET /posts?id=1&id=2
GET /pictures?author=Andy

Sorting:

GET /posts?_sort=author&_order=asc

And much more: Relationships, Slicing, Pagination, Expanding, Collapsing…

It’s even possible to configure your own routes in a separate file, and you can even load json-server in your own node backend to add permission handling. (Be aware of the risk of data loss.)

Thank you to

for this amazing npm package!

See you next time for another article about Angular4 ! Follow me on Twitter, LinkedIn or Medium and take a look at our letsboot.com medium article series!

--

--

F.Laurens
letsboot

Database and software developer, biology lover, scuba and free diver