What is the Fetch API?
The Fetch API provides a modern, promise-based way to make HTTP requests in JavaScript. It's widely used to retrieve or send data to servers, commonly with REST APIs.
Why Use Fetch Instead of XMLHttpRequest?
- Simpler syntax using Promises
- More readable and maintainable
- Built-in support for JSON
- Used in both browser and server (Node.js with polyfills)
Example 1: Making a GET Request
Let's fetch some user data from a free public API called jsonplaceholder.typicode.com
.
// Fetch user data (GET request)
fetch('https://jsonplaceholder.typicode.com/users/1')
.then(response => response.json())
.then(data => {
console.log('User Data:', data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
Output:
User Data: { id: 1, name: "Leanne Graham", username: "Bret", email: "Sincere@april.biz", ... }
Question: What if the response is not a 200 OK?
Answer: The fetch promise does not reject on HTTP errors (like 404 or 500). You have to check response.ok
to handle those cases manually.
Example 2: Handling Errors Gracefully
fetch('https://jsonplaceholder.typicode.com/invalid-url')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not OK');
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Fetch failed:', error.message);
});
Output:
Fetch failed: Network response was not OK
Example 3: Sending a POST Request
Now let’s send some data to the server using POST
method. This is useful for forms, comments, user creation, etc.
const postData = {
title: 'Learn Fetch API',
body: 'This is a POST request example.',
userId: 101
};
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
})
.then(response => response.json())
.then(data => {
console.log('Response from POST:', data);
})
.catch(error => {
console.error('Error:', error);
});
Output:
Response from POST: { title: "Learn Fetch API", body: "This is a POST request example.", userId: 101, id: 101 }
Question: Why use JSON.stringify
for body?
Answer: Fetch expects the body to be a string, so we convert our JavaScript object to a JSON string before sending it.
Example 4: Async/Await Version
If you want cleaner and more readable syntax, use async/await
.
async function getUser() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users/2');
if (!response.ok) {
throw new Error('Request failed');
}
const data = await response.json();
console.log('User:', data);
} catch (error) {
console.error('Error:', error.message);
}
}
getUser();
Output:
User: { id: 2, name: "Ervin Howell", ... }
Key Points to Remember
- Fetch is Promise-based and cleanly supports
then/catch
orasync/await
- Always check
response.ok
to handle non-200 responses - Use
JSON.stringify
for sending objects in POST - Use
Content-Type: application/json
header for JSON requests