Hands on todo app with local fake JSON server

Task: todoApp with local JSON Placeholder Service

Task: todoApp with local JSON Placeholder Service

The API endpoints

API Root: https://jsonplaceholder.typicode.com
GET/todosGet all todos
GET/todos/1Get todo with id=1
POST/todosCreate new Todo
PUT/todos/1Update Todo with id=1)
DELETE/todos/1Delete Todo with id=1)

Setup fake REST API json-server and DB

Setup fake REST API json-server and DB

Overview

We can use a fake REST API json-server, to mock the back-end endpoints.
It is freely available on NPM and ready to use.
Please note, that this server is useful only for learning purposes and you must not use it for any production code.
Before starting the project, make sure you have basic understanding of how to use npm ( Nodejs and NPM intro )

Installation

Install json-server
To prevent polluting your global environment, it's recommended to install NPM packages locally, i.e. without the -g option.

			# navigate to your project root folder
			$ cd /path/to/TodoApp

			# init the project:
			npm init

			# install json-server package
			npm install json-server
		

Create the DB file

In project root folder create the file db.json with next content:

			{
				"todos":[
					{
						"id": 1,
						"title": "Learn HTML",
						"completed": false
					},
					{
						"id": 2,
						"title": "Learn CSS",
						"completed": false
					},
					{
						"id": 3,
						"title": "Learn JavaScript",
						"completed": false
					}
				]
			}
		

Start the server

All locally installed NPM packages place the executable commands in ./node-modules/.bin/ folder. You can start json-server by:

				$ ./node_modules/.bin/json-server --watch db.json
			
Or you can use npx which executes 'command' either from a local node_modules/.bin, or from a central cache, installing any packages needed in order for 'command' to run.

json-server usage notes

Your request body JSON should be object enclosed, just like the GET output. (for example {"name": "Foobar"})
Id values are not mutable. Any id value in the body of your PUT or PATCH request will be ignored. Only a value set in a POST request will be respected, but only if not already taken.
A POST, PUT or PATCH request should include a Content-Type: application/json header to use the JSON in the request body. Otherwise it will result in a 200 OK but without changes being made to the data.

References

Official docs: json-server
Rautes: json-server#routes

These slides are based on

customised version of

Hakimel's reveal.js

framework