Using fetch() to Get Data in JavaScript
fetch-api-request.png: "JavaScript diagram showing fetch API making HTTP GET request and receiving JSON response
The fetch()
API is a modern and powerful way to make HTTP requests in JavaScript. It is built into the browser and provides a simple interface for fetching resources asynchronously.
This guide covers how to use fetch()
to get data from an API or server, handle responses, and work with JSON data.
fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
url
: The endpoint you're requesting data from.
options
(optional): An object containing request configuration like method, headers, body, etc.
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log("Fetched data:", data);
})
.catch(error => {
console.error("There was a problem with the fetch operation:", error);
});
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('HTTP error ' + response.status);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch error:', error);
}
}
getData();
You can work with different response types using the appropriate methods:
// Get plain text
response.text();
// Get Blob (e.g., image)
response.blob();
// Get FormData
response.formData();
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your_token_here'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Fetching JSON data from REST APIs
Loading configuration files
Consuming third-party services
Fetching static files like text or images
The fetch()
API is a clean and versatile way to retrieve data in JavaScript. It supports both promise-based and async/await patterns, making it suitable for modern web applications.
Mastering fetch()
enables you to integrate your front-end with back-end services effectively.