To use JSON Server for creating a simple REST API with a JSON file, follow these steps:
1. Install JSON Server
You need Node.js installed to use json-server
. You can install it globally using npm:
npm install -g json-server
2. Create a JSON File
Create a file named db.json
to serve as the database. For example:
{
"posts": [
{ "id": 1, "title": "Hello World", "author": "John Doe" },
{ "id": 2, "title": "JSON Server", "author": "Jane Doe" }
],
"comments": [
{ "id": 1, "postId": 1, "body": "Nice post!" }
]
}
3. Start JSON Server
You can start the server by running the following command in your terminal from the directory where your db.json file is:
json-server --watch db.json
By default, JSON Server runs on port 3000, so you can access your data via the following routes:
GET
/posts (Retrieve all posts)GET
/posts/1 (Retrieve post with id 1)POST
/posts (Create a new post)PUT
/posts/1 (Update post with id 1)DELETE
/posts/1 (Delete post with id 1)
4. Customizing the Port (Optional)
You can change the port by using the --port
option:
json-server --watch db.json --port 4000
5. Using JSON Server with Routes (Optional)
You can also create custom routes by using the routes.json
file to define custom paths:
{
"/api/posts": "/posts",
"/api/comments": "/comments"
}
To run the server with these custom routes:
json-server --watch db.json --routes routes.json
6. Run JSON Server Programmatically (Optional)
You can run JSON Server as part of your Node.js code:
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();
server.use(middlewares);
server.use(router);
server.listen(3000, () => {
console.log('JSON Server is running');
});
This setup allows you to quickly prototype APIs without having to write backend code.