Back to Blog
Lesson 37 of the JavaScript: From Zero to Interactive Web Pages course
JavaScriptAugust 24, 20264 min read

Mastering the Fetch API: GET Requests and JSON Data in JavaScript

Learn to use the Fetch API to perform GET requests, handle HTTP responses, and parse JSON data in your web applications with this practical guide.

JavaScriptFetch APIAJAXHTTPPromisesWeb Development
A hand holding a JSON text sticker, symbolic for software development.

Previously in this course, we covered Introduction to Promises, where you learned how to manage asynchronous operations using .then() and .catch(). In this lesson, we apply that knowledge to the real world by using the Fetch API to communicate with external servers.

Understanding the Fetch API

The Fetch API is the modern, built-in browser interface for making network requests. It replaces older, more cumbersome techniques like XMLHttpRequest (often associated with the term AJAX). With fetch, you can request resources—like JSON data, images, or HTML—from a server without reloading the page.

When you make a request, the browser initiates an HTTP (Hypertext Transfer Protocol) transaction. In this lesson, we focus on the GET method, which is used to "get" or retrieve data from a specific URL.

Performing a GET Request

The basic syntax for a fetch request is straightforward. You call fetch() with the URL of the resource you want to access. This returns a Promise that resolves to a Response object.

JAVASCRIPT
fetch(CE9178">'https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.error(CE9178">'Fetch error:', error);
  });

Handling the Response Object

The Response object returned by fetch does not contain your data immediately. Instead, it contains metadata about the request, such as the status code (e.g., 200 for "OK" or 404 for "Not Found") and headers.

To access the actual content, you must call a method on the response object that tells the browser how to read the stream. For JSON data, we use .json().

Converting Data to JSON

Since the body of the response is a stream, the .json() method also returns a Promise. This means we chain another .then() to receive the final, parsed JavaScript object.

JAVASCRIPT
fetch(CE9178">'https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    // Check if the request was successful
    if (!response.ok) {
      throw new Error(CE9178">'Network response was not ok');
    }
    // Parse the response body as JSON
    return response.json();
  })
  .then(data => {
    // Now you have the actual data object
    console.log(CE9178">'Post Title:', data.title);
  })
  .catch(error => {
    console.error(CE9178">'There was a problem:', error);
  });

Hands-on Exercise

To practice, open your browser console (F12) on any page and try to fetch a list of users from a public API.

  1. Use fetch('https://jsonplaceholder.typicode.com/users').
  2. Chain a .then() to convert the response to JSON.
  3. Chain a second .then() to log the names of the first three users in the array using a loop.
  4. Add a .catch() to log any potential errors.

Common Pitfalls

  • Ignoring response.ok: A fetch promise only rejects if there is a network failure (like the user being offline). It will not reject on a 404 or 500 error. You must manually check response.ok or response.status to ensure the request actually succeeded.
  • Forgetting the return: If you omit return response.json(), the next .then() will receive undefined because the promise wasn't passed down the chain.
  • CORS Errors: Browsers enforce Cross-Origin Resource Sharing (CORS) policies. If you try to fetch data from a server that doesn't explicitly allow requests from your domain, the browser will block the request for security reasons.

FAQ

What is the difference between AJAX and Fetch? AJAX is a conceptual approach to updating parts of a page without a full reload. The Fetch API is the modern, native browser tool that implements this concept more cleanly than the older XMLHttpRequest object.

Can I use Fetch for POST requests? Yes. While this lesson focuses on GET, you can pass a second argument to fetch() to specify the method, headers, and body for POST or other HTTP verbs.

Why do I need to call .json()? Because the server sends data as a raw stream of text. The .json() method is a helper that reads that stream and automatically parses it into a usable JavaScript object.

Recap

We have moved from simple local logic to networked applications. By using the fetch API, checking response.ok, and parsing data with .json(), you can now pull live content into your web projects. Always remember that network requests are asynchronous—your code execution continues while the browser waits for the server to reply.

Up next: We will dive deeper into Working with JSON Data to learn how to traverse complex API responses and handle nested data structures.

Similar Posts