The Fetch API provides a modern, promise-based way to make HTTP requests from JavaScript. It acts as a cleaner, more powerful alternative to XMLHttpRequest and is commonly used to:
Promise or async/await.Fetch is built into modern browsers and returns a Promise that resolves to a Response object.
.then() or async/await.response.json() or response.text()..catch() or try...catch to handle network errors.Basic syntax of the Fetch API looks like this:
fetch(url, [options])
.then(response => {
// inspect or transform response here
})
.catch(error => {
// handle network errors here
});
Where:
url is the endpoint you are calling (string).options is an optional object to configure:
method – HTTP method (GET, POST, PUT, DELETE, etc.).headers – custom headers like Content-Type.body – data sent with the request (e.g. JSON string).A simple GET request that fetches JSON data and logs it to the console.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
async/await makes asynchronous code look more like synchronous code and is easier to read for complex flows.
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('HTTP error! Status: ' + response.status);
}
const data = await response.json();
console.log('Data:', data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();
You can send JSON data to a server by using the options object with method, headers, and body.
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'John', age: 30 })
})
.then(response => {
if (!response.ok) {
throw new Error('HTTP error! Status: ' + response.status);
}
return response.json();
})
.then(data => console.log('Saved:', data))
.catch(error => console.error('Error:', error));
Below is a small interactive demo. It uses fetch to load a sample post from a public API and renders the title and body on the page.
Click the button to fetch and display a sample post using the Fetch API.
fetch() sends a GET request to the API URL.response.json() to parse it.async/await for complex flows – it makes the logic easier to follow than chaining many .then() calls.response.ok and handle non-2xx status codes explicitly.try...catch or .catch() to handle network errors and avoid silent failures.response.json(), response.text(), response.blob(), etc.).response.ok.XMLHttpRequest and rewrite the requests using the Fetch API.