JavaScript Fetch API
JavaScript Fetch API Interview with follow-up questions
Interview Question Index
- Question 1: What is the Fetch API in JavaScript?
- Follow up 1 : How does it differ from AJAX?
- Follow up 2 : Can you explain how to use it with an example?
- Follow up 3 : What are the advantages of using Fetch API over XMLHttpRequest?
- Follow up 4 : How do you handle errors in Fetch API?
- Question 2: How can you make a POST request using the Fetch API?
- Follow up 1 : What should be included in the headers of a POST request?
- Follow up 2 : How do you send JSON data in the body of a POST request?
- Follow up 3 : How do you handle the response of a POST request?
- Question 3: What is the purpose of the 'options' object in a fetch request?
- Follow up 1 : What are some common properties you can include in the 'options' object?
- Follow up 2 : How do you specify the request method in the 'options' object?
- Follow up 3 : How do you include headers in the 'options' object?
- Question 4: How do you handle responses that are not a 200 OK status?
- Follow up 1 : What does the 'ok' property of a Response object indicate?
- Follow up 2 : How do you access the status code of a response?
- Follow up 3 : What is a common way to handle 404 Not Found responses?
- Question 5: Can you explain how to use the Fetch API to make a request to a third-party API?
- Follow up 1 : How do you include an API key in your request?
- Follow up 2 : How do you handle CORS issues?
- Follow up 3 : How do you parse the JSON response from the API?
Question 1: What is the Fetch API in JavaScript?
Answer:
The Fetch API is a modern JavaScript API that provides a way to make HTTP requests and handle responses. It is built into the JavaScript language and is designed to be more flexible and powerful than the older XMLHttpRequest object.
Follow up 1: How does it differ from AJAX?
Answer:
The Fetch API is a newer and more modern alternative to AJAX (Asynchronous JavaScript and XML). While AJAX uses the XMLHttpRequest object to make HTTP requests, the Fetch API uses the fetch() function. The Fetch API provides a simpler and more intuitive syntax, supports promises for handling asynchronous operations, and allows for more control over the request and response.
Follow up 2: Can you explain how to use it with an example?
Answer:
Sure! Here's an example of how to use the Fetch API to make a GET request to an API and handle the response:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// Handle the data
console.log(data);
})
.catch(error => {
// Handle any errors
console.error(error);
});
Follow up 3: What are the advantages of using Fetch API over XMLHttpRequest?
Answer:
There are several advantages of using the Fetch API over XMLHttpRequest:
- Simpler and more intuitive syntax: The Fetch API provides a more modern and cleaner syntax for making HTTP requests.
- Promises-based: The Fetch API uses promises, which makes it easier to handle asynchronous operations and avoid callback hell.
- Better control over requests and responses: The Fetch API allows for more control over the request and response, such as setting headers, handling different types of data, and handling errors.
- Built-in support for JSON: The Fetch API automatically parses JSON responses, making it easier to work with JSON data.
- Better browser support: The Fetch API is supported by all modern browsers, while XMLHttpRequest has some limitations in older browsers.
Follow up 4: How do you handle errors in Fetch API?
Answer:
To handle errors in the Fetch API, you can use the catch() method on the promise returned by the fetch() function. Here's an example:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
// Handle the data
console.log(data);
})
.catch(error => {
// Handle the error
console.error(error);
});
Question 2: How can you make a POST request using the Fetch API?
Answer:
To make a POST request using the Fetch API, you can use the fetch()
function and pass the URL of the endpoint you want to send the request to, along with an object that contains the request options. Here's an example:
fetch('https://api.example.com/endpoint', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
// Handle the response data
})
.catch(error => {
// Handle any errors
});
Follow up 1: What should be included in the headers of a POST request?
Answer:
In the headers of a POST request, you should include the 'Content-Type' header to specify the format of the data being sent in the request body. For example, if you are sending JSON data, you should include the 'Content-Type' header with the value 'application/json'. Here's an example:
fetch('https://api.example.com/endpoint', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
// Handle the response data
})
.catch(error => {
// Handle any errors
});
Follow up 2: How do you send JSON data in the body of a POST request?
Answer:
To send JSON data in the body of a POST request, you need to convert the data to a JSON string using JSON.stringify()
and set it as the value of the body
option in the request. Here's an example:
const data = {
name: 'John Doe',
age: 30
};
fetch('https://api.example.com/endpoint', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
// Handle the response data
})
.catch(error => {
// Handle any errors
});
Follow up 3: How do you handle the response of a POST request?
Answer:
To handle the response of a POST request, you can use the then()
method on the response object returned by the fetch()
function. You can chain multiple then()
methods to handle the response data in different ways. For example, you can use the json()
method to parse the response data as JSON. Here's an example:
fetch('https://api.example.com/endpoint', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
// Handle the response data
})
.catch(error => {
// Handle any errors
});
Question 3: What is the purpose of the 'options' object in a fetch request?
Answer:
The 'options' object in a fetch request is used to provide additional configuration for the request. It allows you to specify various properties such as the request method, headers, body, and more.
Follow up 1: What are some common properties you can include in the 'options' object?
Answer:
Some common properties that can be included in the 'options' object are:
- 'method': Specifies the request method (e.g., GET, POST, PUT, DELETE).
- 'headers': Specifies the headers to be included in the request.
- 'body': Specifies the body content of the request.
- 'mode': Specifies the mode of the request (e.g., 'cors', 'no-cors', 'same-origin').
- 'cache': Specifies the cache mode of the request (e.g., 'default', 'no-store', 'reload', 'no-cache').
- 'credentials': Specifies whether to include cookies in the request (e.g., 'same-origin', 'include', 'omit').
- 'redirect': Specifies how redirects are handled (e.g., 'follow', 'error', 'manual').
- 'referrer': Specifies the referrer of the request (e.g., 'no-referrer', 'client').
Follow up 2: How do you specify the request method in the 'options' object?
Answer:
To specify the request method in the 'options' object, you can use the 'method' property. For example:
fetch(url, {
method: 'POST'
})
Follow up 3: How do you include headers in the 'options' object?
Answer:
To include headers in the 'options' object, you can use the 'headers' property. The 'headers' property should be an object where each key-value pair represents a header name and its value. For example:
fetch(url, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token'
}
})
Question 4: How do you handle responses that are not a 200 OK status?
Answer:
When handling responses that are not a 200 OK status, you can check the 'ok' property of the Response object. If the 'ok' property is true, it means the response was successful (status code 200). If the 'ok' property is false, it means the response was not successful (status code other than 200). You can then handle the response accordingly, for example by displaying an error message to the user or taking some other action.
Follow up 1: What does the 'ok' property of a Response object indicate?
Answer:
The 'ok' property of a Response object indicates whether the response was successful or not. If the 'ok' property is true, it means the response was successful (status code 200). If the 'ok' property is false, it means the response was not successful (status code other than 200). You can use this property to check the status of the response and handle it accordingly.
Follow up 2: How do you access the status code of a response?
Answer:
To access the status code of a response, you can use the 'status' property of the Response object. The 'status' property returns the HTTP status code of the response. For example, if the response is a 200 OK status, the 'status' property will return 200. You can use this property to check the status code and handle the response accordingly.
Follow up 3: What is a common way to handle 404 Not Found responses?
Answer:
A common way to handle 404 Not Found responses is to check the status code of the response. If the status code is 404, it means the requested resource was not found. You can then display an appropriate error message to the user or take some other action based on your application's requirements. For example, you might show a 'Page Not Found' message or redirect the user to a different page.
Question 5: Can you explain how to use the Fetch API to make a request to a third-party API?
Answer:
To use the Fetch API to make a request to a third-party API, you can use the fetch()
function. Here's an example of how to make a GET request to an API endpoint:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// Do something with the data
})
.catch(error => {
// Handle any errors
});
In this example, we use the fetch()
function to make a GET request to the https://api.example.com/data
endpoint. We then use the .then()
method to parse the response as JSON and access the data. Finally, we use the .catch()
method to handle any errors that may occur during the request.
Follow up 1: How do you include an API key in your request?
Answer:
To include an API key in your request, you can add it as a query parameter or include it in the request headers. Here's an example of how to include an API key as a query parameter:
fetch('https://api.example.com/data?api_key=YOUR_API_KEY')
.then(response => response.json())
.then(data => {
// Do something with the data
})
.catch(error => {
// Handle any errors
});
In this example, we add the api_key
parameter to the URL with the value of your API key. Alternatively, you can include the API key in the request headers using the Headers
object:
const headers = new Headers();
headers.append('Authorization', 'Bearer YOUR_API_KEY');
fetch('https://api.example.com/data', {
headers: headers
})
.then(response => response.json())
.then(data => {
// Do something with the data
})
.catch(error => {
// Handle any errors
});
Follow up 2: How do you handle CORS issues?
Answer:
To handle CORS (Cross-Origin Resource Sharing) issues when making a request to a third-party API, you can set the appropriate headers in your request. Here's an example of how to handle CORS issues using the Fetch API:
fetch('https://api.example.com/data', {
mode: 'cors'
})
.then(response => response.json())
.then(data => {
// Do something with the data
})
.catch(error => {
// Handle any errors
});
In this example, we set the mode
option to 'cors'
in the request options. This tells the browser to include the necessary CORS headers in the request. If the server allows cross-origin requests, the request will be successful. If the server does not allow cross-origin requests, you may need to handle the error or use a proxy server.
Follow up 3: How do you parse the JSON response from the API?
Answer:
To parse the JSON response from the API, you can use the .json()
method on the response object. Here's an example:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// Do something with the data
})
.catch(error => {
// Handle any errors
});
In this example, we use the .json()
method to parse the response as JSON. The resulting data can then be accessed and used in the second .then()
callback. If the response is not valid JSON, an error will be thrown and can be caught in the .catch()
callback.