Mockup API With JSON Server
source link: https://dev.to/rocklinda/mockup-api-with-json-server-3kb8
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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": "[email protected]",
"gender": "Genderfluid",
"ip_address": "24.3.199.140"
},
{
"id": 2,
"first_name": "Manfred",
"last_name": "Erickson",
"email": "[email protected]",
"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": "[email protected]",
"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]
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK