How to Create RESTful API and Fetch Data using ReactJS ?
Last Updated :
08 Jan, 2025
React JS is more than just an open-source JavaScript library, it's a powerful tool for crafting user interfaces with unparalleled efficiency and clarity. One of React's core principles is its component-based architecture, which aligns perfectly with the Model View Controller (MVC) pattern. React components encapsulate pieces of UI functionality and logic, making them reusable, maintainable, and easy to reason about. As a result, developers can focus solely on building the view layer of their applications, confident that React will handle updates and rendering optimizations with ease. In this article, we will see how we can create the RESTful API and Fetch the Data using ReactJS.
Prerequisites
The REST API is now essential for any developer who wants to create a web application or a mobile application. To do this, we must first grasp what a RESTful API is so that we may construct one from the ground up simply and effectively.
Here, we'll create a REST API using a local environment and local database, then use ReactJS to display the data.
REST APIWhat is RESTful API?
REST API stands for Representational State Transfer Application Programming Interface. It is a collection of architectural guidelines and best practices for creating web services that enable various systems to interact and communicate with one another over the Internet. Due to their simplicity, scalability, and usability, RESTful APIs are a popular choice for developing web applications and services.
Why should we use REST API in our web apps and services?
Let's see the table to understand Why should we use REST API in our web apps and services?
Concept | Description |
---|
Resources | In REST API, everything is treated as resources, such as data objects or services. These resources are uniquely identified by URLs (Uniform Resources Locators). |
Statelessness | Each request made by a client to a server must provide all the details required to comprehend and handle the request. The server does not save any data regarding the client's state between queries. |
HTTP Methods | RESTful APIs use standard HTTP methods to perform CRUD(Create, Read, Update, Delete) operations on resources. The common methods are GET(read), POST(create), PUT(update), and DELETE(delete). |
Representations | Resources can have multiple representations, such as JSON, XML, HTML, or others. Clients can specify the desired representation using the HTTP "Accept" header. |
Stateless Communication | Each request made by the client to the server must include all required data. The client's state in-between queries is not recorded by the server. This approach makes it easier to implement the server and improves scalability. |
Start Creating Project and Install the Required Node Modules
Step 1: Create two separate folders one for our backend and the second for our frontend. You can run these commands in your terminal or you can create them on your own with GUI.
cd ReactProject
mkdir backend
Step 2: We will run a command to install all react dependencies and necessary files.
npx create-react-app frontend
Step 3: Now we have to install all Node modules and npm packages for backend.
cd backend
npm init -y
Step 3: This command will create the package.json files where we will able to see our dependencies. So let's install the required dependencies
npm i express nodemon
npm install express cors --save
Project Structure:
Folder Structure -The updated dependencies in package.json file will look like:
Backend:
"dependencies": {
"express": "^4.18.2",
"nodemon": "^3.0.2"
}
Frontend:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Step 4: Create the following files in the backend.
Note: In order to be able to fetch the product photos on the client side, we must place the images folder—which contains the product images—inside the public folder of ReactJS.
JavaScript
//products.json
[
{
"id": 1,
"name": "Product 1",
"description": "Description of Product 1",
"price": 9.99,
"image": "https://media.geeksforgeeks.org/wp-content/uploads/20230728154500/download-(1).jfif"
},
{
"id": 2,
"name": "Product 2",
"description": "Description of Product 2",
"price": 19.99,
"image": "https://media.geeksforgeeks.org/wp-content/uploads/20230728154740/download-(2).jfif"
},
{
"id": 3,
"name": "Product 3",
"description": "Description of Product 3",
"price": 20,
"image": "https://media.geeksforgeeks.org/wp-content/uploads/20230728154838/download-(3).jfif"
},
{
"id": 4,
"name": "Product 4",
"description": "Description of Product 4",
"price": 25,
"image": "https://media.geeksforgeeks.org/wp-content/uploads/20230728154931/download.jfif"
},
{
"id": 5,
"name": "Product 5",
"description": "Description of Product 5",
"price": 30,
"image": "https://media.geeksforgeeks.org/wp-content/uploads/20230728155132/images-(1).jfif"
},
{
"id": 6,
"name": "Product 6",
"description": "Description of Product 6",
"price": 999,
"image": "https://media.geeksforgeeks.org/wp-content/uploads/20230728155224/images.jfif"
}
]
JavaScript
//index.js
const express = require('express');
const app = express();
const cors = require('cors');
app.use(express.json())
const data = require('./products.json')
app.use(cors());
// REST API to get all products details at once
// With this api the frontend will only get the data
// The frontend cannot modify or update the data
// Because we are only using the GET method here.
app.get("/api/products", (req, res) => {
res.json(data)
});
app.listen(5000, () => {
console.log('Server started on port 5000');
});
Step 5: Now run the below command to install Axios:
cd frontend
npm i axios
Step 6: Add this code in the frontend files.
CSS
/*App.css*/
.products {
display: flex;
flex-direction: row;
margin-top: 30vh;
justify-content: space-between;
text-align: center;
}
.img {
height: 100px;
width: 100px;
}
JavaScript
//App.js
import React, { useState, useEffect } from 'react';
import axios from "axios";
import './App.css';
function App() {
const [data, setData] = useState();
useEffect(() => {
axios.get('http://localhost:5000/api/products').then(
response => {
setData(response.data);
}
).catch(error => {
console.error(error);
})
}, [])
return (
<div className="App">
{
<div className='products'>
{data?.map((data) => {
return (
<div key={data.id}>
<img className='img'
src={data.image}
alt="img" />
<h1>{data.name}</h1>
<p>{data.description}</p>
</div>
);
})
}
</div>
}
</div>
);
}
export default App;
Step 7: Launch our website using localhost and see the outcomes. We have to operate the front end and back end simultaneously for that. Open two terminals and then "cd backend" & "cd frontend".
npm start
nodemon index.js
Output:

