Fetch API
The Fetch API in JavaScript is a modern interface for making network requests (such as HTTP requests) similar to XMLHttpRequest. It provides a more powerful and flexible way to handle network requests and responses. The Fetch API is designed to be simple to use and is based on Promises, making it more convenient for handling asynchronous operations.
The fetch() Method
The fetch() method is a modern API for making network requests. It takes a URL as its parameter and returns a Promise that resolves to the Response object representing the response to the request.
Syntax:
fetch(url, options);
– url: The URL of the resource you want to fetch.
– options (Optional): An object containing settings for the request, such as method, headers, body, mode, credentials, etc.
Return Value (Promise):
The fetch() method returns a Promise that resolves to a Response object. This Response object represents the response to the request, including status, headers, and the response body.
Example:
let fetchPromise = fetch(url);
Response Object:
The Response object provides various methods and properties to interact with the response data.
– Status Property: Returns the HTTP status code of the response.
– Syntax: response.status
ok Property: Returns a boolean indicating whether the response was successful (status in the range 200-299).
– Syntax: response.ok
– text() Method: Returns the response body as text.
– Syntax: response.text()
Example :
Example :
1. The fetch() method is used to initiate a GET request to the specified URL.
2. The response from the server is returned as a Promise, stored in the variable fetchPromise.
3.The first .then() block checks if the response was successful using the ok property and throws an error if not.
4. The second .then() block parses the response body as JSON.
5. The resulting JSON data is logged to the console.
Output
Course Video
Examples for Practice
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