Interfaces used in Fetch API
The Fetch API makes use of the following interfaces:
- fetch(): Used to fetch a resource.
- Headers: It represents response or request headers, allowing us to make a query and take different actions depending on the results.
- Request: It represents a resource request.
- Response: It represents the response to a request.
JavaScript fetch() Method Examples
The JavaScript `fetch()` method is a powerful and versatile tool used in web development to make network requests. This method is part of the Fetch API, which provides a more modern and efficient way to fetch resources over the network compared to older methods like `XMLHttpRequest`. The `fetch()` function returns a Promise, which resolves to the `Response` object representing the response to the request. This allows for handling both success and failure scenarios cleanly and functionally through promise chaining.
Let's look at some examples of how to use the `fetch()` method in different scenarios:
- Basic GET Request:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
This example shows a simple GET request to retrieve data from a specified URL. The response is expected to be in JSON format, so `.json()` is used to convert the response stream to a JavaScript object.
2. POST Request with JSON Body:
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John Doe',
email: 'john@example.com'
})
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));
This example sends a POST request with a JSON body to the server. It includes setting the HTTP method to POST, specifying headers, and converting a JavaScript object to a JSON string for the body.
3. Handling HTTP Errors:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Here, the fetch operation includes error handling that checks if the response is successful (i.e., `response.ok` is true). If the response is not successful, it throws an error that is caught by the `.catch()` method.
4. Sending Credentials with a Request:
fetch('https://api.example.com/data', {
credentials: 'include'
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
This example shows how to include credentials like cookies with the request by setting the `credentials` option to 'include.' This is useful for making requests to endpoints that require session authenticity.
Sending a request using Fetch API
The fetch() method is a global scope method that tells web browsers to send a request to a URL. The URL of the resource is the only parameter required by fetch().
Syntax
The fetch() method returns a Promise, which you may handle with the then() and catch() methods.
let fetchResponse = fetch(weburl);
Syntax
The resource will be available once the request has been completed. The Promise will become a Response object at this point.
fetch(url)
.then(response => {
// handle response
})
.catch(error => {
// handle error
});
The fetched resource is wrapped in the Response object, which is an API wrapper for it. The Response object provides several attributes and methods that can be used to examine the response.
Reading a response using Fetch API
We can use the text() function if the contents of the response are in raw text format.
The text() method produces a Promise that resolves with the fetched resource's entire contents.
fetch('/readme.txt')
.then(response => response.text())
.then(data => console.log(data));
In fact, we'll frequently utilize async/await with the retrieve() method, as shown below:
async function fetchText() {
let response = await fetch('/readme.txt');
let data = await response.text();
console.log(data);
}
Aside from the text() function, the Response object offers various methods to handle different types of data, such as json(), blob(), formData(), and arrayBuffer().
Handling response in Fetch API
The status and statusText attributes of the Response object provide the status code and text.
- The status code for a successful request is 200, and the status text is OK.
async function fetchText() {
let response = await fetch('/readme.txt');
console.log(response.status); // 200
console.log(response.statusText); // OK
if (response.status === 200) {
let data = await response.text();
// handle data
}
}
fetchText();

You can also try this code with Online Javascript Compiler
Run Code
Output:
200
OK
The response code 404 is sent if the requested resource does not exist.
let response = await fetch('/non-existence.txt');
console.log(response.status); // 400
console.log(response.statusText); // Not Found

You can also try this code with Online Javascript Compiler
Run Code
Output:
400
Not Found
Try this code with online javascript compiler for better understanding.
- The response code 500 will be returned if the requested URL returns a server error.
- The status of the Response object is set to 200 if the requesting URL is redirected to a new one with the response 300-309. The rerouted property is also set to true.
When a true failure happens, such as a web browser timeout, a network connection loss, or a CORS(Cross-origin resource sharing) violation, get() returns a promise that is rejected.
JavaScript fetch() Method Use Cases
The fetch() method in JavaScript is highly versatile and can be used in many scenarios in web development like:
- Dynamic Data Loading: The fetch() method is ideal for dynamically loading data without reloading the web page. It allows developers to retrieve data from a server and update the content of a webpage in real-time, enhancing user experience.
- Single-page applications (SPAs): In SPAs, fetch() plays a crucial role in interacting with APIs to obtain data that dictates the display on the client side, thereby supporting the seamless user experience that SPAs are known for.
- Form Submission: Instead of traditional form submissions that require a page reload, fetch() can be used to submit form data asynchronously. This process helps send form data to the server and handle the response without disrupting the user's interaction with the page.
- File Upload: The fetch() method can also handle file uploads. Developers can use it to send files to a server asynchronously which is useful in creating responsive, user-friendly file upload features.
- Polling: For applications that require regular updates from the server, such as live sports scores or stock market feeds, fetch() can be used to poll the server at regular intervals, ensuring that the displayed data is kept current without full page refreshes.
- Interacting with APIs: Whether it’s third-party APIs for data like maps and weather or internal APIs for server data, fetch() is the tool of choice for making HTTP requests, processing the responses, and integrating the data into web applications.
- Progressive Web Apps (PWAs): For PWAs, fetch() is used extensively to handle network requests and caching strategies. This is crucial for enabling offline functionality and improving the app's performance by efficiently managing data requests and responses.
Frequently asked questions
What is the fetch JSON method in JavaScript?
The fetch JSON method in JavaScript uses the `fetch()` function to retrieve JSON data from a server, which is then processed and converted to a JavaScript object.
What is a Promise in the fetch API?
The Promise object describes the result of an asynchronous operation's ultimate completion (or failure).
What is the use of the fetch() function?
In Fetch API, the fetch() method is used to request the server to load data into the websites.
Conclusion
The Fetch API is a network-based interface for retrieving resources. It has a more robust and flexible feature set that allows web browsers to send HTTP requests to servers. Fetch API defines Request and Response objects in a generic way and has better specifications in comparison to jQuery.ajax().
Ready to learn more? Here's a curated list of blogs on this topic for you. Do check it out!
- How to build a REST API
- Introduction to Web API
- Introduction to Web Form API