The Fetch API
In the previous lesson, we learned about Async JS. Now, weโre going to use those skills for the most common task in web development: Fetching data from a server.
The fetch() method is a built-in JavaScript tool that allows you to make HTTP requests to a server to retrieve or send data.
1. What is an API?โ
Before we fetch, we need to know where we are fetching from. An API (Application Programming Interface) is like a waiter in a restaurant.
- You (The Client): Order food (Request).
- The API (The Waiter): Takes your order to the kitchen.
- The Server (The Kitchen): Prepares the food.
- The API (The Waiter): Brings the food back to your table (Response).
2. The Basic Fetch Syntaxโ
The fetch() function takes one main argument: the URL of the data you want. It returns a Promise.
fetch('https://api.example.com/data')
.then(response => response.json()) // Convert the raw response to JSON
.then(data => console.log(data)) // Use the data
.catch(error => console.error('Error:', error));
3. Using Fetch with Async/Awaitโ
At CodeHarborHub, we prefer the async/await syntax because it is much easier to read and debug.
async function getGitHubUser(username) {
try {
const response = await fetch(`https://api.github.com/users/${username}`);
if (!response.ok) {
throw new Error("User not found!");
}
const data = await response.json();
console.log(data.name + " has " + data.public_repos + " repositories.");
} catch (error) {
console.log("Something went wrong: " + error.message);
}
}
getGitHubUser('ajay-dhangar');
4. HTTP Methodsโ
When you communicate with a server, you aren't just "getting" things. You can also "send" or "delete" things. These are called HTTP Methods:
| Method | Action | Example |
|---|---|---|
| GET | Retrieve data. | Reading a blog post. |
| POST | Send new data. | Creating a new account. |
| PUT | Update existing data. | Changing your profile picture. |
| DELETE | Remove data. | Deleting a tweet. |
5. Sending Data (POST Request)โ
To send data, you pass a second argument to fetch()โan object containing the method, headers, and the body of your data.
async function uploadPost() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'Learning Fetch',
body: 'I am practicing Fetch API at CodeHarborHub!',
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
});
const result = await response.json();
console.log("Success! Post created with ID:", result.id);
}
Project: The Random User Generatorโ
Let's build a mini-tool that fetches a random person and displays their name and email on the screen.
HTML:
<div id="user-card">
<h2 id="name">Loading...</h2>
<p id="email"></p>
<button id="next-btn">Get Next User</button>
</div>
JavaScript:
const nameDisplay = document.getElementById('name');
const emailDisplay = document.getElementById('email');
const btn = document.getElementById('next-btn');
async function fetchUser() {
const response = await fetch('https://randomuser.me/api/');
const data = await response.json();
const user = data.results[0];
nameDisplay.innerText = `${user.name.first} ${user.name.last}`;
emailDisplay.innerText = user.email;
}
btn.addEventListener('click', fetchUser);
// Load one user immediately when page opens
fetchUser();
Always check if (response.ok). A fetch() will only "fail" if there is a network error. If the server says "404 Not Found," fetch still technically "succeeded" in making the connection. You must check the status yourself!
Servers usually send data in JSON (JavaScript Object Notation) format. It looks just like a JavaScript Object, but all the keys are wrapped in double quotes. response.json() is the magic command that turns that text back into a real JS object we can use.