What is JSON Server?
15 April 2025 | Category: JavaScript
JSON Server is a simple tool that lets you create a full fake REST API with a single JSON file. It’s widely used by frontend developers to simulate backend functionality during development and testing.
✅ It allows you to perform CRUD operations (Create, Read, Update, Delete) on local JSON data, just like working with a real database.
🚀 Why Use JSON Server?
- No backend setup needed
- Instantly create an API with a JSON file
- Supports RESTful routes
- Quick to set up and start using
- Great for mock data testing
🛠️ Installation
🔸 Install via npm (Node.js required)
npm install -g json-server
You can also install it locally for a specific project:
npm install json-server --save-dev
📁 Step-by-Step Example
🔹 1. Create a JSON file (e.g., db.json
)
{
"users": [
{ "id": 1, "name": "Alice", "age": 25 },
{ "id": 2, "name": "Bob", "age": 30 }
]
}
🔹 2. Start the JSON Server
json-server --watch db.json
By default, the server runs at
http://localhost:3000
📡 Available REST API Endpoints
For users
in db.json
, JSON Server automatically provides:
Method | Endpoint | Description |
---|---|---|
GET | /users | Get all users |
GET | /users/1 | Get user by ID |
POST | /users | Add a new user |
PUT | /users/1 | Update entire user |
PATCH | /users/1 | Update partial user |
DELETE | /users/1 | Delete user by ID |
✏️ Example Usage with fetch()
GET all users:
fetch("http://localhost:3000/users")
.then(res => res.json())
.then(data => console.log(data));
POST a new user:
fetch("http://localhost:3000/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name: "Charlie", age: 28 })
});
📂 Folder Structure (Optional Custom Setup)
my-project/
├── db.json
├── package.json
├── index.html
└── script.js
You can also add routes.json
to create custom routes.
⚙️ Extra Features
- Add
_sort
,_order
,_limit
,_page
in URLs for query handling:/users?_sort=name&_order=asc&_limit=2
- Filter by parameters:
/users?age=25
- Search:
/users?q=Alice
✅ Summary
Feature | Details |
---|---|
Use | Fake REST API for development |
Setup | Node + npm required |
Data source | Single JSON file |
Supports | GET, POST, PUT, PATCH, DELETE |
Useful for | Frontend devs testing with mock backend |