How do I fetch data from an API in JavaScript?

HTML, CSS & JS 2 min read
Short answer

Use await fetch(url), check response.ok, then await response.json(). fetch does not reject on HTTP error statuses, so the check is not optional.

javascript
async function getLessons() {
  const response = await fetch('/api/lessons');

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

  return response.json();
}

#POSTing JSON

javascript
const response = await fetch('/api/lessons', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ title: 'New lesson' }),
});

The Content-Type header and JSON.stringify are both required. Passing the object directly sends [object Object].

#Sending a form

javascript
const response = await fetch('/api/upload', {
  method: 'POST',
  body: new FormData(form),      // do NOT set Content-Type here
});

With FormData, the browser sets the content type including the multipart boundary. Setting it yourself breaks the request.

#Timeouts and cancellation

fetch has no timeout by default — it will wait indefinitely.

javascript
const response = await fetch(url, { signal: AbortSignal.timeout(5000) });

For manual cancellation, such as a search-as-you-type box superseding its own request:

javascript
const controller = new AbortController();
fetch(url, { signal: controller.signal });
controller.abort();

#Handling everything

javascript
try {
  const data = await getLessons();
} catch (error) {
  if (error.name === 'AbortError') return;      // we cancelled it
  showMessage('Could not load lessons.');
}