Index

Working with APIs and Fetch

JavaScript for Beginners

17.1 What is an API?

An API, or Application Programming Interface, is like a bridge that allows two different software systems to talk to each other. It defines a set of rules and protocols that enable programs to request and exchange information in a structured way.

Imagine a Restaurant Analogy

Think of an API as a waiter in a restaurant. You (the customer) don’t go into the kitchen to prepare your food; instead, you place an order with the waiter. The waiter takes your request to the kitchen, which prepares the dish, and then the waiter brings it back to you. In this analogy:

You don’t need to know how the kitchen prepares the food; you just trust the waiter to bring the correct dish.

What Do APIs Do?

APIs allow your app to interact with other software or services, often over the internet. They let you:

APIs handle the details of how the data is formatted and transferred, so developers can focus on building the app’s features.

Why Are APIs Essential in Modern Web Development?

Most websites and applications rely on data and services provided by others. For example:

Without APIs, integrating these external services would be difficult and time-consuming.

Summary

APIs are the invisible helpers that connect different software systems. They simplify communication, allow data sharing, and enable developers to create powerful apps that leverage existing services — making the web more connected and interactive than ever before.

Index

17.2 Using fetch to Make HTTP Requests

The fetch API is a modern, built-in way to make HTTP requests in JavaScript. It allows your web app to communicate with servers and retrieve or send data over the internet. Let's explore how to use fetch to perform a basic GET request, handle responses, and manage errors.

Basic GET Request with fetch

A GET request is used to retrieve data from a server. Here’s how you make a simple GET request using fetch:

fetch('https://api.agify.io?name=michael')
  .then(response => response.json())  // Parse JSON from the response
  .then(data => {
    console.log(data);  // Log the fetched data
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

How This Works

  1. Calling fetch(): The fetch function takes the URL of the resource you want to access and returns a Promise.
  2. Handling the Response: When the request completes, the Promise resolves to a Response object.
  3. Parsing JSON: Since most APIs send data as JSON, you call .json() on the Response object, which also returns a Promise that resolves to the JavaScript object.
  4. Using the Data: Inside the next .then(), you work with the parsed data.
  5. Handling Errors: The .catch() block handles any network errors or issues with fetching the data.

A Complete Runnable Example

Try this example in your browser’s console or a JavaScript environment that supports fetch:

fetch('https://api.agify.io?name=sarah')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    console.log(`Predicted age for Sarah: ${data.age}`);
  })
  .catch(error => {
    console.error('Failed to fetch:', error);
  });

Important Notes

Summary

Next, we'll look at how to read and work with JSON responses in more detail.

Index

17.3 Reading JSON Responses

When working with APIs, the most common data format you’ll encounter is JSON (JavaScript Object Notation). JSON is a lightweight, human-readable format for exchanging data between servers and clients.

What is JSON?

JSON looks like JavaScript objects but is actually a string format that represents data as key-value pairs, arrays, and nested structures. For example:

{
  "name": "Alice",
  "age": 28,
  "hobbies": ["reading", "traveling", "coding"]
}

This JSON represents a person’s profile with a name, age, and a list of hobbies.

Parsing JSON with .json()

When you use the fetch API, the response body is received as a stream of bytes. To convert it into a usable JavaScript object, you call the .json() method on the response. This method parses the JSON string and returns a Promise that resolves with the resulting object.

Example: Fetching and Parsing JSON

fetch('https://api.agify.io?name=emma')
  .then(response => response.json())   // Parse JSON data
  .then(data => {
    console.log(data);  // Output the whole object
    console.log(`Name: ${data.name}`); // Access individual properties
    console.log(`Predicted Age: ${data.age}`);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Sample output:

{ name: "emma", age: 29, count: 12345 }
Name: emma
Predicted Age: 29

Working with JSON Arrays

Sometimes, APIs return arrays of objects. Here’s an example of working with such data:

fetch('https://jsonplaceholder.typicode.com/users')
  .then(response => response.json())
  .then(users => {
    users.forEach(user => {
      console.log(`User: ${user.name}, Email: ${user.email}`);
    });
  })
  .catch(error => {
    console.error('Failed to load users:', error);
  });

This fetches an array of users and logs each user’s name and email.

Summary

In the next section, we’ll put all this together by building a simple weather app that fetches real data from a public API!

Index

17.4 Building a Simple Weather App

In this section, we'll build a simple weather app that fetches live weather data from a public API, parses the JSON response, and dynamically updates the webpage with the information. We’ll also add error handling to ensure the app works smoothly.

Step 1: Get API Access

We’ll use the OpenWeatherMap API, which provides free weather data. You need to sign up for a free API key.

For this example, let's assume you have an API key stored in a variable:

const apiKey = 'YOUR_API_KEY_HERE';

Step 2: HTML Setup

Create a simple HTML structure with an input box to enter a city name, a button to fetch weather, and an area to display results:

<input type="text" id="cityInput" placeholder="Enter city name" />
<button id="getWeatherBtn">Get Weather</button>

<div id="weatherResult"></div>

Step 3: Fetch Weather Data

Write a function to fetch weather data from the API using the city name:

const apiKey = 'YOUR_API_KEY_HERE';  // Replace with your actual API key

async function fetchWeather(city) {
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(city)}&appid=${apiKey}&units=metric`;

  try {
    const response = await fetch(url);

    if (!response.ok) {
      throw new Error('City not found');
    }

    const data = await response.json();
    return data;
  } catch (error) {
    throw error;  // Propagate error to caller
  }
}

Step 4: Update the DOM Dynamically

Next, create a function to display weather information or errors on the page:

function displayWeather(data) {
  const weatherDiv = document.getElementById('weatherResult');
  weatherDiv.innerHTML = `
    <h2>Weather in ${data.name}</h2>
    <p>Temperature: ${data.main.temp} °C</p>
    <p>Conditions: ${data.weather[0].description}</p>
    <p>Humidity: ${data.main.humidity}%</p>
  `;
}

function displayError(message) {
  const weatherDiv = document.getElementById('weatherResult');
  weatherDiv.innerHTML = `<p style="color: red;">Error: ${message}</p>`;
}

Step 5: Connect UI and Fetch Logic

Add an event listener to the button to get the city input, fetch the weather, and update the page:

document.getElementById('getWeatherBtn').addEventListener('click', async () => {
  const city = document.getElementById('cityInput').value.trim();

  if (!city) {
    displayError('Please enter a city name');
    return;
  }

  displayError('');  // Clear previous errors
  document.getElementById('weatherResult').textContent = 'Loading...';

  try {
    const weatherData = await fetchWeather(city);
    displayWeather(weatherData);
  } catch (error) {
    displayError(error.message);
  }
});

Complete Flow

  1. User enters a city name and clicks the button.
  2. The app fetches live weather data using the OpenWeatherMap API.
  3. The JSON response is parsed.
  4. Weather details are shown dynamically on the page.
  5. Errors like invalid city names or network problems are handled gracefully.

Summary

You’ve now created a working weather app that demonstrates:

This simple project is a great example of how JavaScript interacts with APIs to build real-world applications!

Index