How to fetch APIs using Vanilla js
Tags: javascript, 100daysofcode
Published: 2022-02-01 14:34:25

Y'ello!

In this article, we are going to fetch APIs using vanilla js. But before we go into it. What are APIs really?

> API is the acronym for Application Programming Interface, yeah so?. It's like a bridge for communication between two platforms. This happens when you are listening to song online, like Spotify, or when you are on Instagram scrolling through your feeds or even now, while you're reading this post!.

The first platform is the UI(application) you interact with, the second platform is the where all the data(the songs you listen to on Spotify, the pictures or videos you like Instagram) you are interacting with comes from, this could be a microservice or a backend server with database.

APIs are the interfaces used when you want to send data from a database or wherever you store it basically.

What are HTTP requests?

> An HTTP request is made by a client(a web page in this case, mobile app, e.t.c), to a named host, url or a resource, which is located on a server. The aim of the request is to access or manipulate data on the server.

When you search for a song or a picture, you are making a request to get data. There are different HTTP requests depending on the action you are taking in the current application.

They are GET, POST, PATCH/PUT, DELETE, many others. I'm not going to go into the details here. To learn more about them you can check MDN https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

We are going to build a simple todo list using REST APIs, we are going to consume some data coming from an endpoint(url) and also write a POST request.

I'm gonna assume that at least you know HTML, CSS and a lil bit of Javascript :D. Moving on, create a folder or a directory add the code to your "name_of_file".html 

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Fetching and posting to rest apis</title>
  </head>
  <body>
    <div class="main--container">
      <div class="card">
        <h2>Todo list</h2>
        <div class="card-body">
          <form id="form" action="script.js">
            <div class="input-group">
              <div class="">
                <input
                  type="text"
                  class="input-control"
                  id="todo"
                  placeholder="Add todo"
                  aria-describedby="emailHelp"
                />
              </div>
              <button id="btn-submit" type="submit">Submit</button>
            </div>

            <ul class="todos__container" id="todo__container">
              <li class="todo">
                <input type="checkbox" name="" id="" class="checkbox" />
                <p>Wash plates</p>
              </li>
              <li class="todo">
                <input type="checkbox" name="" id="" class="checkbox" />
                <p>Wash plates</p>
              </li>
              <li class="todo">
                <input type="checkbox" name="" id="" class="checkbox" />
                <p>Wash plates</p>
              </li>
              <li class="todo">
                <input type="checkbox" name="" id="" class="checkbox" />
                <p>Wash plates</p>
              </li>
            </ul>
          </form>
        </div>
      </div>
    </div>
    <script src="script.js"></script>
  </body>
</html>

```

Next, we are going to create a css file, "style.css" in the same directory. Copy the following code into it :D 

```css
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.card {
  background-color: white;
  padding: 20px;
  box-shadow: 0 4px 12px 0 rgb(0 0 0 / 5%);
  min-height: 400px;
  min-width: 400px;
}

input[type="text"] {
  height: 40px;
  width: 100%;
  border-radius: 3px;
  border: 0.5px solid blueviolet;
  outline: none;
  padding: 10px;
}

.input-group {
  display: flex;
  align-items: center;
}

button {
  height: 40px;
  width: 100px;
  background-color: blueviolet;
  border: 1px solid blueviolet;
  border-radius: 3px;
  color: white;
  margin-left: 5px;
}

button:hover {
  background-color: white;
  color: blueviolet;
  cursor: pointer;
}

.main--container {
  width: 100%;
  min-height: 80vh;
  margin: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
}

.todos__container {
  list-style: ordered;
  margin-top: 20px;
}

.checkbox {
  margin-right: 10px;
}

.todo {
  display: flex;
  width: 100%;
  align-items: center;
}

