DEV Community

Cover image for 🚀Introduction WEB API : Pioneering the Future of Rapid Web Integration🔥⭐
Bro Karim
Bro Karim

Posted on

🚀Introduction WEB API : Pioneering the Future of Rapid Web Integration🔥⭐

For developers diving into React, it's vital to grasp the art of using APIs to bring data into your web apps.

In this post, I'll summarize how to consume rest api in react application using fetch method and demonstrate its practical application in building a functional website.

Table of Content

What you need?

To initiate this project, there are several components required :

  • Command line or Terminal
    to run the necessary commands and start a react project

  • IDE (eg. VSC)
    For editing and debugging code

  • Web browser
    For real-time testing and visualization of your web application

  • Node JS 16+
    we will be utilizing React with Vite,so you'll need Node.js 16+ for this requirement

Project Overview

The most effective way to learn web development and coding is by putting your knowledge into practice through project building. That's why in this article, we'll construct an exciting project to help you gain a deeper understanding of web APIs.

Image description

We're going to create an attractive quote website that will generate inspiring quotes from renowned individuals using an API. We can also publish the quotes to our X (Twitter) account using a Twitter button from the X developer platform

Before we proceed, there are some key aspects about APIs that you should be aware of, So let's get started.

What exactly IS an API?

An API, which stands for "Application Programming Interface," is like a messenger that lets different computer programs talk to each other and share information quickly. It's important to note that an API is not the database or even the server, rather it's more like the set of rules that show how to get data from a computer.

One specific type of API is a REST API, which stands for Representational State Transfer. REST APIs use the internet's language, called HTTP, to send and get information. They know how to do four main things: get data, send new data, change data, and delete data.

In this project we will use fetch function to make requests to the REST API and retrieve the necessary data. To use the Fetch API in React, you can use the fetch() function. This function takes two arguments: the URL of the resource you want to fetch and an optional configuration object.

Consume Rest API
Consume a REST API means to use an API to retrieve or manipulate data, but before we get into how to consume APIs, it's important to understand that consuming APIs in React differs significantly from traditional JavaScript methods. This is because API requests are now made within React components.

In this case, we'll be using functional components, which means we need to use two major React hooks:

  • useState : is a React Hook that enables functional components to manage and update state within the component. It allows you to declare state variables and provides a method to update them. State variables help keep track of data that can change over time. When consuming a REST API, you can use useState to store and manage the data fetched from the API.

  • useEffect : is another React Hook that allows you to perform side effects in functional components. Side effects often include tasks like making API requests, setting up subscriptions, or manually changing the DOM. When it comes to consuming a REST API, useEffect is commonly used to initiate API requests when the component is mounted and to manage updates and re-fetching of data based on dependencies.

Here is an example of how to consume an API in React

import React, { useEffect, useState } from "react";

const API_ENDPOINT = "https://api.example.com/users";

const UserList = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    const fetchUsers = async () => {
      const response = await fetch(API_ENDPOINT);
      const usersData = await response.json();
      setUsers(usersData);
    };

    fetchUsers();
  }, []);

  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
};

Enter fullscreen mode Exit fullscreen mode
  • this code is a React component that fetch information about users from an external source (an API) and displays it in a simple list format.
  • The useEffect hook ensures that the data fetching is performed when the component is mounted
  • the fetched data is stored in the users state, which triggers a re-render to display the user list.

Now, we have a clear understanding that APIs are like tools that enable our websites to communicate with external information. One specific type of API we explored is the REST API. When working with REST APIs in a React project, we use the fetch() function. To make it all work seamlessly, we involve React's useEffect and useState. These tools help our project fetch and manage data from the API, making our applications dynamic and data-rich.

Create New Project

Before you get started, make sure you have Node.js and npm (Node Package Manager) installed on your system.

Open your terminal and run the following commands:

npm create vite@latest quote-api -- --template react

# Navigate into the project directory
cd quote-api
Enter fullscreen mode Exit fullscreen mode

This will create a new react with Vite project named quote-api and move you into the project directory.

Now, we need to install Tailwind CSS and configure it for our project. Run the following commands in your terminal:

# Install Tailwind CSS and its dependencies
npm install -D tailwindcss postcss autoprefixer

