Overview
In a software development project, sometimes the annoying common problem is frontend developer needs to wait until the backend developer finishes working on an API. That's why we need to make a mockup API, therefore both backend and frontend developers can work parallel.
JSON server is an easy way to make a fake REST API, even a beginner or non-programmer can make it. The only prerequisite is you need to understand JSON structure. Here's a tutorial to make a fake REST API with JSON Server.
Setup
- Install node js: [https://nodejs.org/en/download/]
- Open a terminal (bash/shell/linux)
Create a directory call mock-api (or whatever you want)
-
initial new project. Type
npm init
then enter until show like below, and type yes.
Working with JSON Server
install json server npm install -g json-server if you want install globally or npm i json-server if you want install locally. In this tutorial I will install globally
npm install -g json-server
- create file db.json
- write this structure json
{
"users": [
{
"id": 1,
"first_name": "Sonny",
"last_name": "Allward",
"email": "sallward0@umn.edu",
"gender": "Genderfluid",
"ip_address": "24.3.199.140"
},
{
"id": 2,
"first_name": "Manfred",
"last_name": "Erickson",
"email": "merickson1d@mapquest.com",
"gender": "Genderfluid",
"ip_address": "103.30.222.192"
}
],
"products": [
{
"id": 1,
"product_name": "Beets",
"sku": "54949-004",
"price": 27,
"category": "Beauty",
"quantity": 69
},
{
"id": 2,
"product_name": "Wine - Mondavi Coastal Private",
"sku": "46122-146",
"price": 63,
"category": "Home",
"quantity": 12
}
]
}
- running JSON Server
npm run json:server --watch db.json
Call Request
- Get all data
http://localhost:3000/users
- Get one data, method GET
http://localhost:3000/users/1
- Search data, method GET
http://localhost:3000/users?first_name=Manfred
- Pagination, method GET
http://localhost:3000/users?_limit=10&_page=5
- Sorting, method GET
http://localhost:3000/users?_sort=id&_order=DESC
- Create data, method POST
http://localhost:3000/users
body:
{
"id": 51,
"first_name": "Itje",
"last_name": "Juice",
"email": "itje@yale.edu",
"gender": "Helicopter",
"ip_address": "44.73.130.666"
}
- Delete data, method DELETE
http://localhost:3000/users/1
Github URL: [https://github.com/rocklinda/mock-api]
NPM JSON Server: [https://www.npmjs.com/package/json-server]
Top comments (1)
Hi, a few weeks ago I descovered an online tool for mockup APIs or fake APIs. The name of the tool is: DevApiService