What is fetch API?
The Fetch API is a modern, powerful, and standard way to perform network HTTP requests in JavaScript, replacing the outdated and bulky XMLHttpRequest. Basic usage comes down to calling the fetch(url, options) function, which receives the target address and an optional settings object, such as the method, headers, and request body. In response, the method returns a Promise that resolves with a Response object as soon as the server sends the headers, without waiting for the entire response body to load.
To extract useful data from the received response, special asynchronous methods of the Response object are provided. Most commonly, response.json() is used for parsing JSON data, but response.text() is also available for working with plain text or HTML, and response.blob() for downloading binary files, images, or audio. These methods also return promises, so the await operator must be applied to them to get the final result.
When working with the Fetch API, developers should keep in mind an important architectural feature: the promise returned by the fetch function is rejected (transitions to the rejected state) only in case of serious network failures, such as a complete lack of internet connection or DNS errors. If the server responds with error codes 404 (Not Found) or 500 (Internal Server Error), the promise is still considered successful. That is why after calling fetch, it is always necessary to check the response.ok flag or manually analyze the response.status property.