# Create a Tailwind CSS configuration file
npx tailwindcss init -p
Enter fullscreen mode Exit fullscreen mode

Open the tailiwnd.config.js file in your project directory and configure it to use Tailwind CSS and autoprefixer. Update the file as follows:

/** @type {import('tailwindcss').Config} */
export default {
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

Enter fullscreen mode Exit fullscreen mode

Add the @tailwind directives for each of Tailwind’s layers to your ./src/index.css file

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

Enter fullscreen mode Exit fullscreen mode

Run your build process with npm run dev.

npm run dev
Enter fullscreen mode Exit fullscreen mode

Start the project

Prepare the file
Make a new folder name component, inside the folder we will creta 2 file which is QuotePage.jsx and style.css. Import the style css in our QuotePage.jsx using this code

import './style.css';
Enter fullscreen mode Exit fullscreen mode

We also will use useState and useEffect, so just import it to QuotePage.jsx

import React, { useState, useEffect } from 'react';
Enter fullscreen mode Exit fullscreen mode

Start with header
Add this code to your QuotePage.jsx

<section className="relative mx-auto">
        <nav className="flex justify-between border-b border-white bg-transparent text-white w-screen">
          <div className="px-5 xl:px-12 py-6 justify-between flex w-full items-center">
            <a className="text-3xl font-bold font-heading" href="#">
              Quote.
            </a>

            <span className="block mt-[10px] float-right relative" id="author">
              author
            </span>

            <div className="flex space-x-5 gap-6 items-center">
              <button class="relative inline-block px-4 py-2 font-medium group">
                <span class="absolute inset-0 w-full h-full transition duration-200 ease-out transform translate-x-1 translate-y-1 bg-white group-hover:-translate-x-0 group-hover:-translate-y-0"></span>
                <span class="absolute inset-0 w-full h-full bg-black border-2 border-white group-hover:bg-white"></span>
                <span class="relative text-white group-hover:text-black">Next Quote</span>
              </button>
            </div>
          </div>
        </nav>
      </section>
Enter fullscreen mode Exit fullscreen mode
  • There are some function we will add to this header later, especially for the autor name and Next button to chnage the quote.

Next, we will create the main section, which displays the quote

Set the main section

<section className="max-w-full h-96 mx-auto flex relative items-center">
        <div className="container flex justify-center gap-6 flex-col items-center text-white">
          <svg fill="#fff" xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewBox="0 0 52 52" enable-background="new 0 0 52 52" xml:space="preserve">
            <g>
              <path
                d="M44.3,6.5c-9,0-15.9,7-15.9,16V44c0,0.8,0.7,1.5,1.5,1.5h17c0.8,0,1.5-0.7,1.5-1.5V27
        c0-0.8-0.7-1.5-1.5-1.5H34.4v-3c0-5,4.9-10,9.9-10h2.6c0.8,0,1.5-0.7,1.5-1.5V8c0-0.8-0.7-1.5-1.5-1.5H44.3z"
              />
              <path
                d="M19.5,6.5c-9,0-15.9,7-15.9,16V44c0,0.8,0.7,1.5,1.5,1.5h17c0.8,0,1.5-0.7,1.5-1.5V27
        c0-0.8-0.7-1.5-1.5-1.5H9.6v-3c0-5,4.9-10,9.9-10h2.6c0.8,0,1.5-0.7,1.5-1.5V8c0-0.8-0.7-1.5-1.5-1.5H19.5z"
              />
            </g>
            <path d="M30.5,8" />
          </svg>
          <blockquote className="text-5xl text-center min-h-[110px] px-20" id="quote">
            Quote
          </blockquote>

          <button

            className="inline-flex items-center justify-center gap-2 h-16 px-6 py-0 text-xl font-semibold text-center text-gray-200 no-underline align-middle transition-all duration-300 ease-in-out bg-transparent border-2 border-gray-600 border-solid rounded-full cursor-pointer select-none hover:text-white hover:border-white focus:shadow-xs focus:no-underline"
          >
            Button Text
            <svg width="30px" height="30px" viewBox="0 0 48 48" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink">
              <path
                fill="#1DA1F2"
                stroke="#1DA1F2"
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M38.74,16.55v1c0,10.07-7.64,21.61-21.62,21.61A21.14,21.14,0,0,1,5.5,35.71a12.22,12.22,0,0,0,1.81.11,15.25,15.25,0,0,0,9.44-3.24,7.56,7.56,0,0,1-7.1-5.29,6.9,6.9,0,0,0,1.44.15,7.53,7.53,0,0,0,2-.27A7.57,7.57,0,0,1,7,19.72v-.1a7.42,7.42,0,0,0,3.44.94A7.54,7.54,0,0,1,8.05,10.5a21.58,21.58,0,0,0,15.68,7.94,6.38,6.38,0,0,1-.21-1.74,7.55,7.55,0,0,1,13.17-5.31,15.59,15.59,0,0,0,4.83-1.85,7.65,7.65,0,0,1-3.39,4.27,15.87,15.87,0,0,0,4.37-1.26,15.56,15.56,0,0,1-3.76,4Z"
              />
            </svg>
          </button>
        </div>
      </section>
Enter fullscreen mode Exit fullscreen mode
  • With this, the display part should be almost complete, we just need to add a few functions to make this website work as we desire.
  • We will replace the text "quote" with the actual quote, and we'll also change the Twitter button to open the Twitter window accordingly

Add the function
First we will Initializing state with default values for quote and author

const [quoteData, setQuoteData] = useState({
  quote: 'Loading...',
  author: 'Loading...',
});
Enter fullscreen mode Exit fullscreen mode

Then we Create a function to fetch a random quote from an API

const getQuote = async (url) => {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    // Set the fetched quote and author in the state
    setQuoteData({
      quote: data.content,
      author: data.author,
    });
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};
Enter fullscreen mode Exit fullscreen mode
  • f the response is "ok," it reads the JSON data from the response using response.json(). This is where you would typically receive the data provided by the API.
  • Once the data is obtained, it sets the fetched quote and author in the state. This is typically done to display the data on a web page.
  • If there's an error in the process, such as a network issue or an invalid API response, it catches and logs the error to the console. This is important to handle potential issues when working with APIs.

Fetch a random quote when the component mounts (useEffect)

useEffect(() => {
  getQuote('https://api.quotable.io/random');
}, []);
Enter fullscreen mode Exit fullscreen mode
  • The useEffect hook is used to trigger the getQuote function when the component is first mounted, specifying the URL of the API from which to fetch data.
  • the array is empty ([]), which means the code inside the function will run only once after the component initially renders

Change the quote and the author

//Author
<span className="block mt-[10px] float-right relative" id="author">
   //Display the author base on the quote
   {quoteData.author}
</span>

//Quote
<blockquote className="text-5xl text-center min-h-[110px] px-20" id="quote">
  //Display the quote
  {quoteData.quote}
</blockquote>
Enter fullscreen mode Exit fullscreen mode

Provides a function handleNextQuoteClick to fetch the next random quote when a button is clicked

const handleNextQuoteClick = () => {
  // Call the getQuote function to fetch a new random quote
  getQuote('https://api.quotable.io/random');
};
Enter fullscreen mode Exit fullscreen mode

You can now incorporate that function into the 'Next quote' button; here's how the code for your 'Next' button will appear

<button class="relative inline-block px-4 py-2 font-medium group" onClick={handleNextQuoteClick}>
/** code **/
</button>
Enter fullscreen mode Exit fullscreen mode

Last, Create a function to tweet the current quote and author

const tweet = () => {
  // Extract the current quote and author from the state
  const { quote, author } = quoteData;
  // Compose a tweet text including the quote and author
  const tweetText = `${quote} ---- by ${author}`;
  // Open a new window to tweet the text on Twitter
  window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(tweetText)}`, 'Tweet Window', 'width=600, height=300');
};
Enter fullscreen mode Exit fullscreen mode

And add onClick={tweet} to your twitter button

The Result

Image description
Find the complete code in this repository

Thank you for reading!
As we conclude this adventure, I encourage you to continue your exploration of this dynamic landscape. The knowledge you've gained opens doors to limitless possibilities in web development, enabling you to build more than just quote generators, but a wide array of engaging and interactive web applications.

Top comments (0)