Use Web APIs

Learning Objectives

Section 23.1: Introducing Web APIs

What is a Web API?

An API allows applications to request and exchange data over the internet.

Types of APIs

Public API: No authentication needed
  OpenWeatherMap, Random User Generator

Protected API: Requires API key
  YouTube, Twitter, GitHub

Private API: Requires authentication
  Facebook, Google (with tokens)

Common Public APIs

JSONPlaceholder - Fake JSON data
OpenWeatherMap - Weather data
PokéAPI - Pokemon data
GitHub API - Repository data
CoinGecko - Cryptocurrency data
OpenLibrary - Book data

Section 23.2: Consuming a Web API

Making API Requests

// OpenWeatherMap API
let apiKey = "your_api_key";
let city = "London";

fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`)
    .then(response => response.json())
    .then(data => {
        console.log("Temperature:", data.main.temp);
        console.log("Description:", data.weather[0].description);
    });

Using JSONPlaceholder

// Free fake API for testing
fetch("https://jsonplaceholder.typicode.com/posts/1")
    .then(response => response.json())
    .then(post => {
        console.log("Title:", post.title);
        console.log("Body:", post.body);
    });

Section 23.3: Calling an API with JavaScript

Complete Example: User Data

async function getUserData(userId) {
    try {
        let response = await fetch(
            `https://jsonplaceholder.typicode.com/users/${userId}`
        );

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        let user = await response.json();
        
        console.log("Name:", user.name);
        console.log("Email:", user.email);
        console.log("Phone:", user.phone);
        
        return user;
    } catch (error) {
        console.error("Error fetching user:", error);
    }
}

getUserData(1);

Handling Large Responses

// Pagination
async function getPages() {
    let allPosts = [];
    
    for (let page = 1; page <= 3; page++) {
        let response = await fetch(
            `https://api.example.com/posts?page=${page}`
        );
        let posts = await response.json();
        allPosts = allPosts.concat(posts);
    }
    
    return allPosts;
}

Section 23.4: Web APIs and Authentication

API Keys

// Store in environment variables (not hardcoded!)
let apiKey = process.env.API_KEY;

let url = `https://api.example.com/data?key=${apiKey}`;
fetch(url)
    .then(response => response.json())
    .then(data => console.log(data));

Bearer Tokens

let token = "your_bearer_token";

fetch("https://api.example.com/data", {
    headers: {
        "Authorization": `Bearer ${token}`
    }
})
.then(response => response.json())
.then(data => console.log(data));

Headers Authentication

fetch("https://api.example.com/data", {
    headers: {
        "X-API-Key": "your_api_key",
        "Content-Type": "application/json"
    }
})
.then(response => response.json())
.then(data => console.log(data));

Section 23.5: Key-Based Authentication

Using API Keys Safely

// Frontend (.env file - not committed)
VITE_API_KEY=your_public_key

// Access in code
let apiKey = import.meta.env.VITE_API_KEY;

// Backend (.env file)
SECRET_API_KEY=your_secret_key

// Access in Node.js
let apiKey = process.env.SECRET_API_KEY;

Server-Side Proxy

// Bad: Exposing API key in frontend
// fetch(url + "?key=" + apiKey)

// Good: Use backend as proxy
fetch("/api/proxy", {
    method: "POST",
    body: JSON.stringify({ endpoint: "/weather" })
})
.then(response => response.json())
.then(data => console.log(data));

Coding Challenges

Challenge 23.1: More Beer Please

Task: Fetch brewery data from an API

Challenge 23.2: Star Wars Universe

Task: Fetch Star Wars character data

Challenge 23.3: GitHub Profile

Task: Display GitHub user profile information

Key Takeaways

✅ APIs provide data from external services
✅ Use fetch() to call APIs
✅ Parse JSON responses
✅ Handle errors with try/catch
✅ Protect API keys with environment variables
✅ Use tokens for authentication

Quiz Questions


Next Module: Module 24 - Send Data to a Web Server