JavaScript Lesson 18: Fetch API

⚡ JavaScript CourseLesson 18 of 20 · 90% complete

The Fetch API lets JavaScript get data from the internet. Combined with async/await, it’s the standard way to call APIs in modern JavaScript.

Basic Fetch

// Fetch is built into modern browsers — no install needed!
async function getJoke() {
  const response = await fetch("https://official-joke-api.appspot.com/random_joke");
  const joke = await response.json();
  
  console.log(joke.setup);
  console.log(joke.punchline);
}

getJoke();

Checking for Errors

async function fetchData(url) {
  try {
    const response = await fetch(url);
    
    // fetch does NOT throw on 404 — you must check!
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    
    const data = await response.json();
    return data;
    
  } catch (error) {
    if (error.name === "TypeError") {
      console.error("Network error — check your connection");
    } else {
      console.error("Error:", error.message);
    }
    return null;
  }
}

POST Request — Send Data

async function createPost(title, body) {
  const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      title: title,
      body: body,
      userId: 1
    })
  });
  
  const newPost = await response.json();
  console.log("Created:", newPost);
  return newPost;
}

createPost("My Post", "Hello World");

Display Data in the DOM

async function loadUsers() {
  const users = await fetch("https://jsonplaceholder.typicode.com/users")
    .then(r => r.json());
  
  const list = document.querySelector("#user-list");
  list.innerHTML = ""; // clear existing
  
  users.forEach(user => {
    const li = document.createElement("li");
    li.textContent = `${user.name} — ${user.email}`;
    list.appendChild(li);
  });
}

loadUsers();

🏋️ Practice Task

Build a Pokemon lookup tool. Use the free API: https://pokeapi.co/api/v2/pokemon/pikachu — fetch a Pokemon by name, extract its name, height, weight, and abilities array, and display them. Then let the user type any Pokemon name.

💡 Hint: await fetch(“https://pokeapi.co/api/v2/pokemon/” + name).then(r=>r.json()). Access data.name, data.height, etc.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *