No, Axios is a JavaScript library used to make HTTP requests, including those to REST APIs. It’s a tool for interacting with APIs, not an API itself.
Key takeaways:
RESTful APIs use HTTP requests like GET, POST, PUT, and DELETE to perform operations on resources.
Express.js simplifies the process of handling HTTP requests and defining routes for backend services.
The
fetch()
method in React is used to asynchronously retrieve data from a server and update the component’s state.React’s useEffect hook helps in fetching data once the component is mounted, ensuring proper data flow.
Data from the API is mapped and displayed dynamically in the React component’s UI.
A RESTful (Representational State Transfer) API is an architectural style that uses HTTP requests to transmit data. It utilizes standard HTTP methods like GET, POST, PUT, and DELETE to perform operations on resources identified by URIs. It provides a standard way for web applications to communicate with each other over a network. It can be termed as a gateway between clients and resources of a web page.
Let’s go through a step-by-step coding example to build a RESTful API in React and fetch data from the server. We’ll then set up the backend to support our frontend web application.
Let’s create the backend to create the respective route using which the data will be requested from the frontend side. We’ll use the Node and Express to set up a server to efficiently handle HTTP requests and responses. Express simplifies this process by providing a framework for defining routes and middleware.
Here is the code for managing the server-side route:
const express = require('express');const app = express();const PORT = 3000;// The dummy data that will be transferred as a responseconst usersData = [{id: 1, name: 'John', email: "john@gmail.com", city: "Berlin"},{id: 2, name: 'Sam', email: "sam@gmail.com", city: "Amstardam"},{id: 3, name: 'Jordan', email: "jordan@gmail.com", city: "Hamburg" },{id: 4, name: 'Harry', email:"harry@gmail.com", city: "Munich"},{id: 5, name: 'Smith', email: "smith@gmail", city: "Bremen"},{id: 6, name: 'Aila', email: "aila@gmail", city: "Frankfurt"},{id: 7, name: 'Sara', email: "sara@gmail", city: "Bonn"}];// Defining the routeapp.get('/api/data', (req, res) => {res.json(usersData);});// Running serverapp.listen(PORT, () => {console.log(`Server is running on port ${PORT}`);});
Line 1: Import the express
framework.
Lines 3–4: Initialize the express application and set the port number(3000
) on which the server will listen for incoming requests.
Lines 7–15: Define the dummy data that will be transferred to the frontend application.
Lines 17–19: Define a route for handling GET requests to the api/data
endpoint.
Lines 21–23: Start the Express server and make it listen for incoming requests on the specified port.
Let’s create our frontend app using React. We’ll build a simple yet effective interface to interact with our backend. By making API requests to our server, we’ll fetch the data we need and display it on our app’s user interface.
We’ll use the fetch()
method to make an asynchronous HTTP request to the specified URL and retrieve data from the server. Let’s look at the syntax for this method:
const fetchData = async () => {try {const response = await fetch('URL');const jsonData = await response.json();setData(jsonData);} catch (error) {console.error('Error fetching data:', error);}};
In the syntax above:
fetch('URL')
: Sends an HTTP request to the specified URL.
await fetch('URL')
: Waits for the HTTP request to complete before proceeding.
response.json()
: Parses the response body as JSON and returns it as an object.
setData(jsonData)
: Updates the state with the parsed response data.
catch (error)
: Catches and handles any errors during the fetch process.
Now, let’s define the method to make an API call and send a request to the designated server:
const [data, setData] = useState([]);const fetchData = async () => {try {const response = await fetch('https://ed-5783469700939776.educative.run:3000/api/data');const jsonData = await response.json();setData(jsonData);} catch (error) {console.error('Error fetching data:', error);}};
Line 1: Create a useState
Hook to store the data (that will be retrieved from the server).
Line 3: Define an asynchronous function named fetchData()
. The async
keyword represents that the function will operate asynchronously, allowing the use of await
within it to handle promises.
Lines 5–7: Make a GET request to the specified URL and store the retrieved JSON data in a state variable.
Lines 8–10: Catch the errors from fetch()
operations, providing details about network or server issues to the console.
We’ll use the useEffect
Hook to execute the fetchData()
function when the component mounts, ensuring the data is fetched from the server after the component is rendered, and using the map()
method to display all data one by one to the user interface as follows:
function App() {return (<div className="App"><h1>Implement RESTFUL API to fetch data from server</h1><ul className="data-list">{data.map(item => (<li key={item.id}>{item.name} {item.email} {item.city}</li>))}</ul></div>);}
The code fetches data from a server, then maps over the data
array to display each item’s name
, email
, and city
in an unordered list (<ul>
), with each list item (<li>
) having a unique key based on the item’s id
.
Here’s the complete executable React application, along with the server in the backend:
Note: After successfully running the React application, add a new terminal using the "+" button, and run the server using
cd RESTFULAPI/backend && node server.js
command. Also, append:3000/api/data
to the URL after running the server.
{ "name": "backend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "cors": "^2.8.5", "express": "^4.18.2" } }
Building a RESTful API and fetching data in React involves a well-coordinated process between the backend and frontend. Using Node.js with Express.js, we can efficiently handle HTTP requests on the backend, setting up routes to serve data to the frontend. The React frontend uses the fetch() method to asynchronously retrieve data, which is then dynamically displayed in the component’s UI. By leveraging React’s useEffect
hook, we ensure that data is fetched when the component is mounted, providing a smooth and responsive user experience.
This integration allows the frontend and backend to communicate seamlessly, making it possible to create dynamic, data-driven applications.
Haven’t found what you were looking for? Contact Us
Free Resources