Fetch API
Modern JavaScript provides a built-in way to make HTTP requests from the browser.
The Fetch API allows you to request data from servers, send data, and work with APIs in a clean and readable way.
What Is the Fetch API?
The Fetch API is a modern replacement
for older request techniques like XMLHttpRequest.
It returns a Promise that resolves to a response object.
Basic Fetch Request (GET)
A simple GET request using fetch:
fetch("https://api.example.com/users")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});
Fetch does not directly return data — it returns a promise.
Understanding the Response
The response object contains metadata
about the request.
- Status code
- Headers
- Body
To read JSON data,
you must call response.json().
Using Fetch with Async / Await
Fetch works very well with async/await, making code easier to read.
async function getUsers() {
try {
const response = await fetch("https://api.example.com/users");
const data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}
This approach is recommended for modern projects.
Sending Data with Fetch (POST)
Fetch can also send data to a server.
fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Alex",
role: "Developer"
})
});
The data must be converted to JSON before sending.
Handling Errors Properly
Fetch does not reject promises for HTTP errors like 404 or 500.
You must manually check the response status.
async function fetchData() {
const response = await fetch("https://api.example.com/data");
if (!response.ok) {
throw new Error("Request failed");
}
return response.json();
}
Real-World Example
Fetching data and updating the UI:
async function loadUser() {
const response = await fetch("/user");
const user = await response.json();
document.getElementById("name").innerText = user.name;
}
This pattern is extremely common in web apps.
Common Beginner Mistakes
- Forgetting to parse JSON
- Ignoring response status
- Not handling network errors
Always handle errors gracefully.
Thumb Rules
- Fetch returns a promise
- Always parse the response
- Check
response.ok - Use async/await for clarity
What Comes Next?
Now that you can make API requests, the next step is handling multiple asynchronous calls together.
In the next lesson, we will explore Async API Integration.