Skip to main content

Fetch API JavaScript

The Fetch API is a modern web API that provides a simple interface for making network requests in JavaScript. It allows you to make HTTP requests to a server and handle the response in a straightforward manner.

The Fetch API uses the fetch() function to make HTTP requests. The fetch() function takes one argument: the URL of the resource you want to fetch.

Here's an example of using the fetch() function to retrieve a JSON file:

fetch('https://example.com/data.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

In this example:

  • This code makes an HTTP GET request to the URL 'https://example.com/data.json'.
  • When the response is received, it is converted to JSON using the json() method of the Response object.
  • The resulting JSON data is logged to the console.
  • If there's an error, it's logged to the console as well.

The HTTP Method

The Fetch API also allows you to specify options for the request, such as the HTTP method, headers, and request body.

Here's an example of making a POST request with JSON data in the request body:

fetch('https://example.com/api/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John Doe',
email: 'john@example.com'
})
})
.then(response => console.log(response))
.catch(error => console.error(error));

In this example:

  • This code makes an HTTP POST request to the URL 'https://example.com/api/data'.
  • The request includes a JSON payload in the request body, and the Content-Type header is set to 'application/json'.
  • When the response is received, it is logged to the console.
  • If there's an error, it's logged to the console as well.

Async/Await with Fetch

Async/await is a modern JavaScript language feature that allows you to write asynchronous code in a more synchronous style. You can use async/await with the Fetch API to make network requests and handle the response in a more readable and intuitive way.

Here's an example of using async/await with the Fetch API:

async function fetchData() {
try {
const response = await fetch('https://example.com/data.json');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}

fetchData();

In this example:

  • The fetchData() function is defined as an async function.
  • Inside the function, the await keyword is used to wait for the fetch() function to resolve and return a Response object.
  • Once the Response object is obtained, the await keyword is used again to wait for the json() method to parse the response data as JSON. -If there's an error during the network request, the catch block will handle the error.