Setting Up a JSON Server: Step-by-Step Guide
Overview
This guide will walk you through setting up a mock JSON server that simulates a backend, using names in the dataset. We’ll also connect to this server using Postman to confirm everything works.
Step 1: Install json-server
First, install json-server
globally on your system. Open a terminal and run:
npm install -g json-server
This installs the json-server
package so you can use it anywhere. Verify the installation by
running:
json-server --version
If the version number appears, the installation is successful.
Step 2: Create a db.json File
In your project folder, create a file named db.json
. This file will act as your mock
database. Add the following names as data:
{
"posts": [
{ "id": 1, "title": "Learning JSON Server", "author": "Popat" },
{ "id": 2, "title": "Building APIs with json-server", "author": "Champak" }
],
"comments": [
{ "id": 1, "postId": 1, "body": "Well explained, Popat!" },
{ "id": 2, "postId": 2, "body": "Thanks for this guide, Champak." }
],
"profile": { "name": "Daya" }
}
This data structure simulates posts, comments, and a profile.
Step 3: Start the JSON Server
In the directory containing the db.json
file, run the following command to start the server:
json-server --watch db.json
By default, the server will run on http://localhost:3000
.
You’ll see output similar to this:
\{^_^}/ hi!
Loading db.json
Done
Resources
http://localhost:3000/posts
http://localhost:3000/comments
http://localhost:3000/profile
Step 4: Test with Postman
Now, open Postman and perform the following tests:
- GET Request: Create a new request in Postman, set the method to
GET
, and use the URLhttp://localhost:3000/posts
. - POST Request: Add a new post using
POST
method and the URLhttp://localhost:3000/posts
. In the body, set it toraw
and format as JSON. Add:{ "title": "New Post on APIs", "author": "Arjun" }
Ensure that the requests respond correctly with the expected JSON data.
Step 5: Additional Operations with Postman
Test the following operations:
- PUT Request: Update a post using the URL
http://localhost:3000/posts/1
. Set the method toPUT
and enter new data in the body:{ "title": "Updated Post", "author": "Popat" }
- DELETE Request: Delete a post using the
DELETE
method with the URLhttp://localhost:3000/posts/1
.
Step 6: Customizing the JSON Server
You can create custom routes by adding a routes.json
file. For example:
{
"/api/posts": "/posts",
"/api/comments": "/comments"
}
Run the server with custom routes:
json-server --watch db.json --routes routes.json
Additionally, you can simulate a delay in responses using:
json-server --watch db.json --delay 1000
Folder Structure
The following diagram illustrates the folder structure for this project:
- project-directory/
- db.json
- routes.json
- node_modules/
- package.json
- README.md
This structure includes the mock database db.json
, optional route customizations in
routes.json
, and other typical project files.
0 Comments