Home / Articles / Blog

Develop Random/Fake Node JS server for projects
json-servernpmBackendAPINode.js

Develop Random/Fake Node JS server for projects

Develop Fake endpoints in Node.js using json-server for demo projects

BackendShrey Vijayvargiya

Section 1

Under the Hood

Creating fake API such as post, comments, users and so on is very useful for frontend developers to showcase their skills for the mini-portfolio project. Every time you need some sample API that will only be available with the GET method you cannot have sample API with PUT, UPDATE and DELETE methods. json-server is an npm package that provides Fake endpoints with all the HTTP-required methods.

Section 2

Getting Started

Go ahead and add the package to your empty directory using the below command.

text
yarn add json-server

After adding the package the first step is to create sample JSON data. Create a file in the root directory with the name db.json. Create the proper JSON object in it as shown below.

GitHub Gist

Section 3

Routes

Run your server usingjson-server locally to create the Fake API with this JSON object in db.json as sample data.

text
npx json-server --watch db.json

We are using the json-server watch command to extract the data exported by db.json file and use this object as sample data.

Also if your json object consists of an array of objects with “users” as a key then /users will become your GET endpoints to access the list of all users. For example, if your db.json looks like the below one —

GitHub Gist

Here users are the array of the object of a single user, so your endpoint will become /users to extract all the users and if you create another array of objects as posts then you have created another endpoint /posts. In addition, opening localhost:3000 port will show the list of all endpoints under the Resources section.

Localhost:3000 with all the endpoints under the Resources section.
Localhost:3000 with all the endpoints under the Resources section.

Section 4

HTTP Methods

The json-server itself provides HTTP methods to update, and delete the data you have created. Here is the list of methods using endpoints that are available —

1. Fething users

This will simply create a user in the user’s array. I am using Postman to test my endpoints. Once the user is created the user's array gets reflected in your local db.json file. The json-server uses the lowdb npm package to reflect the changes in your local files.

text
POST /users body : { name: 'Dino James' }

2. Deleting a User — 

This method deletes a user whose ID is mentioned in the parameters of the URL. The json-server depends on the lodash library under the hood to filter the object from an array and mutate the objects and so on.

text
DELETE /users/1

The user with id 1 will get deleted from the user's array.

3. Fetching single user —

This method again accepts the id of the corresponding user you want to fetch from the data.

text
GET /users/1 

4. Filtering user with deeply nested value —

Use the. operator in the params of the endpoint to filter a single user with deeply nested value.

text
GET /comments?author.name=” Dino James”

5. Pagination —

By default 10 objects are returned on a single page and after providing _page params you can get the particular 10 values.

text
GET /posts?_page=1

6. Sorting — 

You can sort the data by providing sorting parameters in params of the endpoint. Lodash eases out the pain to create these functionalities on arrays.

text
GET /posts?_sort=post

Sorting of the post in ascending order
Sorting of the post in ascending order

You can also add sorting order which is an enum[asc, desc].

text
GET /post?_sort=post&_order=desc 

Sorting in descending order
Sorting in descending order

  1. Search using query — Passing a query parameter to the endpoint search for the value equals to query and return it.
text
GET /post?q="Firebase"

This will search among the posts and return the object which includes Firebase in the value.

Search result for the query “Introduction”
Search result for the query “Introduction”

That is all about Routes, redirect to the actual documentation for a detailed understanding.

Section 5

Middlewares

You can add customer middleware like the one you did for Express servers. Middlewares can add by CLI using the below command.

text
// File hello.js module.exports = (req, res, next) => {  res.header('X-Hello', 'World')  next()}
text
npx json-server db.json --middlewares ./hello.js

This command will run the file hello.js and set the header as a world to every route. Another way to add middleware to use methods provided by json-server. Create a server using .create method and middleware using .default the method of json-server . Adding middleware in the similar way we add in Express server using .use method of our application. The code below depicts the process.

text
const jsonserver = require('json-server');
const server = jsonserver.create();
const router = jsonserver.router('db.json');
const middlewares = jsonserver.defaults()

server.use(router);
server.use(middlewares);
server.listen(3000, () => console.log('Server is listening on PORT 3000'))

Just run this file using node server.js and your middleware is registered and all other routes are also subscribed to /user and /post endpoint.

Section 6

Adding Scripts in package.json

You can run the whole server using nodemon or node or json-server . Inside package.json add “scripts” object with key-value pair according to your convenience.

text
"scripts" : {  "nodemon-server": "nodemon server.js",  "json-server": "npx json-server --watch db.json",  "node": "node server.js"}

Note => If you use nodemon or node your home route i.e. / the endpoint will not return the json-server interface as shown in the image below.

Json-server interface on localhost:3000/ endpoint
Json-server interface on localhost:3000/ endpoint

Section 7

Serving static files

You can use static in CLI to register static files or create HTML, CSS or JS files in ./public directory.

text
json-server db.json --static ./path-to-statis-file

I have created a file static.html inside the public directory after running the server if you go to the /static.html route you will find the static file running on the server served by json-server.

Section 8

Conclusion

This way around creating all the required endpoints really helps a lot to develop the prototype of your idea. This won't take much time and you can add authentication also using a basic JWT token.

I will cover more articles on Authentication using json-server in future.

That's it, see you in the next one

Shrey

External Links (8)

Explore topics

More in

Weekly letter

Subscribe to iHateReading

Our once-a-week newsletter on programming, jobs, AI, and building products online.

Our once a week newsletter on Programming, Jobs, AI, and Business