JS Fetch API

Fetch API

The Fetch API is a modern way for web browsers to get data from a server. It’s used to make requests (like asking for information) and get responses (like receiving the data you asked for) over the Internet.

For example, you can use it to get information from an API (like weather data or user data) or send data to a server (like submitting a form). The Fetch API is built into most modern browsers, and it works with promises, making it easier to handle asynchronous tasks like loading data without freezing the website.

What is Fetch

The fetch() function allows you to make requests from JavaScript to get data from another place. It is like sending a letter to a friend and waiting for them to return something. Instead of waiting for a letter, though, you send a request over the internet and await a response from the server.

How does the Fetch API work?

   You request: This could be asking for a webpage, image, or data.
   The server responds: It could send back JSON, text, or an image.
•   You process the response: Then you decide what to do with the data. Show it on the page? Save it?

Fetch-Api

How to Use the Fetch API

Now that we know what the Fetch API does, let’s dive into how we can use it. Below is a simple way to use the Fetch API in JavaScript.

Syntax:

fetch(url, options)
.then(response => response.json()) // Convert the response to JSON
.then(data => {
console.log(data); // Do something with the data
})
.catch(error => {
console.log(‘There was an error!’, error);
});

Step-by-Step Breakdown:

1. fetch(url, options) – This line requests the url you provide. If you’re asking for something from a server, you give it the link to where the server is. For example, if you want weather data, you’d use a weather API URL.
2. Then – After the request is made, you need to wait for the server to respond. That’s what .then() does. It’s a way to say, “Once the server responds, do something.”
3. response.json() – When the server sends back data, it’s usually in the form of JSON (JavaScript Object Notation). JSON is a format for storing data in an easy-to-read way. This line converts that response into usable data (an object) that JavaScript can work with.
4. data – This is the actual data we’re working with. In the case of weather, it might be temperature, humidity, or other weather conditions.
5. catch() – In case something goes wrong (e.g., the server is down), the catch() method will handle the error and tell you about it.

Example 1: Getting Data from a Server (GET Request)

Let’s say we want to get a list of users from a server.

fetch(‘https://jsonplaceholder.typicode.com/users’)
.then(response => response.json()) // Convert to JSON
.then(data => {
console.log(data); // Display the data in the console
})
.catch(error => {
console.log(‘Error:’, error);
});

In this example, the server responds with a list of users, and we display it in the console. You could replace console.log() with code to show the users on your webpage.

Code explanation:

1. Fetch Data from the API:

fetch(‘https://jsonplaceholder.typicode.com/users’)

•  fetch() is a built-in JavaScript function used to make network requests.
The URL ‘https://jsonplaceholder.typicode.com/users’ specifies the endpoint from which to retrieve the data.
•  The fetch() function returns a Promise, which represents the eventual completion (or failure) of the asynchronous operation.

2. Process the Response (Convert to JSON):

.then(response => response.json()) // Convert to JSON

•  .then() is a method that gets called when the fetch() request is successful.
•  response.json() is a function that converts the HTTP response (which is typically in the form of a string) into a JavaScript object. This allows you to work with the data in a structured way.
  This response.json() function itself also returns a Promise, which is why another .then() follows it.

3. Handle the Data (Log it to the Console):

Copy code
.then(data => {
console.log(data); // Display the data in the console
})

•  The second .then() method takes the data (which is now the parsed JSON object) and executes the function passed to it.
  Here, the data is logged to the browser’s console using console.log(data).

4. Handle Errors:

.catch() is used to handle any errors that occur during the fetch() operation, such as network issues or problems parsing the response.

If an error occurs, the catch block logs the error to the console.

Output

JS-Data-from

Example 2: Sending Data to the Server (POST Request)

Sometimes, you might need to send data to a server, like when you’re submitting a form. For that, you use a POST request.

Here’s an example where we send data (a new user’s name) to the server:

const newUser = {
name: ‘John Doe’,
username: ‘john_doe’,
email: ‘john.doe@example.com’
};
fetch(‘https://jsonplaceholder.typicode.com/users’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’
},
body: JSON.stringify(newUser) // Convert the object to JSON
})
.then(response => response.json()) // Convert the response to JSON
.then(data => {
console.log(‘New User Added:’, data); // Log the added user
})
.catch(error => {
console.log(‘Error:’, error);
});

Code explanation:

1. Create the New User Object:

const newUser = {
name: ‘John Doe’,
username: ‘john_doe’,
email: ‘john.doe@example.com’
};

The newUser object contains the details of the new user you want to add. This object has three properties: name, username, and email, representing the user’s name, username, and email address.

2. Make a POST Request to the API:

