Fetch API

Request data from APIs using the Fetch API.

Modern websites often need to communicate with external services to retrieve information such as weather updates, product details, user profiles, news articles, or payment information. This communication is usually done through APIs.

JavaScript provides the Fetch API, which allows websites to request data from servers and display it dynamically.

What Is an API?

API stands for Application Programming Interface.

An API acts as a bridge that allows two applications to communicate with each other, similar to a waiter carrying orders between a customer and a kitchen.

Why Are APIs Important?

  • Weather applications
  • Social media platforms
  • Online shopping websites
  • Banking applications
  • Maps and navigation systems

What Is Fetch?

The Fetch API is a built-in JavaScript feature used to make HTTP requests to servers. Fetch returns a Promise, making it useful for asynchronous operations.

Fetching Data with GET Requests

javascript
fetch("https://api.example.com/users")
    .then(response => response.json())
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.log(error);
    });

How it works:

  1. fetch() sends a request to the server.
  2. The server returns a response.
  3. response.json() converts the response into JavaScript data.
  4. The data is displayed or processed.
  5. Errors are handled using catch().

Using Async/Await with Fetch

javascript
async function getUsers() {
    try {
        const response = await fetch("https://api.example.com/users");
        const data = await response.json();

        console.log(data);
    } catch (error) {
        console.log(error);
    }
}

getUsers();

This approach makes asynchronous code look more like regular JavaScript.

Sending Data with POST Requests

javascript
fetch("https://api.example.com/users", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        name: "John",
        age: 25
    })
});

What Is JSON?

Most APIs exchange data using JSON, or JavaScript Object Notation.

json
{
    "name": "John",
    "age": 25
}

Real-World Example

In a weather application, JavaScript uses Fetch to send a request to a weather API, receives the current weather information, and displays it instantly.

Error Handling

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

Summary

APIs allow applications to communicate and exchange data, while Fetch provides a simple way for JavaScript to make requests to servers. Fetch, JSON, Promises, and Async/Await form the foundation of data-driven web applications.

Let's learn with DevBrainBox AI