Codiqo

Learn JavaScript · lesson 43 of 60 · about 10 minutes

fetch() and JSON APIs

Read the guestbook from Sam's server: request data from a URL with fetch, check the status code, and handle failures.

What you'll learn

  • Call fetch and read JSON
  • Check response.ok and status codes
  • Handle network and server errors

The guestbook goes online

Messages left on Sam's page are now saved on Sam's server, at https://sam.example/api/guestbook, which answers with a JSON list of messages. Sam writes one helper, getJson(path), that fetches a path on the server, throws HTTP 500 (or whatever the status was) when the answer isn't ok, and otherwise returns the parsed JSON. The page uses it to show 3 messages, newest from Dee, 1 message for just one, The guestbook is empty, or Guestbook unavailable (HTTP 500) when the server has a problem.

Talking to APIs

An API is a web address that returns data, usually JSON. fetch(url) sends the request and returns a Promise of a Response:

1. await fetch(url) gets the response
2. Check res.ok: it's true for status codes 200 to 299
3. await res.json() reads and parses the body

These lessons run offline, so the examples use a pretend fetch that returns real Response objects. Your code is exactly what you'd write against a real API.

Fetching a user

// Pretend server: in a real app, delete this and use the built-in fetch
const fetch = async (url) =>
  url.endsWith("/users/1")
    ? new Response(JSON.stringify({ id: 1, name: "Ada", xp: 340 }), { status: 200 })
    : new Response("Not found", { status: 404 });

async function getUser(id) {
  const res = await fetch(`https://api.example.com/users/${id}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

async function main() {
  const user = await getUser(1);
  console.log(`${user.name} has ${user.xp} XP`);
  try {
    await getUser(99);
  } catch (err) {
    console.log("Could not load:", err.message);
  }
}
main();

Output

Ada has 340 XP
Could not load: HTTP 404

One helper for every request

Every request to the same server needs the same steps: fetch, check res.ok, read the JSON. Putting them in one helper that takes the path means each part of the page asks for its data in one line, and a failure always becomes the same kind of Error. Notice the helper doesn't catch anything: the code that knows what to show catches it.

One helper, two paths

const fetch = async (url) =>
  url.endsWith("/api/likes")
    ? new Response("[4, 1, 9]", { status: 200 })
    : new Response("Not found", { status: 404 });

async function getJson(path) {
  const res = await fetch(`https://sam.example${path}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

const likes = await getJson("/api/likes");
console.log(`Likes: ${likes.join(", ")}`);
try {
  await getJson("/api/secret");
} catch (err) {
  console.log(`Couldn't load it: ${err.message}`);
}

Output

Likes: 4, 1, 9
Couldn't load it: HTTP 404

Status codes

| Code | Meaning |
|---|---|
| 200 | OK |
| 201 | Created |
| 400 | Bad request (your data was wrong) |
| 401 | Not signed in |
| 404 | Not found |
| 500 | Server error |

Tip

fetch only rejects when the network fails. A 404 or 500 still resolves, so always check res.ok yourself.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.