What is Fetch? And How do you use it to get data from an API?

Joel Rivera
5 min readJan 15, 2019

--

Fetch in programming has a few meanings. The one that will be focussed on here is the process of having data and trying to be able to view its contents to be able to manipulate that data for it to be seen on the DOM (document object model) for us. An API stands for Application Programming Interface. For now, just understand that an API is the part of the server that receives requests and sends responses.

As a beginner programmer, I’ve been struggling to understand the components of Fetch. Think of fetch like the literal game of playing fetch with your dog. As you throw the frisbee, you would like it for your dog to run after the frisbee and hopefully bring it back to you. The first step of throwing and seeing where it lands can be thought of when you first find the API you want to use for your application. You now know where the server is, but the next step is the actual retrieval process. This is where you would hope your dog runs after the the frisbee. At the very least, if your dog runs to the frisbee and has it in his/her mouth, think of this as a ‘promise’. This promise is the dog ‘promising’ to eventually bring it back. If he/she never brings it back, then that’s another problem…

Let’s say your dog decides to at some point retrieve the frisbee and bring it back in one piece, success! Now you can decide to do whatever you want next.

So to break down the steps: 1. You throw the frisbee and see where it lands (fetch the url). 2. Your dog runs after the frisbee and has it in their mouth to eventually bring it back in one piece (A promise to do what you want). 3. Your dog finally brings it back to you and delivers it as you would like (You received the data for you to use how you would like).

Now to see it in code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id="get-posts"> Get Posts </button>
<div>
<form id="new-user">
<label id="name">Name:</label>
<input type="text" name="name" id="user-name">
<br/>
<label id="email">Email:</label>
<input type="text" name="description" id="user-email">
<br/>
<label id="favorite_color">Favorite Color:</label>
<input type="text" name="url" id="favorite-color">
<br/>
<br/>
<input type="submit" value="Create User"></input>
</form>
</div>
<script src="index.js" charset="utf-8"></script>
</body>
</html>

This is my HTML file I created for the purpose of this article. I have a simple form, a few id’s to use for my structuring of the page. Right above my </body> closing tag is my link to my JS script.

document.addEventListener('DOMContentLoaded', () => {// This fetch is retrieves all of the data from the urlfetch("http://localhost:3000/users")
.then(response => response.json())
.then(data => {
const usersInfo = document.createElement('div')
data.forEach(user => {
usersInfo.innerHTML +=
`
<ul>
<li>Name: ${user.name}</li>
<li>Email: ${user.email}</li>
<li>Favorite Color: ${user.favorite_color}</li>
</ul>
`
})
// This is where I would like my fetch request to be on the page document.body.append(usersInfo)
})

Above, I am simply doing a fetch request to GET all of the users in the current data, which was step 1. The fetch is looking for the users file I created to have some example json data to use. The two ‘.then’ s that are shown were steps 2 and 3 from above. After the fetch, you receive your response, and then after the response (promise) and then you take this promise and then tell the fetch request the information inside is to be viewed as a json file. The <ul> and <li> tags are just for how I want the data to be displayed on my page.

// This line was written above the rest of the written code below
// This is to add the click feature on my button
document.querySelector('#get-posts').addEventListener('click', getPosts)
// This fetch shows all of the posts after the button is clicked on // the page
const getPosts = () => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(data => {
const showPosts = document.createElement('div')
data.forEach(post => {
showPosts.innerHTML +=
`
<h3>${post.title}</h3>
<p>${post.body}</p>
`
})
document.body.append(showPosts)
})
}

Here, I am now fetching a different API that just has some example posts. As you can see with this one is that the fetch request has a route finishing with ‘ /posts ’ . This is because I am essentially saying to fetch me all of the posts that is inside of this API. The rest is very similar to the above Users example. Fetch the file, see the response, parse it to json, and then do what you want with it.

// This line was written above the rest of the written code below
// This is to create a new User and just display it in the console
document.querySelector('#new-user').addEventListener('submit', newUser)
// This fetch is a POST request to create a new User
const newUserForm = {
"name": name,
"email": email,
"favorite_color": favorite_color
}
const newUser = (e) => {
e.preventDefault();
const name = document.querySelector('#name')
const email = document.querySelector('#email')
const favoriteColor = document.querySelector('#favorite_color')
fetch("http://localhost:3000/users", {
method: 'POST',
body: JSON.stringify(newUserForm),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(data => console.log(data))
}

This final example is the most complicated yet. If you look at the fetch line, I am still fetching the Users’ data, however, there is a second argument. The second argument is an object that has three keys: method, body, and headers. The method is now saying that this will be a POST request instead of the GET requests we make above (the GET request’s above are implied, any other requests has to be made explicitly). The body key is taking the data that our new user typed in for his information and turning it into a readable piece of data. Then, the headers key is here to let the request know the type of content is the data. The response you receive is the actual data that was typed in and from here, I’m just simply console logging the data to be seen there.

And there it is!

A fetch request using both GET and POST http verbs.

To a beginner programmer, fetch can be confusing. The best thing to do is to keep practicing. The more you practice, the better you will become. Certain concepts will always come faster than others, but that’s okay. Keep learning. Keep coding.

This story is published in Noteworthy, where 10,000+ readers come every day to learn about the people & ideas shaping the products we love.

Follow our publication to see more product & design stories featured by the Journal team.

--

--

Joel Rivera

I am a software engineer currently specializing in building out scalable applications using React and Node.JS, docker-izing and deploying them on AWS.