Anatomy of a Fetch API Request
What is this fetch thing? By its name, we might guess that we are asking for and going to receive something… sorta like askin’ Fido to go get that daily newspaper for us. We tell him “fetch!” and he runs off and returns with the paper, which, contains a promise that it holds some news, which we can read if we so choose, once we unpack, unfold, and read it.
So, as it happens, the Fetch API is a JavaScript interface we can use to retrieve, store, update and delete data. Fetch allows us to construct an HTTP request, such as GET, POST, PUT, PATCH, and DELETE, to name the five most common methods.
By default, if we do not specify a method, our fetch request will default to a GET request. Yup! Just like sending Fido for that paper! Let’s look at the anatomy of a GET request:
function getAllPups(){fetch('http://localhost:3000/pups') //=> sends the HTTP request to the server.then(response => response.json()) //=> this Promise resolves when server responds.then(json => console.log(json)) //=> this Promise resolves when both the transfer and the JSON parsing complete}
This will send a request to the server at ‘http://localhost:3000/pups’ to retrieve all the pups, which then returns all the pups data, and finally console.logs all the pup data.
If we only wanted information about the first pup, we could follow HTTP format and use the URI (or, the pup id =1), and send this request:
function getFirstPup(){
fetch('http://localhost:3000/pups/1')
.then(r => r.json())
.then(pup => console.log(pup))
}
Which will return a resource like this:
{
"id":1,
"name":"Fido",
"age":4,
"breed":"Golden Retriever"
}
With me so far? Great! Oh, but, clearly, we cannot ask Fido to run along to the New York Times and ask them to POST more news that we believe should be added, or PATCH in an update, or DELETE something; and then return with the updated paper…so, that particular metaphor ends here with a GET request.
However, now that we know we can fetch Fido’s data, or Fido and all the other pups’ data, too; and read it, render it, print it — sorta like that newspaper we got in the beginning of this post — let’s think about this…
…what do we do when we need to add more pups? Well, now we have six more pup objects that we need to send to the database using fetch with a POST HTTP method. Let’s start with that little guy on the right, yeah, him, that one who is yawning.
function addAPup(){
fetch('http://localhost:3000/pups', {
method: 'POST',
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body: JSON.stringify({
"name":"Sleepy",
"age": 0,
"breed":"Golden Retriever"
}
})
.then(response => response.json())
.then(json => console.log(json))
}
So, we send our fetch request with a method of POST, with headers which specify the data type we are adding to our database, and with a body which must match the headers’ data type — which we must stringify — because local storage can only save strings. Also, there is no need to add the id, as POST will add an id to the object sent.
Then, like with any fetch request, a promise is returned. We set a handler to hold the promise until it’s resolved, using the then() method. This handler receives the return value/response object. And we console.log to print our response object to the console.
How to handle errors? Catch, of course!
Since fetch returns a promise, we can use catch() to intercept any error which might occur during the request.
fetch('url')
.then(response => {...
})
.catch(error => console.error(error))
Cool! Now that Sleepy has been added to the database, we can use the POST method to add the rest of those dudes…Bashful, Dopey, Grumpy, Happy, Doc, and Sneezy!
And, similarly, we can create a fetch request with either the PATCH or the PUT method to update an object; or using the DELETE method to remove an object.
But, of course, we don’t want to delete any of our pups!!
For more fetch() information, see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch