Simple example of using Fetch

Desiree Joy Bradish
2 min readJan 14, 2022

--

Large brown dog holding green tennis ball.

What is fetch?

While sure you can play fetch with your pup, if you tried to engage him in a fetch call your results will not be great.

Fetch is a way for you to communicate with an API. Be that API your own express server that controls access to your mongoDB or to the information from a publicly accessible api such as https://pokeapi.co/ Fetch is promise based.

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
- MDN

Fetch connects to the endpoint, which is the url given by the api or that you have set up for you to connect with. A promise is then returned.

fetch('https://pokeapi.co/api/v2/pokemon/bulbasaur').then (res =>{
res.json()
})

Now if you console log this call, you will see that the promise has actually been returned. So after that we used a .then statement to grab the res (response object) and attached the json method to be able to read the body of it. The .json method returns another promise, so we will chain them.. but first…

We have another problem. With fetch requests, unless something actually stops fetch from reaching the url, it will consider itself successful no matter if any information is returned. We need to check if the response is valid by checking if it is .ok.

fetch('https://pokeapi.co/api/v2/pokemon/bulbasaur').then (res =>{if (res.ok){
res.json()
}
})

Now we want to make sure we have the data from that second promise, or give an error. Now is when we start chaining our .then statements.

fetch('https://pokeapi.co/api/v2/pokemon/bulbasaur').then (res => .then (res =>{if (res.ok){
res.json()
}
}).then(data => console.log(data)).catch (error => console.log(error))

Now that we have that settled, what if we want to do something with the data? Well when we called fetch we only filled in the url parameter. Fetch actually has two parameters, the url and the second which is an object. This object includes the method. This would be a standard HTTP type method such as POST/GET/DELETE. What we’ve already done is a GET, by default.

Now we don’t have the clearance to POST or DELETE from the Pokemon API, but let’s imagine we did. We’re gonna post our original Pokemon, Bigfoot. We’re going to pass Bigfoot as a JSON so we need to set Headers as the Content-Type: application/json.

fetch('https://pokeapi.co/api/v2/pokemon/bulbasaur', {method: 'POST',headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'Bigfoot',
type: 'ground'
})
}
)
.catch(error => console.log('ERROR'))

Don’t forget to use JSON.stringify() to change your JS object to a JSON string so that the API can utilize your data.

That’s a pretty simple overview of fetch, I hope it helped!

--

--

Desiree Joy Bradish

Full Stack Developer at Flexion Inc. with an Accessibility Focus