How to Integrate React JS with a REST API: A Step-by-Step Guide

Table of contents
React is popular frontend JavaScript library for building web application. You need to integrate APIs in your react project for if you want to build production ready web application.
What is a REST API?
REST API stand for A Representational State Transfer Application Programming Interface. It is also known as RESTful API. It is an application programming interface that conforms to the constraints of REST architectural style and allows for interaction with RESTful web services.
When a client request is made via a RESTful API, it transfers a representation of the state of the resource to the requester or endpoint. This information, or representation, is delivered in one of several formats via HTTP: JSON (Javascript Object Notation), HTML, XLT, Python, PHP, or plain text. JSON is the most generally popular file format to use because, despite its name, it’s language-agnostic, as well as readable by both humans and machines.
What is an API?
API is a medium that allows different applications to communicate programmatically with one another and return a response in real time. It is a set of definitions and protocols for building and integrating application software.
In other words, if you want to interact with a computer or system to retrieve information or perform a function, an API helps you communicate what you want to that system so it can understand and fulfill the request.
How to consume REST API's in React.
We will use Fetch API which is browser in-built web API. You are going to use two popular react hook in your project.
useState
is a React Hook that lets you add a state variable to your component. We Call useState at the top level of your component to declare a state variable. In below example, initialState is the value you want the state to be initially.
Let's understand what is state in react. State is components memory.
const [state, setState] = useState(initialState)
useEffect
: is a React Hook that lets you synchronize a component with an external system. It allows you to perform side effects in functional components. Side effects could be data fetching, subscription, or manually changing the DOM. We will use this hook to fetch API response. It accepts two arguments : a callback function and a dependencies. Second argument is optional. The list of dependencies must have a constant number of items and be written inline like[dep1, dep2, dep3]
. React will compare each dependency with its previous value. If you omit this argument, your Effect will re-run after every re-render of the component.useEffect
returnsundefined
.Here's an example of useEffect Hook:
Copy
Copy
useEffect(() => { // data fetching here }, []);
We will fetch the user data from GitHub API. We will display the fetched user data including username, avatar, number of follower, and last but not the least total number of repositories. Here's an example of getting user details using APIs.
useEffect
: This hook runs after the component mounts to fetch data.
async/await
syntax is used for asynchronous operations.fetch
is used to make a GET request to the specified API endpoint..then()
is returned a response object.response.json()
parses the JSON response. And to resolve the Response object to JSON format..then()
used to get actual data.Error handling using
try...catch
block.
Copy
Copy
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(
"https://api.github.com/users/AnandAnkur404"
);
if (!response.ok) {
throw new Error("Failed to fetch user data");
}
const results = await response.json();
console.log(results);
setAvatarURL(results.avatar_url);
setGithubUserame(results.login);
setNoOfFollower(results.followers);
setNoOfRepo(results.public_repos);
} catch (error) {
console.log(error);
setError(error.message);
}
};
fetchData();
}, []);
Now we will get all the repository data from API.
import "./App.css";
import Button from "react-bootstrap/Button";
import Card from "react-bootstrap/Card";
import { useEffect, useState } from "react";
function App() {
const [avatarURL, setAvatarURL] = useState();
const [githubUserame, setGithubUserame] = useState();
const [noOfFollower, setNoOfFollower] = useState();
const [repoData, setRepoData] = useState();
const [noOfRepo, setNoOfRepo] = useState();
const [error, setError] = useState(null);
async function repoDataURL() {
try {
// Getting all the repos of users.
const response = await fetch(
"https://api.github.com/users/AnandAnkur404/repos"
);
if (!response.ok) {
throw new Error("Failed to fetch repo data");
}
const result = await response.json();
const list = result.map((item) => (
<div className="text-center" key={item.id}>
<a target="_blank" href={item.svn_url}>
{item.name}
</a>
</div>
));
setRepoData(list);
} catch (error) {
console.log(error);
setError(error.message);
}
}
}
Now we will consume data from this API and display.
return (
<div className="App w-100 min-vh-100 justify-content-center align-items-center d-flex flex-column">
<Card style={{ width: "18rem" }}>
<Card.Img variant="top" src={avatarURL} />
<Card.Body>
<Card.Title>{githubUserame}</Card.Title>
<Card.Text>
<h6>No Of Followers {noOfFollower}</h6>
<h6>No Of Public Repos {noOfRepo}</h6>
</Card.Text>
<Button variant="primary" onClick={repoDataURL}>
List My Repo
</Button>
</Card.Body>
</Card>
{ repoData };
</div>
);
Conclusion
Here you see how effectively we have integrated Rest API to our react application to build dynamic and data driven web application. In contrast, REST is a set of guidelines that can be implemented as needed, making REST APIs faster and more lightweight, with increased scalability. You can follow the above guideline and use your specific REST APIs to create your own project.
Resources
https://react.dev/reference/react
https://www.redhat.com/en/topics/api/what-is-a-rest-api#overview
https://www.freecodecamp.org/news/how-to-consume-rest-apis-in-react/
Subscribe to my newsletter
Read articles from Piyush Nanwani directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Piyush Nanwani
Piyush Nanwani
Experienced full-stack developer with a passion for tackling complex challenges. Dedicated to helping you become a top 1% mobile app developer. Passionate about mentoring, teaching, and continuous learning in new technologies.