Working with the Fetch API
What Is the Fetch API?
Section titled “What Is 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.
Basic Syntax
Section titled “Basic Syntax”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.
Making a Simple GET Request
Section titled “Making a Simple GET Request”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
Using Async/Await (Modern Approach)
Section titled “Using Async/Await (Modern Approach)”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
Making a POST Request
Section titled “Making a POST Request”Sending data to an HTTP server using a POST request.
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()
Common HTTP Methods
Section titled “Common HTTP Methods”| Method | Purpose | Has Body |
|---|---|---|
| GET | Retrieve data | No |
| POST | Create new resource | Yes |
| PUT | Update entire resource | Yes |
| PATCH | Update partial resource | Yes |
| DELETE | Remove resource | Optional |
Checking Response Status
Section titled “Checking Response Status”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-299response.status: HTTP status code (200, 404, 500, etc.)response.statusText: Status message
Handling Different Response Types
Section titled “Handling Different Response Types”Parsing the response body of a GET request using the methods of the response object.
// JSON responseconst data = await response.json();
// Plain textconst text = await response.text();
// Blob (for images, files)const blob = await response.blob();
// Form dataconst formData = await response.formData();javascript
Real-World Example: Search Feature
Section titled “Real-World Example: Search Feature”The following is an example of a live search feature using the Fetch API, allowing users to search for planets by name.
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
Common Fetch Options
Section titled “Common Fetch Options”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
Error Handling Best Practices
Section titled “Error Handling Best Practices”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
To Note:
Section titled “To Note:”- Fetch returns Promises: Use
.then()orasync/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.