#javascript #tutorial #intermediate

Day 9: Fetch API & Working with Data

Day 9: The Fetch API

Modern websites arenโ€™t static. They talk to servers to load data (users, posts, weather). We use the global fetch() function.

1. Basic GET Request

By default, fetch makes a GET request.

async function getUsers() {
    // 1. Fire request
    const response = await fetch('https://jsonplaceholder.typicode.com/users');
    
    // 2. Parse JSON body
    // (This is also async because the body might be large)
    const users = await response.json();
    
    console.log(users);
}

getUsers();

2. Handling Errors

Network requests can fail (404, 500, Offline). ALWAYS use try/catch.

async function getPost() {
    try {
        const res = await fetch('https://api.example.com/post/1');
        
        if (!res.ok) { // Check if status code is 200-299
            throw new Error(`HTTP Error! Status: ${res.status}`);
        }

        const data = await res.json();
        console.log(data);
    } catch (err) {
        console.error("Failed to fetch:", err.message);
    }
}

3. Displaying Data on Page

Combine Fetch with DOM Manipulation (Day 5).

async function showUser() {
    const res = await fetch('https://randomuser.me/api/');
    const data = await res.json();
    const user = data.results[0];

    // Create HTML
    const div = document.createElement('div');
    div.innerHTML = `
        <h3>${user.name.first} ${user.name.last}</h3>
        <img src="${user.picture.medium}" alt="User">
    `;

    document.body.appendChild(div);
}

Homework for Day 9:

  1. Use the free PokeAPI (https://pokeapi.co/api/v2/pokemon/pikachu).
  2. Fetch details for Pikachu.
  3. Log its name and its image URL (sprites.front_default).

Day 10: Final Project. We put everything together!