Consuming REST APIs in React

misszamzam

Zamzam Hassan

Posted on May 3, 2023

Consuming REST APIs in React

What is a REST API?

Imagine you want to get some information from a website or an application. For example, you want to get a list of all the movies available on Netflix.

A REST API is like a waiter who can get you that information. You tell the waiter what you want( in this case, a list of movies), and the waiter goes to the kitchen( in this case, the server where the information is stored), gets the information( the list of movies), and brings it back to you( the client who made the request).

API-Waiters

REST stands for Representational State Transfer, which is just a fancy way of saying that the information is transferred from the server to the client in a standardized way. The API uses URLs to identify specific servers( in this case, the list of movies), and it uses HTTP methods like GET, POST, PUT, and cancel to DELETE, read, update, and delete those resources.

So when you make a request to a REST API, you are asking the server for a specific resource using a URL and an HTTP system, and the server responds with the requested resource in a standardized format like JSON or XML.

JSON is extensively used because it's not bound to any particular programming language and can be understood understood by both humans and machines.

For example:




{
  "Title": "The Avengers",
  "Year": "2012",
  "Rated": "PG-13",
  "Released": "04 May 2012",
  "Runtime": "143 min",
  "Genre": "Action, Sci-Fi, Thriller",
  "Director": "Joss Whedon",
  "Writer": [
    "Joss Whedon (screenplay)",
    "Zak Penn (story)",
    "Joss Whedon (story)"
  ],
  "Actors": [
    "Robert Downey Jr.",
    "Chris Evans",
    "Mark Ruffalo",
    "Chris Hemsworth"
  ]
}





Enter fullscreen mode Exit fullscreen mode

Consuming REST APIs in React

Consuming REST APIs in React is a common task for building web applications. In this guide, I will walk you through the steps required to consume a REST API in a React application.

To fully comprehend how to consume APIs in React, it's crucial to acknowledge that this process varies greatly from how it's traditionally done in JavaScript, due to the fact that these requests are now executed within a React Component.

For our scenario, we'll be utilizing functional components, which necessitates utilizing two primary React Hooks:

useState() is a hook that allows you to declare state variables and update them when needed. For example, you might use useState() to declare a data variable that will hold the response data from your API.



  const [movies, setMovies] = useState([]);



Enter fullscreen mode Exit fullscreen mode

useEffect() It is within this particular Hook that we perform API requests.It will either run when the component is first mounted, or after a specific state has been reached.



useEffect(() => {
    // data fetching here
}, []);


Enter fullscreen mode Exit fullscreen mode

The most popular approaches are Axios and Fetch API.Let's cover axios approach today

Using Axios

Step 1:
Install Axios
Axios is a popular library for making HTTP requests from the browser. To install Axios, run the following command in your terminal:



npm install axios



Enter fullscreen mode Exit fullscreen mode

Step 2:
Import the useState and useEffect hooks from React, and the axios library for making HTTP requests.



import React, { useState, useEffect } from 'react';
import axios from 'axios';


Enter fullscreen mode Exit fullscreen mode

Step 3:
We declare a state variable movies using the useState hook, which will hold the list of movies returned from the API.



  const [movies, setMovies] = useState([]);



Enter fullscreen mode Exit fullscreen mode

Step 4:
We then use the useEffect hook to make an HTTP GET request to the API endpoint https://api.example.com/movies and update the movies state with the response data using the setMovies function.



useEffect(() => {
    axios.get('https://api.example.com/movies')
      .then(response => {
        setMovies(response.data);
      })
      .catch(error => {
        console.log(error);
      });
  }, []);



Enter fullscreen mode Exit fullscreen mode

Step 5:
Finally, we render the list of movies using the map function.



  return (
    <div>
      <h2>List of Movies</h2>
      <ul>
        {movies.map(movie => (
          <li key={movie.id}>
            {movie.title}
          </li>
        ))}
      </ul>
    </div>
  );


Enter fullscreen mode Exit fullscreen mode

This is the final product when all those steps are put together




import React, { useState, useEffect } from 'react';
import axios from 'axios';

const MovieList = () => {
  const [movies, setMovies] = useState([]);

  useEffect(() => {
    axios.get('https://api.example.com/movies')
      .then(response => {
        setMovies(response.data);
      })
      .catch(error => {
        console.log(error);
      });
  }, []);

  return (
    <div>
      <h2>List of Movies</h2>
      <ul>
        {movies.map(movie => (
          <li key={movie.id}>
            {movie.title}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default MovieList;



Enter fullscreen mode Exit fullscreen mode

You can customize this example to fit your specific use case by replacing the API endpoint and modifying the rendering of the data.

💖 💪 🙅 🚩
misszamzam
Zamzam Hassan

Posted on May 3, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Consuming REST APIs in React
webdev Consuming REST APIs in React

May 3, 2023