fetch(‘https://jsonplaceholder.typicode.com/users’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’
},
body: JSON.stringify(newUser) // Convert the object to JSON
})

– fetch() is used to send a request to the URL https://jsonplaceholder.typicode.com/users, which is an endpoint for creating a new user in the JSONPlaceholder API.

The request options are provided as the second argument to fetch(). These options specify:

  method: ‘POST’: This indicates that you’re sending data to the server to create a new resource.
  headers: {‘Content-Type’: ‘application/json’}: This tells the server that the body of the request contains JSON data.
 body: JSON.stringify(newUser): The body of the request contains the newUser object, but it must be converted to a JSON string using JSON.stringify() before being sent to the server.

3. Handle the Response:

.then(response => response.json()) // Convert the response to JSON
.then(data => {
console.log(‘New User Added:’, data); // Log the added user
})

After the POST request is sent, the first .then() processes the response. It calls response.json(), which converts the response body (which is usually in JSON format) into a JavaScript object.

•  The second .then() receives the parsed data and logs it to the console using console.log(). This will log the newly added user, including an ID field (which is auto-generated by the server) and the values you sent.

4. Error Handling:

.catch(error => {
console.log(‘Error:’, error);
});

The .catch() method is used to handle any errors that occur during the request. If the fetch request fails or there’s an issue with the response (e.g., network errors), the error is logged to the console.

Output

JS-Sending-data

Important Points to Remember

1. GET vs POST Requests

•  GET is used to retrieve data (e.g., fetch a list of books).
•  POST is used to send data to the server (e.g., submit a form).

2. Handling Errors

It’s important to handle errors. The server might not respond, or the user might be offline. The catch() method helps you neatly handle these errors.

3. Asynchronous Nature

Fetch is asynchronous. This means that your JavaScript doesn’t stop and wait for the server to respond. It continues running while the fetch request is in progress, and when the response comes back, it runs the code inside .then().

Course Video

YouTube Reference :

Practice Examples

You have to solve all the questions given below in the editor without copy-pasting.

