Fetch API in JavaScript (Live Playground)
The Fetch API is a modern, easy-to-use method for making asynchronous API requests in JavaScript. It is built on Promises, making it more powerful and flexible than XMLHttpRequest. In this tutorial, we will learn how to use the Fetch API to make API requests and handle responses.
Basic Fetch Request
To make a request with the Fetch API, call the fetch()
function with the URL of the desired resource:
Example:
fetch('https://api.example.com/data');
Customizing the Request
You can customize the request by passing an options object as the second argument to the fetch()
function:
Example:
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ key: 'value' }),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Handling the Response
The fetch()
function returns a Promise that resolves to the Response object. Use the then()
method to handle the response, and the json()
method to parse the JSON data:
Example:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
Checking the Response Status
When handling the response, it's essential to check the status to ensure the request was successful. The Response object has a status
property that indicates the HTTP status code:
Example:
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));
Handling Different Response Types
The Response object also has methods for handling different response types, such as text()
and blob()
:
Example:
fetch('https://api.example.com/text')
.then(response => response.text())
.then(text => console.log(text))
.catch(error => console.error('Error:', error));
Handling Errors
To handle errors, add a catch()
method after the then()
methods:
Example:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Catching Network Errors
The catch()
method can handle both response status errors and network errors. To differentiate between them, check the Error
object's message:
Example:
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 => {
if (error.message.startsWith('HTTP error')) {
console.error('Request failed:', error);
} else {
console.error('Network error:', error);
}
});
Conclusion
The Fetch API is a powerful, flexible, and modern way to make asynchronous API requests in JavaScript. It offers a simple syntax and uses Promises to handle responses and errors, making it a great choice for working with APIs in modern web applications.