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.w3wiki.org/wp-content/uploads/20230728154500/download-(1).jfif"
    },
    {
        "id": 2,
        "name": "Product 2",
        "description": "Description of Product 2",
        "price": 19.99,
        "image": "https://media.w3wiki.org/wp-content/uploads/20230728154740/download-(2).jfif"
    },
    {
        "id": 3,
        "name": "Product 3",
        "description": "Description of Product 3",
        "price": 20,
        "image": "https://media.w3wiki.org/wp-content/uploads/20230728154838/download-(3).jfif"
    },
    {
        "id": 4,
        "name": "Product 4",
        "description": "Description of Product 4",
        "price": 25,
        "image": "https://media.w3wiki.org/wp-content/uploads/20230728154931/download.jfif"
    },
    {
        "id": 5,
        "name": "Product 5",
        "description": "Description of Product 5",
        "price": 30,
        "image": "https://media.w3wiki.org/wp-content/uploads/20230728155132/images-(1).jfif"
    },
    {
        "id": 6,
        "name": "Product 6",
        "description": "Description of Product 6",
        "price": 999,
        "image": "https://media.w3wiki.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“.

  • In frontend
npm start
  • In backend
nodemon index.js

Output:



How to Create RESTful API and Fetch Data using ReactJS ?

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.

Table of Content

  • Prerequisites
  • What is RESTful API?
  • Why should we use REST API in our web apps and services?
  • Start Creating Project and Install the Required Node Modules

Similar Reads

Prerequisites

Knowledge of React JSJavaScript(es6+)Node and npm/yarn installedAPI concepts and Fetch API...

What 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?...

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....