Welcome to Lesson 9! APIs (Application Programming Interfaces) are bridges between your web application and external services, allowing your site to request data from servers and receive responses in a structured way. The most common modern approach for interacting with APIs in JavaScript is the Fetch API.

The Fetch API is built into modern browsers and provides a simple interface to make HTTP requests. It returns a Promise that resolves to a Response object, which can then be converted into JSON or text.

Basic usage of fetch() looks like this:

fetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error("Error:", error));

Here’s a breakdown of what happens:

  • The fetch function requests data from the URL.
  • The response.json() method parses the returned JSON into a JavaScript object.
  • The then() method is called with the parsed data, allowing you to use it in your application.
  • catch() handles any errors that occur during the request.

You can also make POST requests, sending data to a server:

fetch("https://api.example.com/users", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({name: "Alice", age: 25})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));

Handling headers, authentication tokens, and query parameters are also possible using fetch options. For example, including a Bearer token for authorization:

fetch("https://api.example.com/data", {
  headers: {
    "Authorization": "Bearer YOUR_TOKEN_HERE"
  }
});

Fetching APIs allows your site to dynamically display data, such as weather updates, news, user information, or products from an e-commerce database. You can then manipulate the DOM to render this data for the user.

Example: dynamically generating a list of users:

fetch("https://api.example.com/users")
  .then(response => response.json())
  .then(users => {
    const list = document.createElement("ul");
    users.forEach(user => {
      const li = document.createElement("li");
      li.textContent = user.name;
      list.appendChild(li);
    });
    document.body.appendChild(list);
  });

By learning to work with APIs, your websites can now fetch live data, making them more dynamic and user-friendly. It’s a major step toward building real-world applications, such as dashboards, feeds, or interactive services.

Next, we will build on this concept with Async/Await, which makes working with asynchronous API calls easier and more readable.