Wednesday, July 3, 2024
HomeLanguagesReactHow to Create RESTful API and Fetch Data using ReactJS ?

How to Create RESTful API and Fetch Data using ReactJS ?

ReactJS is an open-source JavaScript library used to create user interfaces in a declarative and efficient way. It is a component-based front-end library responsible only for the view layer of a Model View Controller (MVC) architecture.

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.

RESTAPI.png

REST 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?

  • 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 API is simple to scale and administer because 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.

Let’s start building our very own RESTful API

Prerequisites:

  • Node JS
  • React

As we are creating a REST API in our local environment so we need all three things:

  • Backend(Server)
  • API
  • Frontend(For fetching and displaying API data).

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 because we are using ReactJs and need the react project files and all other necessary files in our frontend folder.

npx create-react-app frontend

Step 3: Now we have to install all Node modules and npm packages for our project’s backend so that we can easily run our server.

Before that, we have to enter the backend folder for that run:

cd backend
npm init -y

Step 4: 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

Install the necessary dependencies:

npm install express cors --save

Currently, the file structure looks like this:

File-structure

File Structure

Step 5: Let us create a “products.json” file inside the backend folder with dummy product data for the project, in the JSON file we will have product “id”, “name”, “description”, “price”, and “image”.

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.

But here we used image links for our products.

  • products.json file

Javascript




//products.json
[
    {
        "id": 1,
        "name": "Product 1",
        "description": "Description of Product 1",
        "price": 9.99,
    },
    {
        "id": 2,
        "name": "Product 2",
        "description": "Description of Product 2",
        "price": 19.99,
    },
    {
        "id": 3,
        "name": "Product 3",
        "description": "Description of Product 3",
        "price": 20,
    },
    {
        "id": 4,
        "name": "Product 4",
        "description": "Description of Product 4",
        "price": 25,
    },
    {
        "id": 5,
        "name": "Product 5",
        "description": "Description of Product 5",
        "price": 30,
    },
    {
        "id": 6,
        "name": "Product 6",
        "description": "Description of Product 6",
        "price": 999,
    }
]


Step 6: Create an index.js file inside the backend folder. Let’s begin by working on the index.js file, which is the main backend file required to operate the backend and host the server.

  • index.js file

Javascript




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'); 
});


First, we require the “express” to run the server and then we import the local JSON file data from the “products.json” file. Following that, we developed an API to transfer data to the front end, and while transferring we must send the JSON format otherwise we will get an error. Here we are running the server on the 5000 port.

Our work on the backend is now complete, and we must begin work on the front end. To simply fetch the data from the backend, we must first install the “Axios” node module for our project.

Step 7: Now run the below command to install Axios:

cd frontend
npm i axios

Since all we need to do is use our REST API to get the data from the backend and display it on the site. Therefore, we simply use the App.js file

  • App.js file

Javascript




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;


  • App.css file

CSS




.products {
    display: flex;
    flex-direction: row;
    margin-top: 30vh;
    justify-content: space-between;
    text-align: center;
}
  
.img {
    height: 100px;
    width: 100px;
}


Step 8: 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“. Now in the backend run the command “nodemon” and in the frontend run “npm start“. It will start at both the backend and the front end.

Now open the browser and check the result:

Output:

Animation

This is the result of our REST API, and the data was successfully and error-free retrieved. We hope that this lesson has given you a better understanding of how REST APIs operate and how simple it is to build our own REST APIs.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments