APIs

Learn how React applications request and display server data with Fetch and Axios.

Working with APIs (Fetch & Axios)

Modern web applications rarely work with static data. Instead, they receive information from servers through APIs, or Application Programming Interfaces. For example, a weather app loads weather data, an online shopping website displays products, and a social media platform shows posts from a server.

In React, you can communicate with APIs using two popular methods:

  • Fetch API
  • Axios

Both methods allow your application to request data from a server and display it on the screen.

What is an API?

An API, or Application Programming Interface, is a bridge that allows two applications to communicate with each other.

Instead of storing all the data inside your React application, you request it from a server using an API.

Real-World Example

Imagine ordering food from a restaurant.

  • You, the React application, place an order.
  • The waiter, the API, takes your request to the kitchen.
  • The kitchen, the server, prepares the food.
  • The waiter returns the food to your table.

Similarly, React sends a request, the API communicates with the server, the server sends back data, and React displays the data to the user.

Why Do We Use APIs?

APIs allow applications to:

  • Display products
  • Show weather information
  • Load blog posts
  • Display user profiles
  • Process payments
  • Authenticate users
  • Save and update information

Without APIs, modern web applications would not be able to display live or dynamic data.

What is the Fetch API?

The Fetch API is a built-in JavaScript feature used to request data from servers. Since it is built into modern browsers, no additional installation is required.

Fetch Example

javascript
import { useEffect } from "react";

function App() {
  useEffect(() => {
    fetch("https://example.com/api/products")
      .then(response => response.json())
      .then(data => console.log(data));
  }, []);

  return <h1>Loading Products...</h1>;
}

Explanation

  • fetch() sends a request to the server.
  • The server returns a response.
  • response.json() converts the response into JavaScript data.
  • The data is then available for use in your application.

Using Async/Await with Fetch

Modern JavaScript often uses async and await to make asynchronous code easier to read.

javascript
useEffect(() => {
  async function loadData() {
    const response = await fetch(
      "https://example.com/api/products"
    );

    const data = await response.json();

    console.log(data);
  }

  loadData();
}, []);

This version produces the same result but is often easier to understand.

What is Axios?

Axios is a popular JavaScript library used to make HTTP requests. Unlike Fetch, Axios must be installed before you can use it.

Install Axios

bash
npm install axios

Axios Example

javascript
import axios from "axios";
import { useEffect } from "react";

function App() {
  useEffect(() => {
    axios
      .get("https://example.com/api/products")
      .then(response => {
        console.log(response.data);
      });
  }, []);

  return <h1>Loading Products...</h1>;
}

Explanation

  • axios.get() sends a request.
  • The returned data is available through response.data.
  • Axios automatically converts JSON responses into JavaScript objects.

Fetch vs Axios

Both Fetch and Axios are widely used, but they have some differences.

text
Feature                   Fetch      Axios
Built into browser        Yes        No
Installation required     No         Yes
Automatic JSON conversion No         Yes
Simpler syntax            Moderate   Yes
Error handling            Basic      Better

Both options are excellent choices, and many developers learn both.

Displaying API Data

Once data is received from an API, React usually stores it in state and displays it using the map() method.

javascript
{
  products.map(product => (
    <div key={product.id}>
      <h2>{product.name}</h2>
      <p>{product.price}</p>
    </div>
  ));
}

This allows React to display multiple products dynamically instead of writing each one manually.

Handling Errors

Sometimes an API request may fail because of:

  • No internet connection
  • Server problems
  • Invalid URL
  • Permission issues

Basic Fetch error handling:

javascript
fetch("https://example.com/api")
  .catch(error => {
    console.log("Error:", error);
  });

Displaying friendly error messages helps users understand what went wrong instead of seeing a blank page.

Real-World Example

Imagine you are building an online shopping website.

When the Products page opens:

  • React sends an API request.
  • The server returns product information.
  • React stores the data in state.
  • The products are displayed automatically.

When a customer refreshes the page, the latest product information is loaded again. This ensures users always see up-to-date data.

Best Practices

When working with APIs:

  • Use useEffect to load data after a component renders.
  • Store API data using useState.
  • Handle loading and error states.
  • Avoid making unnecessary API requests.
  • Keep API logic organized and readable.
  • Validate the received data before displaying it.

These practices improve both performance and user experience.

Summary

APIs are essential for building modern React applications because they allow your application to communicate with servers and display dynamic data. React can use either the built-in Fetch API or the Axios library to send requests and receive information.

While Fetch is available in all modern browsers, Axios provides additional features and simpler syntax. By combining APIs with Hooks such as useEffect and useState, you can build applications that display live data, update automatically, and provide a better user experience.

Key Takeaways

  • An API allows applications to communicate and exchange data.
  • React commonly uses the Fetch API or Axios to request data from servers.
  • Fetch is built into modern browsers and requires no installation.
  • Axios is a third-party library with additional features and simpler syntax.
  • useEffect is commonly used to load API data after a component renders.
  • API responses are often stored in state and displayed using map().
  • Always handle loading states and errors when working with APIs.
  • Understanding APIs is essential for building dynamic and data-driven React applications.
Let's learn with DevBrainBox AI