JSON Server is a simple yet powerful tool frontend developers use to create a mock REST API for development and testing purposes. It allows front end developers to develop a full fake REST API with zero coding in seconds. JSON Server is based on JavaScript Object Notation (JSON), a lightweight data-interchange format that's easy to read and write.
The JSON Server provides all the RESTful routing and responses out of the box, making it a great tool for quickly prototyping and developing applications. It uses a JSON file as a database, allowing you to retrieve data, create new data, update existing data, and delete data using standard HTTP requests.
In frontend development, the JSON Server plays a crucial role. It allows developers to mock the backend setup and start developing the frontend without waiting for the backend to be ready. This is particularly useful in a microservices environment where the frontend and backend are developed concurrently.
The JSON Server helps frontend developers simulate all types of HTTP requests (GET, POST, PATCH, DELETE) to the mock server. This aids in developing interactive applications that need to fetch data, create new data, update existing data, or delete data from the server.
Using JSON Server for frontend development offers numerous advantages:
To begin using JSON Server, you first need to install it. This is accomplished by using Node Package Manager (npm). You must do that first if you still need to install Node.js and npm. Once you have npm installed, you can install JSON Server by running the following command in your terminal:
1npm install json-server
This command installs JSON Server globally on your system, allowing you to start the server from any directory.
After installing JSON Server, the next step is to start it. To do this, you'll need a JSON file that will act as your database for the mock server. Let's create a db.json file with some sample json data here:
1{ 2 "users": [ 3 { "id": 1, "name": "John Doe", "email": "john@example.com" }, 4 { "id": 2, "name": "Jane Doe", "email": "jane@example.com" } 5 ] 6}
Now, you can start JSON Server by running the following command:
1json-server --watch db.json
This command tells JSON Server to start and watch the db.json file. Any changes made to this file will be reflected in the API.
The json-server --watch db.json command is the most basic command to start JSON Server. However, JSON Server provides several other commands and options for more advanced use cases.
For example, you can specify a different port for JSON Server to run on using the --port option:
1json-server --watch db.json --port 4000
This command starts JSON Server on port 4000 instead of the default port 3000.
The JSON file used by the JSON Server acts as a mock database for your project. This file is structured as a collection of key-value pairs, where each key represents a resource (like users, posts, comments, etc.) and the value is an array of objects, each object being a record in that resource.
Here's a simple example of a JSON file structure:
1{ 2 "users": [ 3 { "id": 1, "name": "John Doe", "email": "john@example.com" }, 4 { "id": 2, "name": "Jane Doe", "email": "jane@example.com" } 5 ], 6 "posts": [ 7 { "id": 1, "title": "First Post", "content": "This is the first post.", "userId": 1 }, 8 { "id": 2, "title": "Second Post", "content": "This is the second post.", "userId": 2 } 9 ] 10}
In this example, "users" and "posts" are resources; each object within the array is a record.
To generate sample data for interactive application from the JSON database, you can manually create records in the JSON file or use a tool to generate fake data. The data should be representative of the data your application will handle.
For instance, if you're developing a blog application, your JSON file might include resources for users, posts, and comments. Each post might include an ID, title, content, and userID to link it to a user.
Once your JSON file is set up with sample data, you can configure JSON Server to watch this file. This is done using the --watch option in the JSON Server command:
1json-server --watch db.json
With this command, JSON Server will start and provide endpoints corresponding to the resources in your JSON file. Any changes you make to the db.json file will be reflected in these endpoints, allowing you to test different scenarios by simply updating the JSON file.
Once the JSON Server runs, you can start making HTTP requests to interact with your data. To fetch data from the server, you make a GET request. For instance, you would send a GET request to http://localhost:3000/users
to fetch all users.
In JavaScript, you can use the fetch API to make this request:
1fetch('http://localhost:3000/users') 2 .then(response => response.json()) 3 .then(users => console.log(users));
This code fetches the list of users from the server and logs them to the console.
You make a POST request to add new data to your JSON database. For instance, to add a new user, you would send a POST request to http://localhost:3000/users
with the user data in the request body.
Here's how you can do this in JavaScript:
1const newUser = { name: 'New User', email: 'newuser@example.com' }; 2 3fetch('http://localhost:3000/users', { 4 method: 'POST', 5 headers: { 6 'Content-Type': 'application/json', 7 }, 8 body: JSON.stringify(newUser), 9}) 10.then(response => response.json()) 11.then(user => console.log(user));
This code sends a POST request to add a new user to the server.
You make a PATCH request to update existing data in your JSON database. For instance, to update a user's email, you would send a PATCH request to http://localhost:3000/users/:id
with the updated data in the request body.
Here's an example in JavaScript:
1const updatedUser = { email: 'updatedemail@example.com' }; 2 3fetch('http://localhost:3000/users/1', { 4 method: 'PATCH', 5 headers: { 6 'Content-Type': 'application/json', 7 }, 8 body: JSON.stringify(updatedUser), 9}) 10.then(response => response.json()) 11.then(user => console.log(user));
This code sends a PATCH request to update the user's email with ID 1.
To remove data from your JSON database, you make a DELETE request. For instance, to delete a user, you would send a DELETE request to http://localhost:3000/users/:id
.
Here's how you can do this in JavaScript:
1fetch('http://localhost:3000/users/1', { 2 method: 'DELETE', 3}) 4.then(response => response.json()) 5.then(() => console.log('User deleted'));
This code sends a DELETE request to remove the user with ID 1 from the server.
One of the powerful features of JSON Server is the ability to create custom routes. This allows you to tailor the API endpoints to your specific needs. For instance, you can create a custom route fetching users and their posts.
Add a routes.json file in your project root directory to create custom routes. This file should map your custom routes to the default routes provided by the JSON Server.
Here's an example of a routes.json file:
1{ 2 "/api/users/:id/posts": "/posts?userId=:id" 3}
This custom route fetches all posts of a specific user.
JSON Server provides routes for each resource in your JSON database file by default. These routes support all the standard RESTful operations (GET, POST, PATCH, DELETE).
Here are some examples of default routes:
These default routes can be used as is or customized to suit your needs better.
JSON Server also allows you to serve static files, such as images, stylesheets, and JavaScript files. This can be useful when you mock a full server environment, including serving static assets.
It would be best if you created a public directory to serve static files in your project root directory. JSON Server will automatically serve any files in this directory.
For example, if you have an image at public/img/logo.png, you can access it at the URL http://localhost:3000/img/logo.png
.
When starting JSON Server, You can specify custom directories to serve static files using the -s or --static option. For instance:
1json-server --watch db.json --static ./public --static ./assets
This command tells JSON Server to serve static files from public and asset directories.
Let's fetch and display this user data in a simple React application. We'll create a UserList component that fetches the user data and displays it in a list:
1import React, { useEffect, useState } from 'react'; 2 3function UserList() { 4 const [users, setUsers] = useState([]); 5 6 useEffect(() => { 7 fetch('http://localhost:3000/users') 8 .then(response => response.json()) 9 .then(setUsers); 10 }, []); 11 12 return ( 13 <ul> 14 {users.map(user => ( 15 <li key={user.id}>{user.name} ({user.email})</li> 16 ))} 17 </ul> 18 ); 19} 20 21export default UserList;
This component fetches the user data when it mounts and updates its state with the fetched data, causing a re-render and displaying the user data in the list.
Finally, let's look at how we can make POST, PATCH, and DELETE requests. We'll create a UserForm component that allows us to add new users, update existing users, and delete users:
1import React, { useState } from 'react'; 2 3function UserForm() { 4 const [name, setName] = useState(''); 5 const [email, setEmail] = useState(''); 6 7 const handleSubmit = event => { 8 event.preventDefault(); 9 10 // Add a new user 11 fetch('http://localhost:3000/users', { 12 method: 'POST', 13 headers: { 'Content-Type': 'application/json' }, 14 body: JSON.stringify({ name, email }), 15 }) 16 .then(response => response.json()) 17 .then(user => console.log('User added:', user)); 18 19 // Clear the form 20 setName(''); 21 setEmail(''); 22 }; 23 24 return ( 25 <form onSubmit={handleSubmit}> 26 <input type="text" value={name} onChange={e => setName(e.target.value)} placeholder="Name" required /> 27 <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="Email" required /> 28 <button type="submit">Add User</button> 29 </form> 30 ); 31} 32 33export default UserForm;
This component includes a form where you can enter a name and email. When you submit the form, it sends a POST request to add a new user with the entered name and email. After the user is added, it clears the form.
To illustrate how to make a PATCH request, let's create a UserUpdateForm component. This component will allow us to update a user's email based on their ID:
1import React, { useState } from 'react'; 2 3function UserUpdateForm() { 4 const [id, setId] = useState(''); 5 const [email, setEmail] = useState(''); 6 7 const handleSubmit = event => { 8 event.preventDefault(); 9 10 // Update user's email 11 fetch(`http://localhost:3000/users/${id}`, { 12 method: 'PATCH', 13 headers: { 'Content-Type': 'application/json' }, 14 body: JSON.stringify({ email }), 15 }) 16 .then(response => response.json()) 17 .then(user => console.log('User updated:', user)); 18 19 // Clear the form 20 setId(''); 21 setEmail(''); 22 }; 23 24 return ( 25 <form onSubmit={handleSubmit}> 26 <input type="text" value={id} onChange={e => setId(e.target.value)} placeholder="User ID" required /> 27 <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="New Email" required /> 28 <button type="submit">Update User</button> 29 </form> 30 ); 31} 32 33export default UserUpdateForm;
You can enter a user's ID and the new email in this component. When you submit the form, it sends a PATCH request to update the user's email. After the user is updated, it clears the form.
In conclusion, JSON Server is a powerful tool that allows frontend developers to create a full fake REST API with zero coding in seconds. It provides a quick and simple way to set up a mock server for development and testing purposes, supporting all the basic CRUD operations and serving static files.
With the ability to create custom routes, JSON Server offers flexibility in how the API endpoints are structured. Furthermore, using a JSON file as a database ensures data consistency across different application parts.
JSON Server boosts your productivity and enhances the overall development experience by allowing you to focus on building your application without worrying about setting up a backend.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.