Using the
Fetch API
to Get and Post Data

Introduction to Fetch API

The fetch() API in JavaScript is a modern, promise-based way to make HTTP requests to servers. It works in all modern browsers and replaces the older XMLHttpRequest API with a cleaner and more powerful interface.

Why Use Fetch?

  • It returns Promises — making asynchronous programming more elegant
  • Supports JSON and other content types out-of-the-box
  • Allows better control over requests and responses

Example 1: GET Request Using Fetch

Let's fetch a list of users from a public API.

// Fetching users from JSONPlaceholder API
fetch('https://jsonplaceholder.typicode.com/users')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json(); // parse JSON body
  })
  .then(data => {
    console.log('Fetched users:', data);
  })
  .catch(error => {
    console.error('Fetch error:', error);
  });
Fetched users: [ { id: 1, name: 'Leanne Graham', ... }, ... ]

Question:

What does response.ok check for?

Answer: It checks whether the HTTP status is in the range 200–299. If not, the request is considered unsuccessful.

Example 2: POST Request Using Fetch

Now let's send data to the server using a POST request.

// Posting data to JSONPlaceholder API
const postData = {
  title: 'Hello Fetch',
  body: 'This is a POST request example.',
  userId: 1
};

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(postData)
})
  .then(response => response.json())
  .then(data => {
    console.log('POST success:', data);
  })
  .catch(error => {
    console.error('POST error:', error);
  });
POST success: { id: 101, title: 'Hello Fetch', body: 'This is a POST request example.', userId: 1 }

Question:

Why do we use JSON.stringify(postData)?

Answer: The body of a fetch POST request must be a string, so we convert the JavaScript object into a JSON string format before sending.

Handling Fetch Errors

Fetch only throws an error on network failure (like no internet). It won’t reject on HTTP errors like 404 or 500 — so you need to check response.ok manually.

fetch('https://jsonplaceholder.typicode.com/unknown-endpoint')
  .then(response => {
    if (!response.ok) {
      throw new Error(`Error: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Handled error:', error.message);
  });
Handled error: Error: 404

Points to Remember

  • fetch() always returns a Promise.
  • Always handle errors using .catch() or try/catch with async/await.
  • Use response.json() to parse the JSON response.
  • POST requests require setting the 'Content-Type' to 'application/json'.

Practice Tip

Try using fetch to make GET and POST requests to your own mock API using reqres.in or JSONPlaceholder.

Mallikarjuna Mallisetty, author
About the author

Mallikarjuna Mallisetty

General programming

Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.

View LinkedIn profile ↗