Fetch and REST APIs

18 min read javascript
Course contents (16 lessons)
  1. Modern syntax
  2. Destructuring, spread and rest
  3. ES modules: import and export
  4. Objects, this and errors
  5. Classes and prototypes
  6. Understanding this in JavaScript
  7. Error handling: try, catch and custom errors
  8. Asynchronous JavaScript
  9. The event loop: how JavaScript handles waiting
  10. From callbacks to promises to async/await
  11. Fetch and REST APIs
  12. Working in the browser
  13. Local storage and session storage
  14. Debugging with browser DevTools
  15. Performance basics: debounce and throttle
  16. Node.js essentials
  17. Node.js and npm basics
  18. Working with files in Node.js
  19. A tiny HTTP server with Node.js
  20. Testing and the final project
  21. Testing basics with the Node.js test runner
  22. Final project: a post explorer with modules and fetch

Talking to a server

Most web apps load data from a server. The browser's built-in way to do this is fetch. It also exists in Node.js 18 and later, so the code in this lesson works in both places. Fetch returns a promise, so we will use async/await.

What is a REST API

A REST API is a server that exposes data through URLs, and uses HTTP methods to say what you want to do:

MethodUsual meaningExample
GETReadGET /posts lists posts
POSTCreatePOST /posts adds a post
PUT / PATCHUpdatePATCH /posts/5 changes post 5
DELETEDeleteDELETE /posts/5 removes it

Data usually travels as JSON. A response also has a status code: 200 means OK, 201 means created, 404 means not found, 500 means a server error.

We will use JSONPlaceholder, a free fake API made for practice. It does not save your changes, but it replies as a real one would.

A basic GET request

async function loadPosts() {
  const response = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=3");
  const posts = await response.json();

  for (const post of posts) {
    console.log(`${post.id}: ${post.title}`);
  }
}

loadPosts();

There are two awaits, and that confuses beginners. The first one waits for the response headers to arrive. The second, response.json(), waits for the body to be downloaded and parsed. Both are promises.

The big gotcha: fetch does not reject on 404 or 500

If the server replies with an error status, fetch still resolves. It only rejects when the request itself fails, such as when there is no network. So you must check response.ok yourself:

async function getJson(url) {
  const response = await fetch(url);

  if (!response.ok) {
    throw new Error(`Request failed: ${response.status} ${response.statusText}`);
  }
  return response.json();
}

response.ok is true for any status from 200 to 299. This is the most common fetch bug I see. The code looks fine, response.json() fails with a confusing message because the body was an HTML error page, and nobody realises the real problem was a 404.

Sending data with POST

For POST, you pass an options object with the method, headers and body:

async function createPost(title, body) {
  const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ title, body, userId: 1 }),
  });

  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
}

createPost("Hello", "My first post").then(post => console.log(post.id));

You must turn the object into text with JSON.stringify and say so with the Content-Type header. Forgetting either is the second most common mistake. The server then receives text it does not understand.

Query strings

Build query strings with URLSearchParams so that special characters are encoded correctly:

const params = new URLSearchParams({ userId: 1, _limit: 5 });
const url = `https://jsonplaceholder.typicode.com/posts?${params}`;
console.log(url);

Do not join strings by hand when a user can type the value. A search term like rock & roll would break the URL.

Cancelling and timing out

A request can be cancelled with an AbortController. This is how you add a timeout, or cancel an old search when a new one begins:

async function getWithTimeout(url, ms = 5000) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), ms);

  try {
    const response = await fetch(url, { signal: controller.signal });
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return await response.json();
  } finally {
    clearTimeout(timer);
  }
}

When the timer fires, fetch rejects with an AbortError. The finally block clears the timer on every path.

A small reusable helper

Putting these pieces together, I keep a tiny wrapper in most projects:

const BASE_URL = "https://jsonplaceholder.typicode.com";

export async function api(path, { method = "GET", data, signal } = {}) {
  const options = { method, signal, headers: {} };

  if (data !== undefined) {
    options.headers["Content-Type"] = "application/json";
    options.body = JSON.stringify(data);
  }

  const response = await fetch(BASE_URL + path, options);
  if (!response.ok) {
    throw new Error(`${method} ${path} failed with ${response.status}`);
  }
  return response.status === 204 ? null : response.json();
}

// usage
// const posts = await api("/posts?_limit=5");
// const created = await api("/posts", { method: "POST", data: { title: "Hi" } });

All the HTTP details live in one place. The rest of the app just calls api(...). If you later need an auth token on every request, you change one function.

CORS in one paragraph

If you call an API on a different domain from your page, the browser checks the server's CORS headers. If the server does not allow your origin, the browser blocks the response, and you see a "CORS error" in the console. The request often reached the server, but the browser refuses to give the answer to your script. You cannot fix this from the front end. The server must send the right Access-Control-Allow-Origin header, or you call the API from your own backend instead. Node.js has no such restriction.

Showing loading and error states

Real users have slow connections. Your interface should say what is happening:

async function showPosts(listElement) {
  listElement.textContent = "Loading...";
  try {
    const posts = await api("/posts?_limit=5");
    listElement.textContent = "";
    for (const post of posts) {
      const li = document.createElement("li");
      li.textContent = post.title;
      listElement.append(li);
    }
  } catch (error) {
    listElement.textContent = "Could not load posts. Please try again.";
    console.error(error);
  }
}

Three states: loading, success and failure. Apps that skip the third one leave users staring at a blank screen.

Common mistakes

  • **Not checking response.ok.** A 404 or 500 is not an exception.
  • **Forgetting await response.json().** You get a promise, not data.
  • **Sending an object without JSON.stringify.** The body becomes [object Object].
  • **Missing the Content-Type header on POST.** The server may ignore the body.
  • Concatenating user input into URLs. Use URLSearchParams or encodeURIComponent.
  • Reading the body twice. response.json() can only be called once. Clone the response first if you need both text and JSON.

Try it yourself

  1. Fetch /users/1 from JSONPlaceholder and print the name and email.
  2. Request /posts/99999 and print what response.status and response.ok are.
  3. Write getPostsByUser(userId) using URLSearchParams.
  4. Use Promise.all to fetch posts 1, 2 and 3 in parallel and print their titles.
javascript
async function loadPosts() {
  const response = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=3");
  const posts = await response.json();

  for (const post of posts) {
    console.log(`${post.id}: ${post.title}`);
  }
}

loadPosts();

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account