How to Create RESTful API and Fetch Data using ReactJS ?
Last Updated :
23 Jul, 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
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. "Hello, World!" Program in ReactJavaScriptimport React from 'react'; function App() {
6 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides DOM-specific methods to interact with and manipulate the Document Object Model (DOM), enabling efficient rendering and management of web page elements. ReactDOM is used for: Rendering Components: Displays React components in the DOM.DOM Manipulation: Al
2 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsIn lists, React makes it easier to render multiple elements dynamically from arrays or objects, ensuring efficient and reusable code. Since nearly 85% of React projects involve displaying data collectionsâlike user profiles, product catalogs, or tasksâunderstanding how to work with lists.To render a
4 min read
React FormsIn React, forms are used to take input from users, like text, numbers, or selections. They work just like HTML forms but are often controlled by React state so you can easily track and update the input values.Example:JavaScriptimport React, { useState } from 'react'; function MyForm() { const [name,
4 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. When rendering a list, you need to assign a unique key prop to each element in th
4 min read
Components in React
React ComponentsIn React, components are reusable, independent code blocks (A function or a class) that define the structure and behavior of the UI. They accept inputs (props or properties) and return elements that describe what should appear on the screen.Key Concepts of React Components:Each component handles its
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.Example:JavaScriptimport
4 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
3 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem.Type Safety: When the wrong data type is passed in the component, prototypes help find the issues.Better Debugging: During development, t
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects