Sitemap
How To React

Learn how to create fast, interactive web apps using react.

How to use JSON file as a server for fake API in React JS

--

In this tutorial, we will learn how to use a JSON file as a server for a fake API in React JS. This is useful when we want to test our application without relying on a real API. By using a JSON file as a fake API, we can easily mock API responses and test different scenarios without making real API calls.

Requirements

Step 1: Create a JSON file
Create a new JSON file in your React project and name it “db.json”. In this file, we will define the API responses that we want to mock. Here’s an example:

Step 2: Install json-server
We will use the json-server package to simulate a REST API from our JSON file. To install it, run the following command in your terminal:

npm install -g json-server

Step 3: Start the JSON server
To start the JSON server, run the following command in your terminal and specify the path to your JSON file:

json-server --watch db.json --port 3030

Note: React utilizes the 3000 port, which json-server uses to run the server, thus we used — port 3030to modify the port.

Step 4: Test API
Now if we open http://localhost:3030/posts on our browser, we can see our data.

Step 5: Make API requests in React
In your React component, use the fetch API or any other HTTP client library to make API requests to the JSON server. Here’s an example using fetch:

So we have successfully created our fake API request and fetched data through it to our React component. Not only GET requests but we can also use POST requests to insert data into our JSON file, PUT requests to update the data, and DELETE request to delete our JSON data. Let’s see using that in the postman.

POST REQUEST

To add a new post to our JSON file you need to make a POST request and add JSON data using the body. Here’s an example:

PUT REQUEST

If we need to update the data we can use the PUT request to update it. Here’s an example:

DELETE REQUEST

To delete the data from our JSON file we can use the DELETE request. Here’s an example:

That’s it! By using a JSON file as a fake API in React JS, we can easily test our application without relying on a real API. This is a quick and easy solution for testing purposes, and it allows us to mock different API responses and test different scenarios without making real API calls.

For any query, you can get in touch with me via LinkedIn

That’s it for today below you can find the GitHub repository.

--

--

How To React
How To React

Published in How To React

Learn how to create fast, interactive web apps using react.

Manish Mandal
Manish Mandal

Written by Manish Mandal

Full Stack Developer | React JS | Next JS | Node JS | Vue JS | Wordpress. Connect with me https://www.linkedin.com/in/manishmandal21/

Responses (2)