mc0de
JavaScript · Lesson 15 of 17

JavaScript Fetch API

Connect your website to real information! Learn how JavaScript requests data from an API, waits for a response, converts JSON, and updates a webpage dynamically.

fetch() async / await JSON Responses Error Handling
● ● ●   fetch.js
async function loadData() {
  const response =
    await fetch("/api/data");

  const data =
    await response.json();

  console.log(data);
}
LIVE API REQUEST MONITOR
> Ready to request data. > Select Fetch Live Data.
01 / Getting Started

What Is an API?

Imagine building a website that displays the latest weather, a list of books, or information about users. You could type all that information into your HTML manually, but what happens when the information changes?

An API (Application Programming Interface) provides a defined way for software systems to communicate. Many web APIs allow JavaScript to request information over HTTP.

The Fetch API gives JavaScript a built-in way to make those requests.

Your first fetch request
fetch("https://jsonplaceholder.typicode.com/users/1")
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    console.log(data.name);
  });

This example requests a user record from JSONPlaceholder, a public service designed for practicing API requests.

Connection to Lesson 14: APIs frequently return JSON. You’ll use what you learned about objects and JSON to display API responses.
02 / Understanding Requests

How Does fetch() Work?

When JavaScript calls fetch(), the browser starts an HTTP request and returns a Promise. A Promise represents an operation whose result may become available later.

Request and response
const request = fetch(
  "https://jsonplaceholder.typicode.com/posts/1"
);

console.log(request); // A Promise

The browser doesn’t need to freeze while waiting for the server. Other page interactions can continue.

Once the response arrives, you can inspect its HTTP status and read the response body.

Inspecting a response
fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then(function(response) {
    console.log(response.status);
    console.log(response.ok);
  });

response.status is the HTTP status code. response.ok is true for successful HTTP statuses in the 200–299 range.

Important: A 404 or 500 HTTP response does not automatically reject the fetch Promise. Check response.ok yourself.
03 / Async and Await

Write Asynchronous Code More Clearly

Promises can be handled with .then(), but JavaScript also provides async and await for writing asynchronous code in a readable style.

Fetching JSON with async / await
async function loadUser() {
  const response = await fetch(
    "https://jsonplaceholder.typicode.com/users/1"
  );

  if (!response.ok) {
    throw new Error("Request failed");
  }

  const user = await response.json();

  console.log(user.name);
}

loadUser();

async marks a function as asynchronous. await pauses that function until the awaited Promise settles, without blocking the entire webpage.

Notice the two await expressions: one waits for the response, and the second waits for the response body to be read and parsed as JSON.

Think of it like ordering food
1. Place an order → fetch() 2. Wait for delivery → await 3. Open the package → response.json() 4. Use the contents → display data
04 / Displaying API Data

Turn Responses Into Webpage Content

After retrieving data, you can use DOM methods to show it on the page.

Displaying a user name
async function showUser() {
  const response = await fetch(
    "https://jsonplaceholder.typicode.com/users/1"
  );

  if (!response.ok) {
    throw new Error("Unable to load user");
  }

  const user = await response.json();

  document.getElementById("username").textContent =
    user.name;
}

For multiple records, use forEach() to create a card for each item.

Creating a list from API data
const container = document.getElementById("results");

users.forEach(function(user) {
  const card = document.createElement("div");
  card.textContent = user.name;
  container.appendChild(card);
});
Safe rendering: Prefer textContent when displaying text received from an API. Avoid placing untrusted data directly into innerHTML.
05 / Loading and Error States

Help Visitors Understand What’s Happening

Network requests can take time or fail. A good website tells visitors when information is loading, when it succeeds, and when something goes wrong.

Using try…catch…finally
async function loadData() {
  const status = document.getElementById("status");
  status.textContent = "Loading...";

  try {
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/users"
    );

    if (!response.ok) {
      throw new Error("HTTP " + response.status);
    }

    const users = await response.json();
    status.textContent = users.length + " users loaded.";
  } catch (error) {
    status.textContent = "Unable to load data.";
  } finally {
    console.log("Request finished.");
  }
}

try contains the request, catch handles failures, and finally runs when the operation finishes—even if an error occurred.

Some requests fail because of connectivity, server problems, browser restrictions, or cross-origin access rules (CORS).

WordPress note: Public API access depends on the endpoint and browser security policies. The lesson’s sample-data option lets students practice even if a live request is blocked.
06 / Working With API Results

Filter, Search, and Refresh Information

Once API data is loaded into an array, you can use the same JavaScript techniques you’ve already learned.

Filtering API results
const filtered = users.filter(function(user) {
  return user.name.toLowerCase().includes("a");
});

filtered.forEach(function(user) {
  console.log(user.name);
});

You can also add a Refresh button that calls your loading function again.

Refreshing the dashboard
const refreshButton =
  document.getElementById("refresh");

refreshButton.addEventListener("click", loadData);

These small additions make a static webpage feel like an application.

Remember: Don’t include private API keys in public JavaScript or WordPress HTML blocks. Sensitive credentials belong on a secure server.
07 / Fetch API in Action

Try the Live API Explorer

Let’s retrieve public user records from JSONPlaceholder. You can load live records or use built-in sample data if the request is unavailable.

Live API Explorer

Request a list of users and see how JavaScript turns JSON into readable content.

Ready to load users.

Try the live request first. Then compare it with the sample-data option. Both produce the same kind of JavaScript array, even though the data comes from different sources.

🚀 mC0de Challenge

Build an API Data Dashboard

Create a dashboard that retrieves user information from an API and displays it as attractive cards.

Your Mission

  1. Create a button labeled Fetch Users.
  2. Use fetch() to request user records from JSONPlaceholder.
  3. Use async and await to handle the request.
  4. Check response.ok before reading the JSON.
  5. Display each user’s name, email address, and company.
  6. Show loading, success, and error messages.
  7. Add Refresh and Sample Data buttons.
Extra challenge: Add a search field that filters the loaded users by name or company, and show the number of matching results.
💻 Interactive JavaScript Sandbox

Build Your API Data Dashboard!

The starter project includes a working API request, error handling, user cards, and sample data. Load Solution adds search, result counts, and a polished dashboard layout.

Live Result

Live requests require internet access and permission from the API’s cross-origin policy. The sandbox uses an isolated iframe; its sample data works without external requests.

Lesson 15 Recap

What You’ve Learned

You’re Connecting JavaScript to Real Data!

You’ve learned how webpages communicate with APIs and how to turn responses into useful interfaces.

  • Understand what APIs do and how HTTP requests work.
  • Use fetch() to request information.
  • Write asynchronous code with async and await.
  • Read JSON responses using response.json().
  • Display API results using DOM methods.
  • Handle loading, success, and error states.
  • Build an interactive API Data Dashboard.

Next up: Local Storage — learn how to remember information even after a visitor refreshes or closes a webpage!

Your Learning Journey

0 / 17 Completed

Lesson 15 of 17 — only Local Storage and the Final Project remain!

🎉

You've Mastered Fetch API Basics!

You can now request data from APIs, work with asynchronous JavaScript, handle loading and errors, and display real information on a webpage. You've built your own API Data Dashboard!