How do I fetch data from an API in JavaScript?
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.
async function getLessons() {
const response = await fetch('/api/lessons');
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json();
}#POSTing JSON
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
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.
const response = await fetch(url, { signal: AbortSignal.timeout(5000) });For manual cancellation, such as a search-as-you-type box superseding its own request:
const controller = new AbortController();
fetch(url, { signal: controller.signal });
controller.abort();#Handling everything
try {
const data = await getLessons();
} catch (error) {
if (error.name === 'AbortError') return; // we cancelled it
showMessage('Could not load lessons.');
}