JAVASCRIPT
Optimizing API Calls with ETag and If-None-Match
Learn to optimize API requests using HTTP ETag headers and the If-None-Match condition to reduce bandwidth and server load by fetching data only when it has changed.
async function fetchWithETag(url, etag = null) {
const headers = {};
if (etag) {
headers['If-None-Match'] = etag;
}
try {
const response = await fetch(url, {
method: 'GET',
headers: headers
});
if (response.status === 304) {
console.log('Data not modified. Using cached version.');
return { status: 304, data: null, etag: etag };
} else if (response.ok) {
const newEtag = response.headers.get('ETag');
const data = await response.json();
console.log('New data fetched.');
return { status: response.status, data: data, etag: newEtag };
} else {
console.error(`API Error: ${response.status} - ${response.statusText}`);
return { status: response.status, data: null, etag: etag };
}
} catch (error) {
console.error('Network or parsing error:', error);
return { status: 0, data: null, etag: etag, error: error };
}
}
// Example Usage:
let lastEtag = null;
async function loadData() {
const result = await fetchWithETag('https://api.example.com/items', lastEtag);
if (result.status === 200) {
console.log('Processing new data:', result.data);
lastEtag = result.etag;
// Update UI with result.data
} else if (result.status === 304) {
// Data hasn't changed, use previously rendered data or cache
console.log('UI is already up-to-date.');
} else {
console.error('Failed to load data.');
}
}
loadData();
How it works: This snippet demonstrates how to leverage HTTP ETag headers for efficient API data fetching. When a resource is first fetched, its ETag (a unique identifier for that version of the resource) is stored. On subsequent requests, this ETag is sent in the `If-None-Match` header. If the resource on the server hasn't changed, the server responds with a `304 Not Modified` status, indicating that the client can use its cached version, saving bandwidth and server processing. If the resource has changed, the server returns the new data with a new ETag.