Similar Reads
How to create a food recipe app using ReactJS ? We are going to make a food recipe app using React.js.Pre-requisite:React hooksReact componentsJavaScript ES6APIÂ CSSApproach: Here in this app we should have a component where we are going to show our food recipes. And we need to fetch all the required food recipes using a food recipe API. We will f
3 min read
How to Fetch Data From an API in ReactJS? ReactJS provides several ways to interact with APIs, allowing you to retrieve data from the server and display it in your application. In this article, weâll walk you through different methods to fetch data from an API in ReactJS, including using the built-in fetch method, axios, and managing the st
8 min read
How to fetch data from APIs using Asynchronous await in ReactJS ? Fetching data from an API in ReactJS is a common and crucial task in modern web development. Fetching data from API helps in getting real-time updates dynamically and efficiently. API provides on-demand data as required rather than loading all data. PrerequisitesReact JSFetch data from APIApproachTo
3 min read
How to create a Location finder app using ReactJS ? In this article, we will be building a location finder app that lets you search for different places on a map. Our app contains two sections, one for displaying the marker on the map and the other is for searching different places. For rendering the map and getting the coordinates for the searched l
4 min read
Using Restify to Create a Simple API in Node.js Restify is an npm package that is used to create efficient and scalable RESTful APIs in Nodejs. The process of creating APIs using Restify is super simple. Building a RESTful API is a common requirement for many web applications. Restify is a popular Node.js framework that makes it easy to create RE
6 min read
Consuming a REST API ( Github Users ) using Fetch - React Client In this article, you will learn to develop a React application, which will fetch the data from a REST API using Fetch. We will use GitHub Users API to fetch the user's public information with their username. You can find the API reference and source code links at the end of this article.Prerequisite
2 min read
How to create a Dictionary App in ReactJS ? In this article, we will be building a very simple Dictionary app with the help of an API. This is a perfect project for beginners as it will teach you how to fetch information from an API and display it and some basics of how React actually works. Also, we will learn about how to use React icons. L
4 min read
How To Use JavaScript Fetch API To Get Data? An API is a set of rules, protocols, and tools that allows different software applications to communicate with each other. One of the popular ways to perform API requests in JavaScript is by using Fetch API. What is the Fetch API?The Fetch API is a built-in JavaScript feature that allows you to make
4 min read
How to handle data fetching in React-Redux Applications ? Data fetching in React-Redux applications is a common requirement to retrieve data from APIs or other sources and use it within your components. This article explores various approaches to handling data fetching in React-Redux applications, providing examples and explanations for each approach.Table
4 min read
How to use JavaScript Fetch API to Get Data ? The Fetch API provides a JavaScript interface that enables users to manipulate and access parts of the HTTP pipeline such as responses and requests. Fetch API has so many rich and exciting options like method, headers, body, referrer, mode, credentials, cache, redirect, integrity, and a few more. H
2 min read