1. Write a function fetchPost that uses the Fetch API to retrieve a post from the JSONPlaceholder API (https://jsonplaceholder.typicode.com/posts/1) and logs the title and body of the post.

The task is to write a JavaScript function called fetchPost that uses the Fetch API to retrieve a post from the JSONPlaceholder API (https://jsonplaceholder.typicode.com/posts/1) and logs the title and body of the post.
1. Fetch API Call:
Use the Fetch API to make a GET request to the specified API endpoint (https://jsonplaceholder.typicode.com/posts/1).
2. Retrieve Post Data:
Once the data is fetched, extract the title and body of the post from the response.
3. Log to the Console:
Log the title and body of the post to the console.

Here’s an example program:

<!DOCTYPE html>
<html>
<head>
<title>Fetch Post Example</title>
</head>
<body>
<script>
// JavaScript code
async function fetchPost() {
try {
// Make a GET request to fetch post data
const response = await fetch(‘https://jsonplaceholder.typicode.com/posts/1’);
const postData = await response.json();

// Extract title and body from the post data
const { title, body } = postData;

// Log the title and body to the console
console.log(‘Title:’, title);
console.log(‘Body:’, body);
} catch (error) {
console.error(‘Error:’, error.message);
}
}

// Call the function to fetch and log post data
fetchPost();
</script>
</body>
</html>

Output

2. Write a function getUserDetails that simulates fetching user details and posts from an API using separate Promises. Use Promise.all to combine the results and return an object with user details and posts.

The task is to write a JavaScript function called getUserDetails that simulates fetching user details and posts from an API using separate Promises. Then, use Promise.all to combine the results and return an object with user details and posts.
1. Simulate Fetching User Details and Posts:
Create two separate functions, let’s say fetchUserDetails and fetchUserPosts, that return Promises simulating the fetching of user details and posts from an API.
2. Use Promise.all:
Inside the getUserDetails function, use Promise.all to combine the results of the two Promises (user details and posts).
3. Return Combined Results:
Return an object containing user details and posts.

Here’s an example program:

function fetchUserDetails() {
return new Promise((resolve, reject) => {
// Simulate fetching user details from an API
setTimeout(() => {
const userDetails = { userId: 1, username: ‘john_doe’ };
resolve(userDetails);
}, 1000); // Simulating a delay of 1 second
});
}

function fetchUserPosts(userId) {
return new Promise((resolve, reject) => {
// Simulate fetching user posts from an API using userId
setTimeout(() => {
const userPosts = [
{ postId: 1, title: ‘Post 1’, body: ‘Body of Post 1’ },
{ postId: 2, title: ‘Post 2’, body: ‘Body of Post 2’ }
];
resolve(userPosts);
}, 1500); // Simulating a delay of 1.5 seconds
});
}

async function getUserDetails() {
try {
// Use Promise.all to combine results of fetching user details and posts
const [userDetails, userPosts] = await Promise.all([
fetchUserDetails(),
fetchUserPosts(1) // Assuming userId is 1 for simplicity
]);

// Return an object with user details and posts
return { userDetails, userPosts };
} catch (error) {
console.error(‘Error:’, error.message);
}
}

// Call the function to get user details and posts
getUserDetails().then(result => {
console.log(‘Combined User Details and Posts:’, result);
});

Output

3. Create a function fetchMultipleData that fetches data from multiple remote APIs concurrently using Promise.all. The function should return an array of responses.

The task is to create a JavaScript function called fetchMultipleData that fetches data from multiple remote APIs concurrently using Promise.all. The function should return an array of responses.
1. Simulate Fetching Data:
Create separate functions, each representing fetching data from a remote API. These functions should return Promises simulating the API calls.
2. Use Promise.all:
Inside the fetchMultipleData function, use Promise.all to concurrently fetch data from multiple remote APIs.
3. Return Array of Responses:
Return an array containing the responses from each API call.

Here’s an example program:

// Simulated functions representing fetching data from remote APIs
function fetchDataFromAPI1() {
return new Promise((resolve, reject) => {
// Simulate fetching data from API 1
setTimeout(() => {
const data = { api: ‘API 1’, result: ‘Data from API 1’ };
resolve(data);
}, 1000); // Simulating a delay of 1 second
});
}

function fetchDataFromAPI2() {
return new Promise((resolve, reject) => {
// Simulate fetching data from API 2
setTimeout(() => {
const data = { api: ‘API 2’, result: ‘Data from API 2’ };
resolve(data);
}, 1500); // Simulating a delay of 1.5 seconds
});
}

async function fetchMultipleData() {
try {
// Use Promise.all to concurrently fetch data from multiple APIs
const responses = await Promise.all([
fetchDataFromAPI1(),
fetchDataFromAPI2()
]);

// Return the array of responses
return responses;
} catch (error) {
console.error(‘Error:’, error.message);
}
}

// Call the function to fetch data from multiple APIs
fetchMultipleData().then(results => {
console.log(‘Responses from Multiple APIs:’, results);
});

 

Output

4. Create a function fetchComments that uses the Fetch API to retrieve comments for a post from the JSONPlaceholder API (https://jsonplaceholder.typicode.com/posts/1/comments) and logs the first three comments.

The task is to create a JavaScript function called fetchComments that uses the Fetch API to retrieve comments for a post from the JSONPlaceholder API (https://jsonplaceholder.typicode.com/posts/1/comments) and logs the first three comments.
1. Use Fetch API:
Utilize the Fetch API to request the provided API endpoint that contains comments for a specific post.
2. Retrieve Comments:
Extract the comments from the response.
3. Log First Three Comments:
Log the details of the first three comments to the console.

Here’s an example program:

async function fetchComments() {
try {
// Use Fetch API to retrieve comments for a post
const response = await fetch(‘https://jsonplaceholder.typicode.com/posts/1/comments’);

// Check if the request was successful (status code 200)
if (!response.ok) {
throw new Error(‘Failed to fetch comments’);
}

// Parse the response to get the comments
const comments = await response.json();

// Log the details of the first three comments
for (let i = 0; i < 3 && i < comments.length; i++) {
console.log(`Comment ${i + 1}:`);
console.log(`Name: ${comments[i].name}`);
console.log(`Email: ${comments[i].email}`);
console.log(`Body: ${comments[i].body}`);
console.log(‘—————————‘);
}
} catch (error) {
console.error(‘Error:’, error.message);
}
}

// Call the function to fetch and log comments
fetchComments();

Output

5. Write a JS program using Fetch API to fetch the resource of an API and pick the API link from GitHub.

The task is to use the Fetch API to fetch the resource of an API, and then print the output in different formats.
1. Fetch API Call:
Use the Fetch API to request a specific API link. In this case, you mentioned picking the API link from GitHub.
2. Console Output – JSON Form:
Print the fetched data in JSON format to the console.
3. Console Output – Text Form:
Print the fetched data in text format to the console.
4. Console Output – JSON String:
Convert the fetched data to a JSON string and print it to the console.

Here’s an example program:

<!DOCTYPE html>
<html>
<head>
<title>Fetch API Example</title>
</head>
<body>
<script>
// JavaScript code
const apiLink = ‘https://jsonplaceholder.typicode.com/todos/1’; // Example API link from JSONPlaceholder

// Function to fetch data using Fetch API
async function fetchData() {
try {
const response = await fetch(apiLink);
const data = await response.json();

// Print the output in different formats to the console
console.log(‘Output in JSON Form:’, data);
console.log(‘Output in Text Form:’, JSON.stringify(data, null, 2)); // Convert to JSON string with indentation
console.log(‘Output in Console using JSON:’, data);
} catch (error) {
console.error(‘Error:’, error.message);
}
}

// Call the function to fetch data
fetchData();
</script>
</body>
</html>

Output

6. Write a function fetchTodos that uses the Fetch API to retrieve todos from the JSONPlaceholder API (https://jsonplaceholder.typicode.com/todos) and logs the number of completed and incomplete todos.

The task is to create a JavaScript function called fetchTodos that uses the Fetch API to retrieve todos from the JSONPlaceholder API (https://jsonplaceholder.typicode.com/todos) and logs the number of completed and incomplete todos.
1. Use Fetch API:
Utilize the Fetch API to request the provided API endpoint that contains todos.
2. Retrieve Todos:
Extract the todos from the response.
3. Count Completed and Incomplete Todos:
Iterate through the todos and count the number of completed and incomplete todos.
4. Log the Counts:
Log the counts of completed and incomplete todos to the console.

Here’s an example program:

async function fetchTodos() {
try {
// Use Fetch API to retrieve todos
const response = await fetch(‘https://jsonplaceholder.typicode.com/todos’);

// Check if the request was successful (status code 200)
if (!response.ok) {
throw new Error(‘Failed to fetch todos’);
}

// Parse the response to get the todos
const todos = await response.json();

// Count completed and incomplete todos
let completedCount = 0;
let incompleteCount = 0;

todos.forEach(todo => {
if (todo.completed) {
completedCount++;
} else {
incompleteCount++;
}
});

// Log the counts
console.log(‘Number of Completed Todos:’, completedCount);
console.log(‘Number of Incomplete Todos:’, incompleteCount);
} catch (error) {
console.error(‘Error:’, error.message);
}
}

// Call the function to fetch and log todos
fetchTodos();

Output

Frequently Asked Questions

Still have a question?

Let's talk

The Fetch API provides a modern interface for making HTTP requests, allowing developers to retrieve and send data to servers. Learn more in our JavaScript fetch API free course video.

Use the fetch() function with the URL of the resource.
Example:

fetch(‘https://api.example.com/data’) 

  .then(response => response.json()) 

  .then(data => console.log(data)); 

Explore this in the JS fetch API with free video tutorial.

Use a catch() block to handle network errors or invalid responses.
Example:

fetch(‘https://api.example.com/data’) 

  .then(response => { 

    if (!response.ok) { 

      throw new Error(‘Network response was not ok’); 

    } 

    return response.json(); 

  }) 

  .catch(error => console.error(‘Error:’, error)); 

Discover this step-by-step in the Free JavaScript fetch API tutorial for beginners.

Yes, include a method property in the options object and set the body for the request.
Example:

fetch(‘https://api.example.com/data’, { 

  method: ‘POST’, 

  headers: { 

    ‘Content-Type’: ‘application/json’ 

  }, 

  body: JSON.stringify({ name: ‘John’, age: 30 }) 

}).then(response => response.json()); 

Watch practical examples in the JavaScript fetch API with free tutorial.

  • Fetch API is promise-based, making it easier to work with than the callback-based XMLHttpRequest.
  • Fetch has a cleaner and more modern syntax.
    Learn the advantages of Fetch in the JavaScript fetch API free course video.

Use the headers property in the options object.
Example:

fetch(‘https://api.example.com/data’, { 

  method: ‘GET’, 

  headers: { 

    ‘Authorization’: ‘Bearer token123’ 

  } 

}); 

Find this explained in the JS fetch API with free video tutorial.

Yes, use methods like response.json() for JSON, response.text() for plain text, and response.blob() for binary data. Discover more in the Free JavaScript fetch API tutorial for beginners.

  • fetch: A built-in API in browsers.
  • axios: A third-party library with additional features like automatic JSON conversion, request cancellation, and interceptors.
    Learn more about these tools in the JavaScript fetch API with free tutorial.

Fetch does not natively support timeout, but you can implement it using AbortController.
Example:

const controller = new AbortController(); 

const timeout = setTimeout(() => controller.abort(), 5000); 

fetch(‘https://api.example.com/data’, { signal: controller.signal }); 

Explore this in the JavaScript fetch API free course video.

Yes, use Promise.all to handle multiple requests simultaneously.
Example:

Promise.all([fetch(‘/data1’), fetch(‘/data2’)]) 

  .then(responses => Promise.all(responses.map(res => res.json()))) 

  .then(data => console.log(data)); 

Learn how to implement this in the JS fetch API with free video tutorial.