Fetch Yourself Some URLs.

Charlie Knight
4 min readJan 27, 2021

Javascript has a built-in function that makes it tremendously easy to grab information from any website. Using fetch(www.exampleurl.com) you can retrieve just about anything (if it’s offered in the proper format) and re-render or reuse it for your program. Following the CRUD format I will go over the following fetch requests:

GET — Read

POST — Create

PATCH/PUT — Update

DELETE — Destroy

Every fetch request has the same basic structure: a URL to request data from, the type of request (it will default to GET), headers (typically the same, anything other than application/json is beyond the scope of this article), body (this is where you will set the change, for GET requests this is unnecessary) and .then will be how you want the data to be rendered.

GET request:

//index.jsfunction getDogs() {    
fetch ('http://localhost:3000/dogs')
.then (res => res.json())
.then (dogs => renderDogs(dogs))
}
//or handle iteration within the fetch function getDogs() {
fetch ('http://localhost:3000/dogs')
.then (res => res.json())
.then (dogs => dogs.forEach(dog => renderDogs(dog))
}

To test out what data you’re getting you can use .then (dogs => console.log(dogs)) and see the output. This will allow you to tailor the last .then so the data it presented on the page the right way. Typically we will have to iterate through the data since it is passed backed to us as an array of objects. The data is originally passed back as JSON data, which is all strings, the .json allows us to take the response from the API and parse it so we can manipulate it.

POST request:

//index.jsfunction createDog() {    
const body = {name: newName} //set the object to be "stringified"
fetch ('http://localhost:3000/dogs', {
method: 'POST',
headers: {
'Content-Type': 'application/json'}
body: JSON.stringify(body) })
}

// once posted we will render dogs again with the new item in the database

This can also be fairly straightforward with a little additional inputs since many of the fields for a fetch are defaulted for a get request. Note that the body data type must match what’s stated in the header, in this case, JSON. The body for a post will be all the attributes for a given object, for the above, only a name is needed on the creation of this particular object.

PATCH/PUT request:

Of the four operations this is probably the most complex, providing for variability in how something is updated and how that update will be presented on the screen once it’s changed. A quick aside before showing sample code; PUT is for updating the whole object and PATCH is a partial update, an example would be if I did the following (pseudo code)

const obj = {first:  charlie, last: knight}
method: 'PUT'
body: {first: chucky}
obj = {first: chucky} method: 'PATCH'
body : {first: chucky}
obj = {first: chucky, last: knight}

as you can see the PUT got rid of the last attribute altogether and the entire object has been changed. A PUT is similar to a POST in that it essentially creates a new object but then replaces the old one.

//index.jsfunction updateDog(dog) {    
const update = {name: newName}
fetch (`http://localhost:3000/dogs/${dog.id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'}
body: JSON.stringify(update) })
.then(resp => resp.json())
.then(dogs => renderUpdatedDogs(dogs))
.catch(error => console.log(error))}

Somewhat similar to POST since I am just updating the name but things can get trickier when you want to update certain attributes that take a fair amount of logic. Rule of thumb is to separate it out and set things to other variables/functions so all the language is implied. I also added .catch so you can visibly see the error that occurred if there was one with calling the api. Another key difference is my route is set to the ‘show’ page of a particular dog since I need to specify which dog I’m updating.

DELETE request:

//index.jsfunction updateDog(dog) {    
fetch (`http://localhost:3000/dogs/${dog.id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json' }}
.then(resp => resp.json())
.then(dogs => renderUpdatedDogs(dogs))
.catch(error => console.log(error))}

Very straightforward, you do not need to pass anything into the body for this since you will be erasing all associated information from the database. Again, the only thing that can be tricky is how you’d like to re-render the information so the deleted object is properly removed from the DOM as well.

Uploading a file: a useful tidbit is knowing that you can upload files as well, if you’d like to add a picture this can especially useful.

const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

formData can now be used in the body of the fetch i.e. body: formData.

resources:

--

--