⚡
Fetch API - Making HTTP Requests
Intermediate
110 XP
45 min
Lesson Content
Fetch API - Making HTTP Requests
The Fetch API provides a modern way to make HTTP requests. It's built into browsers and returns Promises, making it perfect for async/await.
Basic Fetch Request
// GET request
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));Fetch with Async/Await
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
}
}POST Request
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'John',
email: 'john@example.com'
})
})
.then(response => response.json())
.then(data => console.log(data));Response Methods
- response.json() - Parse as JSON
- response.text() - Get as text
- response.blob() - Get as blob
- response.arrayBuffer() - Get as array buffer
Checking Response Status
fetch('/api/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data));Example Code
Use Fetch API to make HTTP requests
// Note: In a real environment, you'd use actual API endpoints
// This example simulates fetch behavior
// Simulate fetch function for practice
function mockFetch(url, options = {}) {
return new Promise((resolve) => {
setTimeout(() => {
if (options.method === 'POST') {
const body = JSON.parse(options.body);
resolve({
ok: true,
status: 201,
json: async () => ({ id: 1, ...body, created: true })
});
} else {
resolve({
ok: true,
status: 200,
json: async () => ({ id: 1, name: 'John', email: 'john@example.com' })
});
}
}, 100);
});
}
// GET request
async function getUser(userId) {
try {
const response = await mockFetch(`/api/users/${userId}`);
if (!response.ok) {
throw new Error('Failed to fetch user');
}
const user = await response.json();
console.log('User:', user);
return user;
} catch (error) {
console.error('Error:', error);
}
}
// POST request
async function createUser(userData) {
try {
const response = await mockFetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData)
});
const newUser = await response.json();
console.log('Created user:', newUser);
return newUser;
} catch (error) {
console.error('Error:', error);
}
}
// Test the functions
console.log('Fetching user...');
getUser(1);
console.log('\nCreating user...');
createUser({ name: 'Alice', email: 'alice@example.com' });Expected Output:
Fetching user...
User: {id:1,name:John,email:john@example.com}
Creating user...
Created user: {id:1,name:Alice,email:alice@example.com,created:true}Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code