Start.dev
Back to blog

JavaScript fetch: get data from an API, step by step

Learn JavaScript fetch step by step: request data, read JSON, send a POST, and handle the errors fetch doesn't throw for you.

Ariel Weinberger
Ariel Weinberger ยท 6 min read

How do you get data from an API into your JavaScript?

Short answer: call fetch with a URL, wait for the response, then call .json() on it to get the data. Both steps return promises, so you await each one.

const response = await fetch("https://jsonplaceholder.typicode.com/users/1")
const user = await response.json()
 
console.log(user.name) // "Leanne Graham"

That is the whole happy path. The rest of this post covers what each line does, how to send data with a POST, and the one surprise that catches almost everyone: fetch doesn't throw an error when the server says 404. If await is new to you, read JavaScript async/await explained first.

What fetch actually does

fetch sends an HTTP request and gives you back a promise. The promise resolves to a Response object as soon as the server starts replying.

That Response is not your data yet. It is an envelope. It has the status code, the headers, and a body you still need to read. Why Fetch (opens in a new tab) explains where that data comes from in the first place.

So every fetch has two waits:

  1. Wait for the response. await fetch(url) gives you the envelope.
  2. Wait for the body. await response.json() opens it and parses the JSON into a normal JavaScript object or array.

Forgetting the second await is the most common first bug. You log the result and see Promise { <pending> } instead of your data.

Your first fetch, line by line

Here is a small function that loads one user and shows their name on the page:

async function showUser(id) {
  const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`)
  const user = await response.json()
 
  document.querySelector("#name").textContent = user.name
}
 
showUser(1)
  • async function lets you use await inside it.
  • The template literal builds the URL with the id in it.
  • response.json() turns the JSON text into an object, so user.name works.

You can follow the same steps in Your First Fetch (opens in a new tab).

The same thing with .then()

You will see older code that chains .then() instead of using await. It does exactly the same thing:

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

Each .then() waits for the step before it. Most modern code uses async/await because it reads top to bottom, but you should be able to read both.

The surprise: fetch doesn't fail on 404

This is the part that trips people up. The promise from fetch only rejects when the request couldn't be made at all, like when you are offline or the domain doesn't exist.

If the server answers with a 404 or a 500, that still counts as a response. fetch resolves normally. Your code carries on and tries to read a body that isn't what you expected.

The fix is to check response.ok yourself. It is true for status codes 200 to 299 and false for everything else:

async function getUser(id) {
  const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`)
 
  if (!response.ok) {
    throw new Error(`Request failed with status ${response.status}`)
  }
 
  return response.json()
}

Now a 404 becomes a real error you can catch. Handling Fetch Errors (opens in a new tab) walks through this in the course.

Catching errors with try/catch

Wrap the call in try/catch so a failed request shows a message instead of breaking the page:

async function showUser(id) {
  const nameEl = document.querySelector("#name")
 
  try {
    const user = await getUser(id)
    nameEl.textContent = user.name
  } catch (error) {
    nameEl.textContent = "Couldn't load this user."
    console.error(error)
  }
}

That one catch handles both kinds of failure: the network ones fetch throws on its own, and the bad status codes you throw from getUser.

Sending data with a POST

By default fetch sends a GET request. To send data, pass a second argument with the method, a header, and a body:

const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ title: "Hello", body: "My first post", userId: 1 }),
})
 
const created = await response.json()
console.log(created.id)

Three things matter here:

  • method says what kind of request it is: "POST", "PUT", "PATCH" or "DELETE".
  • The Content-Type header tells the server the body is JSON.
  • body must be a string, so you wrap your object in JSON.stringify.

If GET, POST and status codes are still fuzzy, How REST APIs work explains the conversation between your code and the server.

What the Response object gives you

Property or methodWhat it gives youWhen to use it
response.oktrue for 200 to 299Before reading the body, every time
response.statusThe status code, like 404Error messages and logging
response.json()A promise of the parsed JSONMost APIs
response.text()A promise of the raw textPlain text or HTML responses
response.headers.get(name)One header valueReading things like content type

You can only read the body once. If you call response.json() and then response.text(), the second call fails.

Common mistakes

  • Forgetting the second await. const data = response.json() gives you a promise, not data. Write await response.json().
  • Assuming a 404 throws. It doesn't. Check response.ok before you trust the body.
  • Sending an object as the body. body: { title: "Hello" } sends the text [object Object]. Use JSON.stringify.
  • Leaving out the Content-Type header. Many servers won't parse the JSON without it.
  • Using await outside an async function. In a plain script, that is a syntax error. Put the code inside an async function, or use .then().
  • Reading the body twice. Store the result of response.json() in a variable and reuse it.

Quick recap

  • await fetch(url) gives you a Response. await response.json() gives you the data.
  • fetch only rejects on network failures. Check response.ok for bad status codes.
  • Wrap calls in try/catch and show the user a message when something fails.
  • For a POST, pass method, a JSON Content-Type header, and a JSON.stringify body.
  • The body can be read once, so save it.

Frequently asked questions

What does fetch return in JavaScript?

It returns a promise that resolves to a Response object. To get the data itself, call a body method on that response, usually response.json(), which returns another promise.

Why does fetch not throw an error on 404?

Because the request worked. The server replied, just with an error status. fetch only rejects when it can't get a response at all. Check response.ok or response.status to handle 404s and 500s.

What is the difference between fetch and axios?

fetch is built into the browser and modern Node.js, so there is nothing to install. axios is a library that parses JSON for you and throws on bad status codes. Learn fetch first. Everything axios does is built on the same ideas.

How do I send JSON with fetch?

Pass an options object with method: "POST", a "Content-Type": "application/json" header, and body: JSON.stringify(yourObject).

Can I use fetch with async/await?

Yes. That is the most common way to use it today. Put your code in an async function and await both the fetch call and the response.json() call.

Practice

The matching exercises are in the course. Start with Your First Fetch (opens in a new tab), handle bad responses in Handling Fetch Errors (opens in a new tab), then check yourself with Fetching Data Knowledge Check (opens in a new tab). Each one runs in your browser, so there is nothing to install. When you want to show fetched data on a page, JavaScript addEventListener shows how to trigger a request from a button.

Keep going

Intermediate JavaScript (opens in a new tab) takes you from your first fetch to an app that loads, filters and displays real data. If functions and objects still feel shaky, start with JavaScript Basics (opens in a new tab).

Level up your coding skills

Jump into interactive courses and start building real-world projects.

Start learning

Related posts

A plain-English guide to JavaScript async/await: what it really does, how it relates to promises, and the mistakes that trip people up.
Ariel Weinberger
Ariel Weinberger ยท 5 min read
Learn how REST APIs work by following one request from client to server and back: URLs, methods, headers, status codes, JSON, and what REST actually means.
Ariel Weinberger
Ariel Weinberger ยท 7 min read
Learn addEventListener step by step: handle clicks, typing and form submits, use the event object, and avoid the mistakes that break listeners.
Ariel Weinberger
Ariel Weinberger ยท 6 min read