```

Now, you can view the web page in the browser, it should look like this
![simple-todo-list](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3g4rwksu39g46igxzup0.png)

Next, create a "script.js" file in the same directory. We are going into the main part of this article.

Remember a few moments ago, we talked about getting some data from a source(url), we are going to use JsonPlacholder API, it's pretty fast and easy to implement. You can check it out here: https://jsonplaceholder.typicode.com/guide

To get data from a source, we need a function to run everytime we want to get data. Copy this code;

```javascript
function fetchData() {
  fetch("https://jsonplaceholder.typicode.com/todos")
    .then((response) => response.json())
    .then((json) => takeData(json));
}

function takeData(val) {
  return val.slice(1, 11);
}

fetchData();
```


`fetchData` is the function that makes a request, it's using the built-in `fetch` method, which takes a url or a resource(stringified), an optional object of properties containing the HTTP method, body, headers and other necessary parameters, for more info, check here https://developer.mozilla.org/en-US/docs/Web/API/fetch
If the fetch method is called with one parameter, it will make a GET request by default.

If you log the data into the console, you'll see the output is about 200 todos, that's a lot! That why I created the function `takeData`, it's just going to take the first 10 todos from the response.

Next, we are going to render the todos we sliced out of the array. You need to delete all the lis in your html code first.

Copy the following code.


```javascript

function checkTodos(val) {
  let bool = "false";
  val === true ? (bool = "COMPLETED") : (bool = "UNCOMPLETED");
  return bool;
}

function renderData(dataSlice) {
  let list = dataSlice
    .map(
      (todo, i) =>
        `<li class="todo">
		
   <p>${i + 1}. ${todo.title} - ${checkTodos(todo.completed)}</p>
 </li>`
    ) //5
    .join(" "); //6

  //7 i + 1

  todosList.innerHTML = list;
}
```

Put this code `const todosList = document.getElementById("todo__container");` at the top level of your script.

Okay, before you jump out of here! 

1. We're mapping the array we got from the slice.
2. We're creating a todo for every item, we get. 
3. In the map function, we get access to the index, we are adding 1 to each index because, computer counts from 0. So we get 1 - 10, instead of 0 - 9.
4. For each item, remove the comma after it.
5. After removing the commas, join them with a space instead, so we don't see commas, rendered from the list.
6. `checkTodos` renders a string based on the values it gets.
7. `list` is the variable saving the html template strings of todos and we push it into the todo list container.


You should see something like this: 
![tod-list with apis](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ryjth8foczdqkvdbrurb.png)

You just made your own request, yaaay!!!.

Now let's round this project off by also adding a post request. Note that JsonPlaceholder does not save your data in It's database, that will be unsustainable. It's going to return your data, thereby imitating, the way a data is sent to the server and sent back to the client. Copy the following code into your script 

```javascript

const input = document.getElementById("todo"); //put this at the top level of your code
const button = document.getElementById("btn-submit"); //put this at the top level of your code
const form = document.getElementById("form");//put this at the top level of your code


function postData(data) {
  fetch("https://jsonplaceholder.typicode.com/todos", {
    method: "POST",
    body: JSON.stringify(data),
    headers: {
      "Content-type": "application/json; charset=UTF-8",
    },
  })
    .then((response) => response.json())
    .then((json) => console.log(json));
}

form.addEventListener("submit", (e) => {
  e.preventDefault();
  console.log(input.value);
  let data = {
    title: input.value,
    completed: false,
    userId: 1,
  };

  postData(data);
});


```

Here we did the following:
1. We select the form, button and input.
2. `postData` function is making a POST request. It is sending the data it recieves from the input value and it logs it response into the console.
3. `form` is listening for a submit event, this means that it will submit the value if a user clicks the submit button or presses enter.
4. `e.preventDefault()` prevents auto submission.
5. We log the value we are getting from `input` and we save the necessary parameters.

It should look like this 
![todo list with post request](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0fuua9g1s8zpx8hk2ide.png)

One more thing! we need to clear input on submit too!
add this code `input.value = ""` to the eventlistener function in `form` 

Now it should look like this when you send a todo!
![completed todo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sd4rr3vzb20z9xxhfy3w.png)

If you still have problems with this project you can check the source here https://github.com/ayomidebajo/fetch-api-with-plain-js.

We just interacted with a REST API and we sent our first POST request! Yaaaaaayyyy!