JavaScript Fetch API

Load data from a server.

✍️ 3 exercises + code challenge in this lesson

The Fetch API requests data from servers. It returns a promise.

  1. const response = await fetch(url);
  2. Check response.ok (true for status 200–299).
  3. Read the body: await response.json() or response.text().

To send data, pass options: fetch(url, { method: "POST", headers: {...}, body: JSON.stringify(data) }).

The example loads sample data from jsonplaceholder.typicode.com, a free fake API for testing.

Key Takeaways: JavaScript Fetch API

Mastering JavaScript Fetch API helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Fetch API Code Example

JavaScript
<button onclick="loadUsers()">Load users</button>
<ul id="users"></ul>

<script>
  async function loadUsers() {
    const list = document.getElementById("users");
    list.innerHTML = "<li>Loading...</li>";
    try {
      const response = await fetch("https://jsonplaceholder.typicode.com/users?_limit=5");
      if (!response.ok) throw new Error("HTTP " + response.status);
      const users = await response.json();

      list.innerHTML = "";
      users.forEach(user => {
        const li = document.createElement("li");
        li.textContent = `${user.name} (${user.email})`;
        list.append(li);
      });
    } catch (e) {
      list.innerHTML = "<li>Could not load users: " + e.message + "</li>";
    }
  }
</script>
Free sign-in required · Google login available

JavaScript Fetch API Practice Exercises

Check what you learned in “JavaScript Fetch API”.

/ 3 solved
Fill in the blank

Read the response body as JSON.

const res = await fetch(url);
const data = await res.();
✓ Correct! Not quite. Try again.
Multiple choice

Which property tells you whether the HTTP status was successful (200–299)?

✓ Correct! Not quite. Try again.
Code challenge

Fetch https://jsonplaceholder.typicode.com/users/1 and log the user's name.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services