Course contentsShow
← Web Development
Lesson 827 of 2,98215. Browser NetworkingFree lesson

Fetch API Fundamentals and Basic GET Requests

Learn the core fetch() function syntax, how to make simple GET requests, and understand the Promise-based API.

Fetch API Fundamentals and Basic GET Requests

You'll learn how to use the modern fetch() function to retrieve data from servers using GET requests.

The Fetch API is JavaScript's built-in way to make network requests from the browser. Think of it like sending a messenger to retrieve information from a distant location—you give an address (URL), and the messenger brings back what they find.

The Core fetch() Syntax

At its simplest, fetch() takes a URL and returns a Promise that resolves when the server responds:

fetch('https://api.example.com/data')

This initiates a GET request (the default HTTP method) to retrieve data from the specified URL.

Working with the Promise

Since fetch() returns a Promise, you handle the response using .then():

fetch('https://api.example.com/users')
  .then(response => response.json())
  .then(data => {
    console.log(data); // Your retrieved data
  })
  .catch(error => {
    console.error('Request failed:', error);
  });

Notice the two-step process: first you get a response object, then you extract the actual data (often using .json() which also returns a Promise).

Why Promises?

Network requests take time—the browser doesn't freeze while waiting. Promises let your code continue running and handle the result whenever it arrives, just like the storage event or addEventListener() patterns you've already learned.

Basic GET Request Pattern

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(post => console.log(post.title));

This retrieves a single post and logs its title once the data arrives.

Key Takeaway: The fetch() function makes network requests using a Promise-based API—call fetch(url) to GET data, then chain .then() to handle the response when it arrives.