A Guide to the JavaScript Fetch API

JavaScript Logo

The Fetch API provides a modern, powerful, and flexible interface for fetching resources across the network. It's a promise-based API that has largely replaced the older `XMLHttpRequest` for making network requests in the browser.

Making a Simple GET Request

The `fetch()` function takes one mandatory argument: the URL of the resource you want to fetch. It returns a Promise that resolves to the `Response` object representing the response to your request.

fetch('https://api.example.com/users/1')
  .then(response => {
    // Check if the request was successful
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json(); // Parse the JSON from the response body
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
  });

Using `async/await`

`async/await` syntax makes Fetch code much cleaner and easier to read.

async function getUser() {
  try {
    const response = await fetch('https://api.example.com/users/1');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Could not fetch user:', error);
  }
}

getUser();

Making a POST Request

To make other types of requests (like POST, PUT, DELETE), you can pass a second argument to `fetch`: an `options` object.

async function createUser(userData) {
  const response = await fetch('https://api.example.com/users', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(userData) // Convert the JS object to a JSON string
  });
  return response.json();
}

createUser({ name: 'Alice', job: 'Developer' })
  .then(data => console.log(data));

Comments