Skip to content

Working with the Fetch API

  • The Fetch API is a modern JavaScript interface for making HTTP requests to HTTP servers.
  • It provides a cleaner, more flexible, and promise-based alternative to the older XMLHttpRequest.
  • With Fetch, you can easily retrieve data, send form submissions, upload files, and interact with APIs.

fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
javascript
  • url: The endpoint you want to request
  • options (optional): Request configuration object for method, headers, body, etc.

Fetching JSON data from an API:

fetch('https://api.example.com/planets')
.then(response => response.json())
.then(planets => {
console.log(planets);
// Display users on the page
})
.catch(error => console.error('Failed to fetch planets:', error));
javascript

Key points:

  • fetch() returns a Promise
  • .json() parses the response body as JSON (also returns a Promise)
  • Use .catch() to handle errors

Making a GET request using async/await.

async function getPlanets() {
try {
const response = await fetch('https://api.example.com/planets');
const planets = await response.json();
console.log(planets);
} catch (error) {
console.error('Failed to fetch planets:', error);
}
}
getPlanets();
javascript

Benefits:

  • Cleaner and more readable code
  • Easier error handling with try/catch
  • Works better with multiple sequential requests

Sending data to an HTTP server using a POST request.

Example: Sending a POST request to create a planet
async function createPlanet(planetData) {
try {
const response = await fetch('https://api.example.com/planets', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(planetData)
});
const result = await response.json();
console.log('Planet created:', result);
} catch (error) {
console.error('Error creating planet:', error);
}
}
createPlanet({ name: 'Earth', system: 'Solar System', distanceFromStar: 149.6, radius: 6371, mass: 5.972e24, habitable: true, discoveryDate: '1970-01-01' });
javascript

Important:

  • Specify method: 'POST'
  • Set appropriate headers
  • Convert JavaScript objects to JSON with JSON.stringify()

MethodPurposeHas Body
GETRetrieve dataNo
POSTCreate new resourceYes
PUTUpdate entire resourceYes
PATCHUpdate partial resourceYes
DELETERemove resourceOptional

Checking the response status of a GET request.

async function fetchData() {
try {
const response = await fetch('https://api.example.com/planets');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch failed:', error);
}
}
javascript

Important properties:

  • response.ok: true if status is 200-299
  • response.status: HTTP status code (200, 404, 500, etc.)
  • response.statusText: Status message

Parsing the response body of a GET request using the methods of the response object.

Example: Parsing the response body of a GET request using async/await
// JSON response
const data = await response.json();
// Plain text
const text = await response.text();
// Blob (for images, files)
const blob = await response.blob();
// Form data
const formData = await response.formData();
javascript

The following is an example of a live search feature using the Fetch API, allowing users to search for planets by name.

Example: Live search feature using the Fetch API
const searchInput = document.getElementById('search');
const resultsDiv = document.getElementById('results');
// AJAX triggering action: on keypress (as you type the search query)
searchInput.addEventListener('keypress', async (e) => {
const query = e.target.value;
if (query.length < 3) return; // Wait for at least 3 characters
try {
const response = await fetch(`https://api.example.com/planets?q=${query}`);
const results = await response.json();
// AJAX response: the search results are displayed in the resultsDiv
resultsDiv.innerHTML = results
.map(item => `<div class="result">${item.name}</div>`)
.join('');
} catch (error) {
resultsDiv.innerHTML = '<p>Search failed. Please try again.</p>';
}
});
javascript

Setting the options of a GET request.

fetch(url, {
method: 'POST', // HTTP method
headers: { // Request headers
'Content-Type': 'application/json',
'Authorization': 'Bearer token123'
},
body: JSON.stringify(data), // Request body
mode: 'cors', // cors, no-cors, same-origin
credentials: 'include', // include, same-origin, omit
cache: 'no-cache' // Cache mode
});
javascript

Handling errors of a GET request using async/await.

async function fetchWithErrorHandling(url) {
try {
const response = await fetch(url);
// Check for HTTP errors
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
return data;
} catch (error) {
// Network errors, parsing errors, etc.
if (error.name === 'TypeError') {
console.error('Network error or CORS issue');
} else {
console.error('Fetch error:', error.message);
}
throw error; // Re-throw if needed
}
}
javascript

  • Fetch returns Promises: Use .then() or async/await
  • Always check response.ok: Fetch doesn’t reject on HTTP errors.
  • Parse response appropriately: Use .json(), .text(), or .blob()
  • Handle errors properly: Use try/catch with async/await.
  • Set correct headers: Especially for POST/PUT requests.
  • Remember CORS: Cross-origin requests need proper server configuration.