JSON Server is a very remarkable asset for programmers, particularly when you want to create a fake REST API for development and testing purposes. It enables the user to generate an API in less than a minute. Before proceeding with the implementation, let’s understand what JSON Server can do.
JSON server uses a simple JavaScript file or JSON file for maintaining database operations like GET, POST, PUT, PATCH, and DELETE. It provides flexibility to the developers as it works with front-end technologies like Angular, React, Vue, etc.
// Installation npm install -g json-server // To start JSON Server json-server --watch db.json
The perks of JSON Server
- It enables full fake REST API with zero-coding in a few seconds.
- It supports all essentials HTTP Requests: GET, POST, PUT, PATCH, DELETE.
- It supports delay responses and generates data using JS.
- It provides rapid backend setup for prototyping and mockups
- It includes features like sorting, slicing, filtering, and full-text search.
JSON Server in Action
Beginning to use JSON Server is very straightforward. After installation, all you need is to generate a JSON file that will act as different end-points of your API. You can mock the data in the JSON file on how you generally see in a real-world database.
{ "users": [ { "id": 1, "name": "John", "email": "john@example.com" }, { "id": 2, "name": "Kane", "email": "kane@example.com" } ], "posts": [ { "id": 1, "title": "json-server", "author": "John" } ], "comments": [ { "id": 1, "body": "It's amazing", "postId": 1 } ], "profile": { "name": "typicode" } }
The above JSON file is establishing a Database with USERS, POSTS, COMMENTS, and PROFILE as its different tables. The JSON Server treats every top-level key as an end-point.
Accessing the JSON Data
The JSON data will be accessible on different end-points (also known as routes in the server scenario). For instance, if you want to see all the users, you can request the /users end-point.
fetch('http://localhost:3000/users') .then(response => response.json()) .then(data => console.log(data));
Here we are using JavaScript’s fetch API to request the users route. The server will respond with the data related to all the users we set up in the JSON file earlier.
To sum it up, Using a JSON server as a mock REST API for development will dramatically improve the productivity of your development workflow. Moreover, it is effortless to set up and integrate with your process.