How to Use JavaScript Fetch API to Call a REST API (GET, POST, Error Handling)

fetch() is already in every modern browser — no library needed. This tutorial shows how to call a REST API with GET and POST, handle the 404 trap most beginners miss, add a timeout, and run requests in parallel.

RH Raja HunainAuthor 24 Nov 2026 7 min read 8 views
Table of Contents
Share

Almost every web app talks to a server: loading a user profile, saving a form, or checking the weather. In JavaScript, the built-in tool for that job is the Fetch API. It is already in every modern browser and in Node.js 18 and newer, so you do not need to install Axios or jQuery to make your first API call.

This tutorial uses JSONPlaceholder, a free fake REST API made for practice, so you can run every example without setting up a server. By the end you will know how to send GET and POST requests, handle errors the right way, add a timeout, and run several requests at the same time.

Step 1: Your first GET request

The fetch() function takes a URL and returns a Promise that resolves with a Response object. The body is not in that object yet — you read it with a second step, usually .json():

fetch('https://jsonplaceholder.typicode.com/users/1')
  .then(response => response.json())
  .then(user => console.log(user.name))
  .catch(error => console.error('Request failed:', error));

The same request reads much better with async/await, because the code runs top to bottom like normal code. Both await keywords matter: the first waits for the response headers, the second waits for the body to download and be parsed:

async function getUser(id) {
  const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
  const user = await response.json();
  return user;
}

const user = await getUser(1);
console.log(user.name); // Leanne Graham

Step 2: The error trap almost every beginner misses

Here is the part that causes the most confusion: fetch() does not reject its Promise for HTTP errors like 404 or 500. It only rejects when the request could not be made at all — no internet, a DNS failure, or a blocked request. A 404 response still counts as a successful fetch, so this code prints a broken result instead of an error:

const response = await fetch('https://jsonplaceholder.typicode.com/users/9999');
const data = await response.json();
console.log(data); // {} — an empty object, not an error

Always check response.ok, which is true only for status codes from 200 to 299, and throw your own error when it is false:

async function getUser(id) {
  const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);

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

  return response.json();
}

try {
  const user = await getUser(9999);
  console.log(user.name);
} catch (error) {
  console.error('Could not load user:', error.message);
  // Could not load user: HTTP 404 Not Found
}

That one check turns silent failures into errors you can actually see and handle.

Step 3: Send data with a POST request

To create data, set the method to POST, tell the server you are sending JSON with the Content-Type header, and convert your object to a JSON string with JSON.stringify():

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: title,
      body: body,
      userId: 1,
    }),
  });

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

  return response.json();
}

const post = await createPost('Hello Fetch', 'My first POST request.');
console.log(post.id); // 101 — the fake API returns the new id

PUT, PATCH, and DELETE work exactly the same way — only the method value changes, and DELETE usually sends no body:

// Update a post
await fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'PUT',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ title: 'Updated title', body: 'Updated body', userId: 1 }),
});

// Delete a post
await fetch('https://jsonplaceholder.typicode.com/posts/1', { method: 'DELETE' });

Step 4: Add headers, like an auth token

Most real APIs need an authorization header. Pass it in the same headers object, and keep the token in a variable — never hard-code a real secret into code you commit:

const token = 'your-api-token-here';

const response = await fetch('https://api.example.com/profile', {
  headers: {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${token}`,
  },
});

The same pattern works for any custom header the API asks for.

Step 5: Add a timeout so a slow server cannot freeze your app

By default, fetch() waits forever. If the server hangs, your page hangs with it. AbortSignal.timeout() fixes that in one line — it aborts the request after the given milliseconds and throws a TimeoutError:

async function request(url, options = {}, timeoutMs = 8000) {
  try {
    const response = await fetch(url, {
      ...options,
      signal: AbortSignal.timeout(timeoutMs),
    });

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

    return response.json();
  } catch (error) {
    if (error.name === 'TimeoutError') {
      throw new Error(`Request timed out after ${timeoutMs} ms`);
    }
    throw error;
  }
}

const user = await request('https://jsonplaceholder.typicode.com/users/1');
console.log(user.name);

This small helper is worth copying into every project: it checks the status, parses the JSON, and enforces a timeout, so every call site stays short and readable.

Step 6: Run several requests in parallel

If you need a user and their posts, do not wait for one request to finish before starting the next. Promise.all() runs them together and waits for all of them:

const [user, posts] = await Promise.all([
  request('https://jsonplaceholder.typicode.com/users/1'),
  request('https://jsonplaceholder.typicode.com/users/1/posts'),
]);

console.log(user.name, 'has', posts.length, 'posts');

Two requests that take one second each now finish in about one second instead of two. One warning: if any request in Promise.all() fails, the whole thing rejects. When you want the results even if one fails, use Promise.allSettled() instead.

Common Fetch API errors and their fixes

What you see What it means The fix
Empty object {} instead of an error The server returned 404, but fetch did not reject Check response.ok before reading the body
TypeError: Failed to fetch Network problem, wrong URL, or the server is down Check the URL and your connection; open the Network tab
CORS error in the console The API does not allow requests from your origin The fix is on the server (CORS headers), not in your code
SyntaxError: Unexpected token You called .json() on a response that is not JSON Check response.headers.get('Content-Type') first, or use .text()
Page freezes on a slow API No timeout was set Use AbortSignal.timeout() as shown above

The CORS row surprises people the most. Browsers block cross-origin requests unless the server sends the right Access-Control-Allow-Origin header. No header or option in your fetch() call can override that — it is a server setting, and for public practice APIs like JSONPlaceholder it is already enabled.

fetch() vs Axios — which one should you use?

Axios is a popular library that wraps requests with conveniences: it throws on HTTP errors automatically, it has built-in timeouts and request interceptors, and it works the same in old browsers. fetch() needs the small helper from Step 5 to match that behaviour. For learning and for most small projects, fetch() is enough — it is built in, it has no dependency to install or update, and everything in this tutorial works in the browser console right now. Reach for Axios when a project needs interceptors, automatic retries, or upload progress bars.

Wrapping up

The whole Fetch API fits in a few habits: use async/await so the code reads clearly, always check response.ok because fetch will not throw for a 404, set the Content-Type header and JSON.stringify() the body when you POST, add a timeout with AbortSignal.timeout(), and run independent requests together with Promise.all(). With those habits, calling any REST API from JavaScript is the same short pattern every time.

Try it yourself: open your browser console, paste the request() helper from Step 5, and fetch a user from JSONPlaceholder. Then change the URL to your own Laravel API — the one from our earlier REST API tutorial works the same way — and you have a full front end talking to a back end you built.

#JavaScript #FetchAPI #RESTAPI #WebDevelopment #Tutorial

Was this helpful? 0 likes Login to like & bookmark
RH

Written by

Raja Hunain

Full Stack Developer at Raja Dev Solutions — writes about real development work, the errors he faced and exactly how he fixed them, plus practical Laravel, PHP, JavaScript and MySQL tutorials.

More about the author

Comments (0)

No comments yet. Be the first to comment.

Leave a comment

Comments are moderated and appear after approval.

Keep reading

Related Articles