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?

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);
  });
    

Output:

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);
  });
    

Output:

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);
  });
    

Output:

Handled error: Error: 404

Points to Remember

Practice Tip

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



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M