techStackGuru

Making HTTP Requests using fetch


Several HTTP request mechanisms are provided by JavaScript. Requests and responses can be handled asynchronously using the Fetch API, which is the most commonly used approach. Using the fetch() function, HTTP requests can be initiated in an easy and powerful manner. A wide variety of HTTP methods can be used, including GET, POST, PUT, PATCH, and DELETE. The developer can also specify headers, handle response types such as JSON or text, and manage errors.

It is also possible to use the older XMLHttpRequest object, which offers similar functionality but has a slightly different syntax. Through JavaScripts HTTP request mechanisms, data can be retrieved from remote servers and communicated with APIs.

Example 1 - GET Request

async function fetchData() {
  const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
  const jsonData = await response.json();
  console.log(jsonData);
}

Example 2 - GET Request

fetch('https://jsonplaceholder.typicode.com/users/1')
.then(response => response.json())
.then(data => {
  // Process the data returned from the API
  console.log(data);
})
.catch(error => {
  // Handle any errors that occur during the API call
  console.log('Error:', error);
}); 

The example above uses the URL to make a GET request. In the fetch function, a Promise is returned that resolves to the response returned from the server. It is possible to chain .then methods to handle data from a response.

In the first case, json() is used to convert the response to JSON format. To handle the parsed data, we can chain this method with another .then method.

With the second .then method, you can process and operate on the data returned by the API. We simply log the data to the console in the example above.

Example 3 - POST Request

fetch('https://reqbin.com/echo/post/json', {
  method: 'POST',
  headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
  },
  body: JSON.stringify({ "id": 78912 })
})
 .then(response => response.json())
 .then(response => console.log(JSON.stringify(response))) 

Example 4 - POST Request

fetch("https://jsonplaceholder.typicode.com/todos", {
  method: "POST",
  body: JSON.stringify({
    userId: 1,
    title: "Hello POST Request",
    completed: false
  }),
  headers: {
    "Content-type": "application/json; charset=UTF-8"
  }
  })
.then((response) => response.json())
.then((json) => console.log(json)); 

Example 5 - PUT Request

const url = 'https://jsonplaceholder.typicode.com/users/1'; 
const data = {
	name: 'vishal torgal',
	username: 'vishaltor',
	email: 'vishaltor@gmail.com'
}
fetch(url, {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
  .then(response => response.json())
  .then(result => {
    console.log('PUT request successful', result);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Fetch takes two arguments: a URL and an options object. Considering the data being sent is in JSON, we need to set the Content-Type header of the options object to 'application/json'.

Example 6 - PATCH Request

 const url = 'https://jsonplaceholder.typicode.com/users/1'; 
const data = { name: 'test'};
fetch(url, {
  method: 'PATCH',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
  .then(response => response.json())
  .then(result => {
    console.log('PATCH request successful', result);
  })
  .catch(error => {
    console.error('Error:', error);
  }); 

To send this PATCH request, we are using the fetch function. The url variable specifies the URL of the API endpoint and the data variable specifies the data to send.

Example 7 - Delete Request

  const url = 'https://jsonplaceholder.typicode.com/users/1';
fetch(url, {
  method: 'DELETE',
})
.then(response => {
  if (response.ok) {
    console.log('DELETE request successful');
  } else {
    console.error('Error:', response.status);
  }
})
.catch(error => {
  console.error('Error:', error);
}); 

A DELETE request does not include a request body since it is not commonly requested. When the request is sent, the response is handled in the then method. A response with a status code in the 2xx range indicates a successful response, as indicated by the response.ok property. The console is logged as a success message if it is true. Errors are logged to the console if its false.