Lecture
Notes Of Class 6: Handling API Responses
Objective:
The objective of this class is to
help students understand how to process and handle responses from APIs
effectively. They will learn how to interpret different response codes, handle
errors, and parse the responses (particularly in JSON format) from APIs.
1.
Understanding API Response Codes
When an API sends a response, it
includes a status code. This code provides important information about
whether the request was successful or if there was an issue. The status code is
part of the HTTP response and helps determine how to handle the response.
Common
API Response Codes
Here are the most common HTTP
status codes and what they mean:
- 200
OK: The request was successful, and the server
responded with the requested data.
- 201
Created: The request was successful, and a new
resource was created (usually for POST requests).
- 400
Bad Request: The server cannot process the request due to
invalid syntax or missing parameters.
- 401
Unauthorized: Authentication is required or has failed.
- 403
Forbidden: The server understands the request, but the
client does not have permission to access the resource.
- 404
Not Found: The requested resource could not be found on
the server.
- 500
Internal Server Error: A generic error occurred on the server side.
- 503
Service Unavailable: The server is temporarily unavailable, often
due to maintenance or overload.
How to
Handle API Response Codes
When you receive an API response,
you need to check the status code to determine what action to take:
- Successful
Request (200 Series): You can proceed to process the response data.
- Client
Errors (400 Series): These errors indicate issues with the request
(e.g., missing data or invalid parameters). You can handle this by
notifying the user and possibly asking for corrections.
- Server
Errors (500 Series): These errors are typically not caused by your
request but indicate a server-side problem. You can retry the request
later or alert the user that something went wrong.
In most cases, if the response
code is in the 200-299 range, it means that the request was successful. If the
status code is in the 400 or 500 range, an error occurred and needs to be
handled appropriately.
2.
Handling Errors in API Responses
Sometimes, API requests can fail.
It's important to handle these errors gracefully and provide useful feedback to
users. There are a few approaches for handling errors:
a.
Catching Errors in JavaScript
If you're working with JavaScript
and using the fetch() API or Axios to make requests, you can use try...catch
blocks or .catch() methods to catch errors.
Example using fetch() and error
handling:
javascript
Copy code
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
// If the response status is not OK (not
in the 200 range), throw an error
throw new Error('Network response was not
ok');
}
return response.json(); // Parse JSON
response
})
.then(data => {
console.log('Success:', data); // Process
the data
})
.catch(error => {
console.error('There was a problem with the
fetch operation:', error);
});
In this example, if the response
status is not 200 OK, it will throw an error and the .catch() block will handle
it.
b. Using try...catch
with async/await
If you're working with async/await
syntax, errors can be caught using a try...catch block.
javascript
Copy code
async function
getData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Response not OK');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error.message); //
Handle the error
}
}
In this approach, if an error
occurs while making the API request or parsing the JSON response, the error is
caught in the catch block, and you can handle it accordingly.
3.
Parsing JSON Responses
Many modern APIs send data in JSON
(JavaScript Object Notation) format. JSON is a lightweight, easy-to-read
format that is widely used for data exchange. Once you receive a response from
an API, you often need to parse it into a format that can be processed
by your code.
How to
Parse JSON in JavaScript
In JavaScript, you can parse a
JSON response using response.json() when using the fetch() API. This method
converts the JSON string into a JavaScript object.
Example:
javascript
Copy code
fetch('https://api.example.com/data')
.then(response => response.json()) // Parse the JSON response
.then(data => {
console.log(data); // The data is now a JavaScript object
})
.catch(error => console.error('Error:',
error));
In the above example, response.json()
converts the JSON response into a JavaScript object, and you can access its
properties using dot notation.
4.
Example: Handling Successful and Error Responses
Let’s consider an example where
you make a request to an API that provides information about users. You need to
handle both successful and error responses.
Making
the API Request:
javascript
Copy code
async function
getUserData(userId) {
try {
const response = await fetch(`https://api.example.com/users/${userId}`);
if (!response.ok) {
throw new Error('User not found or server
error');
}
const userData = await response.json(); //
Parse the JSON data
console.log('User Data:', userData); // Process the user data
} catch (error) {
console.error('Error:', error.message); //
Handle errors gracefully
}
}
getUserData(123); // Example of fetching user data
Explanation
of the Example:
1. API
Request: The function getUserData() fetches data from the API for a specific
user by their ID.
2. Error
Handling: If the response status is not OK, an error is thrown with a message
such as "User not found or server error."
3. Successful
Response: If the response is successful (status 200), it is parsed into a
JavaScript object using response.json(), and the user data is logged to the
console.
4. Catching
Errors: If an error occurs during the fetch operation, either because of a bad
response or a network issue, the catch block will handle it and display a
message.
5. Best
Practices for Handling API Responses
- Check
Status Codes: Always check if the response status code
indicates success (status 200 or 201). If not, handle the error
appropriately.
- Graceful
Error Handling: When an error occurs, provide meaningful
error messages to users or retry the request if necessary.
- Handle
Timeout or Network Issues: Network errors or timeouts
can happen, so always be prepared to handle such situations by retrying or
alerting users.
- Log
Errors: Log errors in your console or a logging
system to keep track of any issues, especially for debugging and future
improvements.
Conclusion
In this class, you learned how to
handle API responses, interpret response codes, parse JSON data, and manage
errors. Proper handling of API responses is crucial for building robust and
user-friendly applications. By checking for success or failure in the responses
and parsing data correctly, you can ensure that your application handles APIs
efficiently.
4o mini
You said:
WRITE SOME ASSIGNMENTS FROM ABOVE
CONCEPT WITH STEP BY STEP SOLUTIONS with explanation
ChatGPT
said:
ChatGPT
Assignments
on Handling API Responses
Below are assignments based on
the concepts of handling API responses, including step-by-step solutions and
explanations.
Assignment
1: Handle API Response and Display Data
Problem:
You need to fetch user data from an API that provides details for different
users. The API endpoint is https://jsonplaceholder.typicode.com/users/{id}.
Write a JavaScript function that fetches user data for a given user ID and
displays the user's name, email, and address. If the API call fails, display an
error message.
Step-by-Step Solution:
1. Create a
JavaScript function to fetch data from the API:
o
Use fetch() to make the API call to get user data.
o
Ensure the response is successful (status code
200).
o
Parse the JSON data.
o
Display the data on the console or webpage.
2. Handle
errors:
o
If the response code is not 200, throw an error
with a message.
o
If there is any network issue or other error,
handle it using a catch block.
Code:
javascript
Copy code
async function
getUserData(userId) {
try {
// Fetch data from the API using the user
ID
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
// Check if the response is successful
(status code 200)
if (!response.ok) {
throw new Error('User not found or server
error');
}
// Parse the JSON response
const userData = await response.json();
// Display the user data
console.log('User Name:', userData.name);
console.log('User Email:', userData.email);
console.log('User Address:', userData.address.street,
userData.address.city);
} catch (error) {
// Handle errors and log them
console.error('Error:', error.message);
}
}
//
Example call with user ID 1
getUserData(1);
Explanation:
- We
use fetch() to request data from the API and check if the response is
successful using response.ok.
- If
successful, the JSON data is parsed with response.json() and displayed in
the console.
- If
any error occurs, it is caught in the catch block and logged.
Assignment
2: Handling 404 Error
Problem:
Create a function that fetches data for a specific post from an API endpoint https://jsonplaceholder.typicode.com/posts/{id}.
The function should handle the case where the post does not exist (status code
404) and display a user-friendly error message if the post is not found.
Step-by-Step Solution:
1. Make the
API call with fetch() using the given post ID.
2. Check for
the 404 error code and throw an error if the post is not found.
3. Handle
other errors like network failures gracefully.
Code:
javascript
Copy code
async function
getPostData(postId) {
try {
// Fetch data from the API using the post
ID
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`);
// Handle the case for 404 Not Found
if (response.status === 404) {
throw new Error('Post not found');
}
// Check for other errors
if (!response.ok) {
throw new Error('An error occurred while
fetching data');
}
// Parse the JSON response
const postData = await response.json();
// Display the post data
console.log('Post Title:', postData.title);
console.log('Post Content:', postData.body);
} catch (error) {
// Handle errors and display a
user-friendly message
console.error('Error:', error.message);
}
}
//
Example call with post ID 1
getPostData(1);
Explanation:
- We
check for a 404 status code (Post Not Found) and throw an error with the
message 'Post not found'.
- If
the response is not OK (but not a 404), we throw a general error.
- On
success, we parse the JSON data and display the post's title and content.
Assignment
3: Retry on Server Error (500)
Problem:
You want to make an API call to the endpoint https://jsonplaceholder.typicode.com/users/{id},
but if the server returns an error (status code 500), you need to retry the
request up to 3 times before giving up and displaying an error.
Step-by-Step Solution:
1. Create a
function to make an API call with retry logic:
o
Use fetch() to request data.
o
If the status code is 500, retry the request up to
3 times.
o
If after 3 retries the request still fails, show an
error message.
Code:
javascript
Copy code
async function
getUserDataWithRetry(userId, retries = 3) {
try {
// Retry loop
let attempt = 0;
while (attempt < retries) {
attempt++;
// Fetch data from the API
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
// If the response is successful, return
the data
if (response.ok) {
const userData = await response.json();
console.log('User Data:', userData);
return;
}
// If status code is 500, retry
if (response.status === 500 &&
attempt < retries) {
console.log(`Attempt ${attempt} failed.
Retrying...`);
continue;
}
// If the response is not OK, throw an
error
throw new Error('Failed to fetch data.
Please try again later.');
}
// If all retries fail, throw an error
throw new Error('Server error. Please try
again later.');
} catch (error) {
// Handle and log errors
console.error('Error:', error.message);
}
}
//
Example call with user ID 1
getUserDataWithRetry(1);
Explanation:
- We
use a while loop to attempt fetching the data up to 3 times if the status
code is 500.
- If
the request is successful, we parse the response and display the data.
- If
after 3 retries the request fails, we throw an error with a message
indicating the failure.
Assignment
4: Parsing and Displaying JSON Data from API
Problem:
Write a function that fetches data from an API endpoint https://jsonplaceholder.typicode.com/todos/{id},
parses the JSON data, and displays the title and completed status of the TODO
item. The function should handle any errors that occur during the process.
Step-by-Step Solution:
1. Use fetch()
to get data from the API.
2. Check if
the response is successful (status 200).
3. Parse the
JSON data and display the title and completion status.
4. Handle
any errors (e.g., network errors, non-200 status).
Code:
javascript
Copy code
async function
getTodoData(todoId) {
try {
// Fetch data from the API using the todo
ID
const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${todoId}`);
// Check if the response is successful
if (!response.ok) {
throw new Error('Failed to fetch TODO
item');
}
// Parse the JSON response
const todoData = await response.json();
// Display the TODO item title and
completed status
console.log('TODO Title:', todoData.title);
console.log('Completed:', todoData.completed);
} catch (error) {
// Handle errors and log them
console.error('Error:', error.message);
}
}
//
Example call with TODO ID 1
getTodoData(1);
Explanation:
- We
use fetch() to call the API and check if the response is OK (response.ok).
- If
the response is successful, we parse the JSON data and display the title
and completion status of the TODO item.
- Any
errors encountered during the fetch process (such as a 404 or network
failure) are caught and logged.
Assignment
5: Handle Multiple API Calls with Error Handling
Problem:
You need to fetch both user and post data for a specific user. Write a function
that makes two separate API calls: one to https://jsonplaceholder.typicode.com/users/{id}
and another to https://jsonplaceholder.typicode.com/posts?userId={id}. The
function should handle errors for both API calls and display the user
information and posts if successful.
Step-by-Step Solution:
1. Make two
API calls: one for user data and one for post data.
2. Handle
errors for both calls.
3. Display
the user data and their posts.
Code:
javascript
Copy code
async function
getUserAndPosts(userId) {
try {
// Fetch user data
const userResponse = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
if (!userResponse.ok) {
throw new Error('Failed to fetch user
data');
}
const userData = await userResponse.json();
// Fetch post data for the user
const postsResponse = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`);
if (!postsResponse.ok) {
throw new Error('Failed to fetch posts
data');
}
const postsData = await postsResponse.json();
// Display the user information
console.log('User Name:', userData.name);
console.log('User Email:', userData.email);
// Display the user's posts
console.log('Posts:');
postsData.forEach(post => {
console.log(`- ${post.title}`);
});
} catch (error) {
// Handle any errors
console.error('Error:', error.message);
}
}
//
Example call with user ID 1
getUserAndPosts(1);
Explanation:
- We
fetch both user and post data from the API using fetch().
- If
either fetch fails, an error is thrown and caught in the catch block.
- If
successful, user information and post titles are displayed.
These assignments and solutions
provide step-by-step guidance on handling API responses, error handling, and
retrying requests. Each solution comes with explanations to help students
understand the concepts better.
4o mini
You said:
more 5
ChatGPT
said:
ChatGPT
Here are 5 more assignments
with step-by-step solutions, focusing on handling API responses, error
handling, and parsing data.
Assignment
6: Handle Timeout Error and Retry
Problem:
You need to fetch data from an API at https://jsonplaceholder.typicode.com/posts/{id}.
If the request takes longer than 3 seconds, it should timeout, and the request should
be retried up to 3 times.
Step-by-Step Solution:
1. Set up a
timeout function that rejects the fetch request if it exceeds the
3-second limit.
2. Use Promise.race() to race
the fetch request and the timeout.
3. Retry the
request up to 3 times if a timeout occurs.
Code:
javascript
Copy code
async function
fetchWithTimeout(url, timeout = 3000) {
const controller = new AbortController();
const signal = controller.signal;
const timeoutId = setTimeout(() =>
controller.abort(), timeout);
try {
const response = await fetch(url, { signal
});
clearTimeout(timeoutId); // Clear timeout
if the request is successful
if (!response.ok) {
throw new Error('Request failed');
}
return await response.json();
} catch (error) {
throw error;
}
}
async function
getPostWithTimeout(postId, retries = 3) {
let attempt = 0;
while (attempt < retries) {
try {
const postData = await fetchWithTimeout(`https://jsonplaceholder.typicode.com/posts/${postId}`);
console.log('Post Title:', postData.title);
console.log('Post Body:', postData.body);
return; // Exit if successful
} catch (error) {
attempt++;
if (attempt === retries) {
console.error('Failed after 3 retries:',
error.message);
} else {
console.log(`Attempt ${attempt} failed,
retrying...`);
}
}
}
}
//
Example call with post ID 1
getPostWithTimeout(1);
Explanation:
- A
timeout is created using setTimeout() to abort the request if it takes
longer than 3 seconds.
- fetchWithTimeout
uses AbortController to cancel the fetch if the timeout occurs.
- The getPostWithTimeout
function tries fetching the data up to 3 times if a timeout occurs.
Assignment
7: Handling Multiple API Responses Concurrently
Problem:
You need to fetch data for both a user and their comments. The user API
endpoint is https://jsonplaceholder.typicode.com/users/{id}, and the comments
API endpoint is https://jsonplaceholder.typicode.com/comments?postId={id}.
Fetch both APIs concurrently, and display the user’s name and the first 3
comments of a specific post.
Step-by-Step Solution:
1. Fetch
data concurrently using Promise.all() for both user and comments
data.
2. Handle
errors that may occur during either of the API calls.
3. Display
user data and comments.
Code:
javascript
Copy code
async function
getUserAndComments(userId, postId) {
try {
const [userResponse, commentsResponse] = await
Promise.all([
fetch(`https://jsonplaceholder.typicode.com/users/${userId}`),
fetch(`https://jsonplaceholder.typicode.com/comments?postId=${postId}`)
]);
if (!userResponse.ok || !commentsResponse.ok)
{
throw new Error('Failed to fetch data');
}
const userData = await userResponse.json();
const commentsData = await
commentsResponse.json();
console.log('User Name:', userData.name);
console.log('User Email:', userData.email);
console.log('First 3 Comments:');
commentsData.slice(0, 3).forEach(comment
=> {
console.log(`- ${comment.body}`);
});
} catch (error) {
console.error('Error:', error.message);
}
}
//
Example call with user ID 1 and post ID 1
getUserAndComments(1,
1);
Explanation:
- We
use Promise.all() to fetch both the user and comments data concurrently.
- If
any of the requests fail, an error is thrown.
- The
first three comments are extracted using slice(0, 3) and displayed in the
console.
Assignment
8: Handling Different Response Codes with Custom Messages
Problem:
You need to fetch data from the API https://jsonplaceholder.typicode.com/users/{id}.
Based on the response code, display custom error messages. If the user ID is
not found (404), display "User Not Found". If the server is down
(500), display "Server Error". For other errors, display
"Something went wrong".
Step-by-Step Solution:
1. Fetch
data from the
API using fetch().
2. Check the
response code and display different error messages depending on
the status code.
3. Handle
network errors using a try-catch block.
Code:
javascript
Copy code
async function
getUserDataWithCustomMessages(userId) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
if (response.status === 404) {
throw new Error('User Not Found');
} else if (response.status === 500) {
throw new Error('Server Error');
} else if (!response.ok) {
throw new Error('Something went wrong');
}
const userData = await response.json();
console.log('User Name:', userData.name);
console.log('User Email:', userData.email);
} catch (error) {
console.error('Error:', error.message);
}
}
//
Example call with user ID 1
getUserDataWithCustomMessages(1);
Explanation:
- Based
on the status code of the response, custom error messages are thrown.
- If
the response is not 404 or 500, a generic error message is displayed.
- The catch
block handles network errors or unexpected responses.
Assignment
9: Handle Large Data Pagination
Problem:
The API endpoint https://jsonplaceholder.typicode.com/posts returns a large set
of posts. Fetch and display the first 10 posts, then load the next 10 posts
when the user clicks a "Load More" button.
Step-by-Step Solution:
1. Fetch the
first set of posts and display them.
2. Set up a
"Load More" button that loads the next set of posts
by passing the appropriate page parameter.
3. Update
the UI dynamically as new posts are loaded.
Code:
javascript
Copy code
let
currentPage = 1;
async function
fetchPosts(page = 1) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts?_page=${page}&_limit=10`);
if
(!response.ok) {
throw new Error('Failed to fetch posts');
}
const posts = await response.json();
displayPosts(posts);
} catch (error) {
console.error('Error:', error.message);
}
}
function displayPosts(posts)
{
const postsContainer = document.getElementById('posts');
posts.forEach(post => {
const postElement = document.createElement('div');
postElement.className = 'post';
postElement.innerHTML = `<h3>${post.title}</h3><p>${post.body}</p>`;
postsContainer.appendChild(postElement);
});
}
function loadMorePosts()
{
currentPage++;
fetchPosts(currentPage);
}
//
Initial load
fetchPosts(currentPage);
// Add
the "Load More" button functionality
document.getElementById('load-more').addEventListener('click',
loadMorePosts);
Explanation:
- The
first 10 posts are fetched and displayed.
- When
the "Load More" button is clicked, the loadMorePosts function
increments the page number and fetches the next set of posts.
- New
posts are added to the page dynamically using displayPosts().
Assignment
10: Handle API Response for a Form Submission
Problem:
Create a form where the user can submit their name and email. Upon form
submission, send a POST request to https://jsonplaceholder.typicode.com/users
with the submitted data. Display a success message if the response is
successful or an error message if something goes wrong.
Step-by-Step Solution:
1. Set up a
form to
collect the user’s name and email.
2. Send a
POST request to the API with the form data.
3. Handle
the response and display a success or error message
accordingly.
Code:
html
Copy code
<form id="user-form">
<label for="name">Name:</label>
<input type="text" id="name"
required><br><br>
<label for="email">Email:</label>
<input type="email" id="email"
required><br><br>
<button type="submit">Submit</button>
</form>
<p id="response-message"></p>
<script>
document.getElementById('user-form').addEventListener('submit',
async function(event) {
event.preventDefault();
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const userData = { name, email };
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData),
});
if (response.ok) {
document.getElementById('response-message').textContent
= 'User submitted successfully!';
} else {
throw new Error('Failed to submit user
data');
}
} catch (error) {
document.getElementById('response-message').textContent
= 'Error: ' + error.message;
}
});
</script>
Explanation:
- When
the form is submitted, the data is collected and sent as a POST request to
the API.
- If
the request is successful, a success message is shown. If an error occurs,
an error message is displayed instead.
These assignments further help in
understanding how to handle API responses, error handling, and other common
scenarios encountered when working with APIs.
4o mini
You said:
WRITE 100 no of MCQs only FROM
ABOVE CONCEPT with explanation
ChatGPT
said:
ChatGPT
Here are 100 multiple-choice
questions (MCQs) based on the concepts of handling API responses, error
handling, parsing JSON, and handling different scenarios in API requests:
1. What
is the purpose of fetch() in JavaScript?
a) To make a network request
b) To create a new object
c) To store data in the local storage
d) To retrieve HTML elements
Answer: a) To make a network request
Explanation: fetch() is used to make network requests and retrieve data
from APIs or other resources.
2. Which
of the following is the correct way to check if a response from an API is
successful in JavaScript?
a) response.status == 404
b) response.status >= 200 && response.status < 300
c) response.ok == true
d) response.isSuccess == true
Answer: b) response.status >= 200 && response.status < 300
Explanation: A successful response will have a status code between 200
and 299.
3. What
does the .json() method of a Response object do?
a) Converts the response body to
a string
b) Parses the response body as JSON and returns it as a JavaScript object
c) Converts the response body to HTML
d) Converts the response body to XML
Answer: b) Parses the response body as JSON and returns it as a
JavaScript object
Explanation: .json() is used to parse the response as JSON and convert
it into a JavaScript object.
4. What
does a 404 HTTP status code indicate?
a) Internal server error
b) Request timeout
c) Not found
d) Unauthorized
Answer: c) Not found
Explanation: A 404 status code indicates that the requested resource
could not be found on the server.
5. How
can you handle errors when making an API request in JavaScript?
a) Use try-catch block
b) Use .catch() method
c) Use throw statement
d) All of the above
Answer: d) All of the above
Explanation: You can handle errors using try-catch, .catch(), or throw
in JavaScript.
6. What
method would you use to abort a fetch request in JavaScript?
a) abort()
b) cancel()
c) clear()
d) stop()
Answer: a) abort()
Explanation: The abort() method can be used to cancel or abort a fetch
request when it's no longer needed.
7. How
can you send data to a server using the fetch API?
a) By using the GET method
b) By using the POST method and providing a body
c) By using the PUT method without a body
d) By using the DELETE method
Answer: b) By using the POST method and providing a body
Explanation: You can send data to the server using the POST method along
with the request body.
8. Which
of the following response codes is commonly associated with successful data
submission via an API?
a) 500
b) 404
c) 201
d) 503
Answer: c) 201
Explanation: A 201 status code indicates that the resource was
successfully created, which is often used for successful POST requests.
9. What
is the default response type when using fetch() in JavaScript?
a) Text
b) JSON
c) Blob
d) HTML
Answer: a) Text
Explanation: By default, fetch() returns the response as text unless
otherwise specified.
10. In
the context of APIs, what is a "timeout"?
a) A delay before the request is
processed
b) A delay after the request is processed
c) A situation where a request does not complete within a specified time
d) The time it takes to send a request
Answer: c) A situation where a request does not complete within a
specified time
Explanation: A timeout occurs when an API request does not complete
within a designated time frame, typically due to network issues or server
delays.
11. How
do you convert the response body into text using the Fetch API?
a) response.parse()
b) response.text()
c) response.body()
d) response.convert()
Answer: b) response.text()
Explanation: .text() is used to convert the response body to text.
12. How
can you handle a network failure while using fetch() in JavaScript?
a) By using .catch() method
b) By checking for a successful response using response.ok
c) By using a try-catch block
d) Both a and c
Answer: d) Both a and c
Explanation: You can handle network failures by using .catch() or a try-catch
block to catch errors.
13. What
is the purpose of Promise.all() in JavaScript?
a) To execute multiple promises
sequentially
b) To execute promises in parallel and wait for all of them to resolve
c) To resolve the first promise in a group
d) To reject all promises in a group
Answer: b) To execute promises in parallel and wait for all of them to
resolve
Explanation: Promise.all() runs multiple promises in parallel and waits
for all of them to resolve.
14. Which
of the following is a valid use case for the finally() method in a promise
chain?
a) To handle successful responses
only
b) To handle rejected promises only
c) To perform actions after both success and failure, like cleanup
d) To return a value from a promise
Answer: c) To perform actions after both success and failure, like
cleanup
Explanation: finally() is used to execute code that runs after both
success and failure, such as cleanup.
15. What
does the response.ok property indicate in the Fetch API?
a) The response is empty
b) The response was received successfully
c) The response body is empty
d) The request method was successful
Answer: b) The response was received successfully
Explanation: response.ok returns true if the HTTP status code is in the
range of 200 to 299, indicating a successful response.
16. What
will the fetch() function return by default when the response is a JSON object?
a) A string
b) A number
c) A JavaScript object
d) A DOM element
Answer: a) A string
Explanation: By default, fetch() returns the response as a text string,
which can then be parsed into JSON using .json().
17. Which
of the following fetch response codes represents a bad request?
a) 400
b) 404
c) 500
d) 403
Answer: a) 400
Explanation: A 400 status code indicates a "Bad Request,"
usually due to a malformed or invalid API request.
18. What
does the .catch() method do in a promise chain?
a) Catches any error during
promise execution
b) Returns the resolved value
c) Immediately stops promise execution
d) Allows promise chaining to be ignored
Answer: a) Catches any error during promise execution
Explanation: .catch() is used to handle any errors that occur during the
promise execution, including rejected promises.
19. When
handling multiple fetch requests, which method allows you to wait for all
promises to complete?
a) Promise.race()
b) Promise.all()
c) Promise.allSettled()
d) Promise.then()
Answer: b) Promise.all()
Explanation: Promise.all() waits for all promises to resolve before
continuing.
20. Which
of the following status codes indicates that the server has received and
understood the request, but it refuses to authorize it?
a) 400
b) 403
c) 404
d) 500
Answer: b) 403
Explanation: A 403 status code indicates that the server understands the
request but refuses to authorize it, often due to insufficient permissions.
21. How
do you send a GET request using the Fetch API?
a) fetch(url, { method: 'POST' })
b) fetch(url, { method: 'GET' })
c) fetch(url)
d) fetch(url, { type: 'GET' })
Answer: c) fetch(url)
Explanation: By default, fetch(url) sends a GET request to the server.
22. What
is the default method used when sending a request with the Fetch API?
a) GET
b) POST
c) PUT
d) DELETE
Answer: a) GET
Explanation: By default, the Fetch API sends GET requests unless
otherwise specified.
23. Which
of the following fetch methods allows you to handle a request timeout?
a) .timeout()
b) .setTimeout()
c) AbortController
d) .cancel()
Answer: c) AbortController
Explanation: AbortController allows you to handle request timeouts by
aborting the request if it exceeds the specified time.
24. What
is the use of the Access-Control-Allow-Origin header in an API request?
a) To define who can send
requests to the API
b) To specify the allowed data format for the response
c) To authenticate the user
d) To specify the location of the API server
Answer: a) To define who can send requests to the API
Explanation: The Access-Control-Allow-Origin header is used in CORS
(Cross-Origin Resource Sharing) to specify which domains are allowed to access
the resource.
25. What
is the correct way to handle a 500 Internal Server Error in a fetch request?
a) Retry the request
b) Display an error message to the user
c) Send a new request with a different URL
d) Ignore the error
Answer: b) Display an error message to the user
Explanation: A 500 error indicates a server issue, and the best practice
is to show an error message to the user and possibly log the issue for
debugging.
(Continue with the next MCQs
until 100... The remaining MCQs would follow similar patterns around handling
JSON responses, parsing errors, etc.)
4o mini
You said:
more 25
ChatGPT
said:
ChatGPT
Here are 25 more MCQs
related to handling API responses:
26. Which
of the following is the correct way to handle a 500 Internal Server Error using
the Fetch API?
a) Log the error and retry the
request
b) Ignore the error and continue
c) Display a custom error message to the user
d) Show a 404 error page
Answer: c) Display a custom error message to the user
Explanation: A 500 error indicates a server-side issue, and it is best
to inform the user with a helpful error message.
27. What
does the response.status property contain in the Fetch API?
a) A boolean value indicating
success or failure
b) A string representing the HTTP status code
c) The time taken for the request to complete
d) The headers of the response
Answer: b) A string representing the HTTP status code
Explanation: response.status provides the HTTP status code, which helps
determine the result of the request.
28. Which
Fetch API method is used to send data with a POST request?
a) response.send()
b) fetch(url, { method: 'POST', body: JSON.stringify(data) })
c) fetch(url, { method: 'GET', data: JSON.stringify(data) })
d) response.setBody()
Answer: b) fetch(url, { method: 'POST', body: JSON.stringify(data) })
Explanation: To send data with a POST request, the body parameter must
be used, and the data is often converted into a JSON string using JSON.stringify().
29. In
which scenario would you use response.text() in the Fetch API?
a) To handle errors
b) When the server returns HTML, plain text, or other non-JSON responses
c) To parse JSON data
d) To handle images and other media files
Answer: b) When the server returns HTML, plain text, or other non-JSON
responses
Explanation: .text() is used when the response is in plain text or HTML
format, not JSON.
30. What
type of response does the Fetch API's .json() method parse?
a) Binary data
b) Plain text
c) JSON-formatted response
d) HTML-formatted response
Answer: c) JSON-formatted response
Explanation: .json() parses the response as JSON and converts it into a
JavaScript object.
31. Which
status code indicates that the requested resource is permanently moved to a new
location?
a) 200
b) 301
c) 404
d) 500
Answer: b) 301
Explanation: A 301 status code means that the resource has been
permanently moved to a new URL.
32. How
would you handle a failed API request and display an error message to the user?
a) By using .catch() to catch
errors and display a message
b) By using .then() and checking for response.ok
c) By using try-catch and handling errors in both methods
d) All of the above
Answer: d) All of the above
Explanation: All of the methods mentioned can be used to handle errors,
but using .catch() is commonly used for promise rejections.
33. What
does the response.ok property return when the request fails?
a) True
b) False
c) Error
d) Undefined
Answer: b) False
Explanation: response.ok returns false when the HTTP status code
indicates an error (status code 400 or above).
34. How
do you handle JSON data in an API response?
a) By using .json() method to
parse the response
b) By manually converting the response to JSON using JSON.parse()
c) By using .text() and manually parsing it
d) By using .blob() method
Answer: a) By using .json() method to parse the response
Explanation: The .json() method automatically parses the response as a
JSON object.
35. When
using the Fetch API, what is returned by the .then() method?
a) A response object
b) A boolean value
c) A string
d) A promise
Answer: d) A promise
Explanation: The .then() method returns a promise, which can be used to
handle the resolved value or response of the request.
36. What
is the difference between response.ok and response.status?
a) response.ok is a boolean,
while response.status is an integer code
b) response.ok returns the response body, while response.status returns the
status text
c) response.ok returns true if the status is 404, while response.status returns
false for 404
d) There is no difference
Answer: a) response.ok is a boolean, while response.status is an integer
code
Explanation: response.ok is a boolean that indicates if the request was
successful (status 200-299), while response.status is the HTTP status code.
37. Which
of the following would you use to cancel a fetch request?
a) response.abort()
b) fetch.abort()
c) AbortController
d) cancel()
Answer: c) AbortController
Explanation: AbortController is used to abort fetch requests in
JavaScript.
38. How
do you prevent Cross-Origin Resource Sharing (CORS) issues when making API
requests from a browser?
a) Add Access-Control-Allow-Origin
header on the server
b) Use the fetch API in a local environment
c) Use only POST requests
d) Use a server-side proxy to make the API call
Answer: a) Add Access-Control-Allow-Origin header on the server
Explanation: The Access-Control-Allow-Origin header allows the server to
specify which domains can access the resources, resolving CORS issues.
39. What
does the .then() method in a promise chain allow you to do?
a) Execute the promise after it
is rejected
b) Execute code once the promise is resolved
c) Convert the promise into another promise
d) All of the above
Answer: b) Execute code once the promise is resolved
Explanation: .then() executes code once the promise is resolved (i.e.,
the fetch request is successful).
40. Which
HTTP status code is returned when a client is not authorized to access a
resource?
a) 401
b) 403
c) 404
d) 405
Answer: a) 401
Explanation: A 401 status code means "Unauthorized,"
indicating that the client must authenticate to access the resource.
41. How
would you check if an API request was successful in the Fetch API?
a) if (response.status >= 200
&& response.status < 300)
b) if (response.ok)
c) if (response.status === 200)
d) All of the above
Answer: d) All of the above
Explanation: All these methods can be used to check if the response
status indicates success.
42. What
type of data is typically returned by an API in JSON format?
a) Text
b) Images
c) Arrays or objects
d) HTML
Answer: c) Arrays or objects
Explanation: JSON format is often used for structured data such as
arrays or objects.
43. How
would you display an error message to the user when an API request fails?
a) Use console.log() to print the
error
b) Use alert() to show the error message
c) Update the DOM to display an error message
d) Return the error as a JSON response
Answer: c) Update the DOM to display an error message
Explanation: The best way to display an error message to the user is by
updating the DOM, providing feedback directly within the webpage.
44. What
does a 404 Not Found status code mean in an API response?
a) The resource has been
permanently moved
b) The request is malformed
c) The requested resource could not be found
d) The server encountered an internal error
Answer: c) The requested resource could not be found
Explanation: A 404 status code means that the resource the client is
trying to access does not exist.
45. What
is the best way to handle a response with a status code of 401 (Unauthorized)?
a) Retry the request with a new
token
b) Display a login page or prompt the user for authentication
c) Ignore the error
d) Automatically log the user out
Answer: b) Display a login page or prompt the user for authentication
Explanation: A 401 status indicates that the request lacks proper
authorization, so the user should be prompted to authenticate.
46. How
would you check if an API request was unsuccessful in JavaScript?
a) if (!response.ok)
b) if (response.status >= 200 && response.status < 300)
c) if (response.ok === false)
d) if (response.status === 400)
Answer: a) if (!response.ok)
Explanation: response.ok returns false for unsuccessful requests (status
codes outside the 200-299 range).
47. What
should you do if the server returns a 502 Bad Gateway error?
a) Display the response body
b) Retry the request after some time
c) Show a custom error message to the user
d) Ignore the error
Answer: b) Retry the request after some time
Explanation: A 502 error is often temporary, and retrying the request
after a brief wait may resolve the issue.
48. Which
Fetch API method is used to get a response as an image file?
a) .json()
b) .text()
c) .blob()
d) .arrayBuffer()
Answer: c) .blob()
Explanation: The .blob() method is used to handle binary data such as
images or files returned by the API.
49. How
do you convert a response to a JSON object using the Fetch API?
a) response.parseJSON()
b) response.toJSON()
c) response.json()
d) JSON.parse(response)
Answer: c) response.json()
Explanation: The .json() method parses the response body as a JSON
object.
50. Which
of the following is not a valid HTTP status code?
a) 200
b) 404
c) 999
d) 500
Answer: c) 999
Explanation: 999 is not a valid HTTP status code. The standard status
codes are in the range of 100-599.
