Skip to content

The Fetch Function

fetch() is a built-in browser function that sends a request to a URL and returns a promise.

That is the whole thing. One line. One promise. Everything else is what you do with the result.


The simplest fetch call

fetch("/patients")

This sends a GET request to /patients on the same server as the page. The browser receives a response. But you have not told it what to do with that response yet.


The response is not the data

When the promise from fetch() fulfills, what you get is a Response object. Think of it as the envelope - it holds the data, but you have not opened it yet.

fetch("/patients")
  .then(response => {
    console.log(response)        // Response object - the envelope
    console.log(response.status) // 200
    console.log(response.ok)     // true if status is 200-299
  })

To get the actual data out of the envelope, you call .json() on the response:

fetch("/patients")
  .then(response => response.json())
  .then(data => {
    console.log(data)  // the actual array or object from Flask
  })

.json() also returns a promise - that is why you need the second .then(). The first one opens the envelope. The second one uses what was inside.


Two .then() calls - why

This is the part that confuses people. Let me show it step by step:

// Step 1: send the request, get a promise
let step1 = fetch("/patients")

// Step 2: when the response arrives, parse the JSON - also a promise
let step2 = step1.then(response => response.json())

// Step 3: when the parsing is done, use the data
step2.then(data => console.log(data))

Chained together, this is exactly:

fetch("/patients")
  .then(response => response.json())
  .then(data => console.log(data))

Fetching from a full URL

When you fetch from a different website (not your own Flask server), you use the full URL:

fetch("https://jsonplaceholder.typicode.com/users/1")
  .then(response => response.json())
  .then(user => console.log(user.name))

When fetching from your own Flask app, the path alone is enough:

fetch("/patients")
  .then(response => response.json())
  .then(patients => console.log(patients))

Challenge

Fetch a single user from https://jsonplaceholder.typicode.com/users/1 using arrow functions. Log only the name and email fields from the response.

Then try changing 1 to 5 - do you get a different person?


← Promises    Next: Then, Catch and Finally →