API Interaction

Understanding and Using the Fetch API

Web API in the form of an object, provided by the user agent, whose methods transfer data between a user agent and a web server, often for continually modifying a loaded web page; despite the name, can be used with non-HTTP protocols or non-XML data

Web API in the form of an object, provided by the user agent, whose methods transfer data between a user agent and a web server, often for continually modifying a loaded web page; despite the name, can be used with non-HTTP protocols or non-XML data.

The Fetch API is a modern, promise-based system for making asynchronous HTTP requests. It is built into most modern browsers and is used to load data from a server, submit new data or update existing data.

Introduction to the Fetch API

The Fetch API provides a more powerful and flexible feature set to handle requests and responses than the older XMLHttpRequest, which was typically used for AJAX requests. It is promise-based, which means it uses objects that represent the eventual completion or failure of an operation.

Making Requests with Fetch

To make a request with Fetch, you call the fetch() function, passing in the URL of the resource you want to fetch as an argument. This returns a Promise that resolves to the Response object representing the response to the request.

Here's a basic example:

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

In this example, fetch() makes a GET request to the specified URL. The then() method is called when the Promise resolves, passing the response to a callback function. The response.json() method returns another Promise that resolves with the result of parsing the body text as JSON, which is then logged to the console. If any error occurs during the fetch or parsing, the catch() method is called with the error.

Handling Responses

The Response object returned by fetch() includes several properties and methods to handle the response:

  • ok: A Boolean indicating whether the response was successful (status in the range 200-299) or not.
  • status: The status code of the response.
  • statusText: The status message corresponding to the status code.
  • url: The URL of the response.
  • clone(): Creates a clone of the response.
  • json(): Returns a Promise that resolves with the result of parsing the body text as JSON.

Error Handling with Fetch

The Fetch API only rejects a Promise on network failure or if anything prevented the request from completing. It will not reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, as soon as the server responds with headers, the Promise will resolve normally, and it will only reject on network failure or if anything prevented the request from completing.

To handle HTTP errors, you need to check the ok property of the Response object:

fetch('https://api.example.com/data') .then(response => { if (!response.ok) { throw new Error('HTTP error ' + response.status); } return response.json(); }) .then(data => console.log(data)) .catch(error => console.error('Error:', error));

In this example, if the response is not ok, an Error is thrown with the status code, which is caught in the catch() method.

The Fetch API provides a powerful, flexible way to make HTTP requests. It's promise-based, which makes it easier to use and understand than the older XMLHttpRequest. By understanding how to make requests, handle responses, and handle errors with Fetch, you can load data from a server, submit new data, or update existing data.