Skip to content

Fetch

fetch() sends a request to a URL, brings back data, and lets you do something with it — all without reloading the page.

You already know the pattern from the previous page: ask for something, and when it arrives, run the "do this after" code. fetch() is exactly that, applied to getting data from the internet.


A URL to practise with

Before you build your own API, you need a URL that returns data. There are public APIs on the internet you can use freely for practice. A good one is:

https://jsonplaceholder.typicode.com/users

Visit that URL in your browser. You will see a list of users in JSON — names, emails, addresses. That is what fetch() will bring back to your JavaScript code.


The basic fetch

fetch("https://jsonplaceholder.typicode.com/users")
  .then(function(response) {
    return response.json()
  })
  .then(function(data) {
    console.log(data)
  })

Walk through it:

  1. fetch(url) — sends a request to that URL
  2. First .then() — the raw response arrives; response.json() converts it into a JavaScript array of objects you can work with. The return passes it to the next step.
  3. Second .then()data is now your array of users

Open the browser console and try this in a <script> tag. You should see the array of user objects printed.


Putting the data on the page

Reading to the console is for testing. The real goal is showing the data to the user.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Users</title>
  </head>
  <body>

    <h1>Users</h1>
    <div id="output"></div>

    <script>
      // find the container where we will put the results
      let outputBox = document.getElementById("output")

      fetch("https://jsonplaceholder.typicode.com/users")
        .then(function(response) {
          return response.json()
        })
        .then(function(users) {
          let html = ""

          for (let user of users) {
            html = html + "<p>" + user.name + " — " + user.email + "</p>"
          }

          outputBox.innerHTML = html
        })
    </script>

  </body>
</html>

Open this in your browser. The page loads, the fetch goes out to the internet, and when the data arrives the names and emails appear — no Flask, no Python, no page reload.


What is JSON?

JSON stands for JavaScript Object Notation. It is a way of writing structured data as text — the same idea as Python dictionaries and lists, just written slightly differently. { "name": "Alice", "age": 24 } is JSON. When fetch() gets a response, .json() converts that text into actual JavaScript objects you can loop through and read with dot notation.


Challenge

Change the fetch URL to https://jsonplaceholder.typicode.com/posts. Each post has a title and a body. Display just the titles on the page inside <h3> tags. How many posts come back?


← Do This After    Next: JavaScript 102 Exercises →