W03 Learning Activity: Review: The Fetch API
Overview
A key in modern web development is making asynchronous HTTP requests to communicate with servers without forcing a full page refresh. This activity will help you review how to use the Fetch API to make these requests.
Prepare
The fetch api is a modern way to make HTTP requests. It is a native (built-in) Web API supported by most modern browsers and is a great way to get started with making requests to APIs. The fetch API returns a promise that resolves to the response of the request. This response can then be converted to JSON or text, depending on the type of data you are expecting back from the server.
If needed, review the following resource from WDD 231:
Here is a simple example of how to use the fetch API:
const url = 'https://pokeapi.co/api/v2/pokemon/1';
const options = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
};
fetch(url, options)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log('first: ', data);
console.log('second: ', data.name);
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
Activity Instructions
Optional Resources
- Fetch API – MDN
- Fetch() Supplying Request Options – MDN