Using Fetch API to Get and Post 
Tags: javascript, es6fetch, api
Published: 2018-06-14 15:48:40

---
title: Using Fetch API to Get and Post 
published: true
description: beginners guild on how to use fetch API
tags: #javascript #es6 fetch #API
---

![fetchAPI](https://i.ytimg.com/vi/0bec1BmeY4c/maxresdefault.jpg)

In this article, I will talk about how to use javascript fetch API to get and post data to a public API.

PREREQUISITE
* Text Editor (Notepad++, VSCode, Atom, Bracket, Sublime,  any text editor of your choice)
* Browser( Chrome, Moxilla)
* Any server of your choice (WAMP, XAMP), you can also install live-server extension if you are using VScode, atom-live-server if you are using Atom, or just install npm live server using ```npm install –g live-server``` if you have node install on your machine.


## INTRO

Fetch API is a built-in Javascript ES6 [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that is used to make XMLHttpRequest simpler and easier to GET or POST data asynchronously. There are a lot of libraries that are used to make XMLHttpRequest simpler and easier to read. The most popular one is "jquery's ajax", but fetch API allows us to make XMLHttpRequest with Native Javascript without import of any library. 

Below is a syntax of simple fetch() call back
```
#fetch Syntax

         fetch(url)
            .then(function (res) {
                return res, json()
            })
            .then(function (data) {
                Console.log(data);
            }).catch(function (err) {
                console.log(err)
            })
```


### How to use fetch API  to GET data from an API
1. Create a directory, name it any name of your choice, mine will be call fetchAPI. You can do this using the traditional way of creating a directory,  create an index.html file inside the folder or you can use the code below in your terminal.

```
//create directory
       mkdir fecthAPI
//enter the fecthAPI folder
       cd fetchAPI
//create  an index.html file
       touch index.html
	
```

2. Let add the basic html tags, two button tags with an id of id="getData" and id="getAPI" respectively and a paragraph tag with an id='result'.

```
<!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>Fetch API</title>
</head>
<body>
	  <button id="getData">GET DATA FROM LOCAL</button>
          <button id="getData">GET DATA FROM API </button>
          <p id="result"></p>
    
</body>
</html>
```

The buttons will be used to send a GET request to a local sampleUser.json and public API. There are a lot of public API's you can get data from e.g [Github API](http://api.github.com/users), [Random User API](http://randomuser.me). But in this example, we will be using [JSONPlaceholder](https://jsonplaceholder.typicode.com) API. An API that generates random users.

3. Create javascript eventListener to handle the click event in the index.html file.

```
<script>
        document.getElementById('getData').addEventListener('click', getData);
        document.getElementById('getAPI').addEventListener('click', getAPI);

        
        function getData(){
            // code to execte
        }
        
        function getAPI(){
            // code to execte
        }

</script> 
```

4. Let get data from the local file using the fetch API to give more understanding on how to work with the local file. Create a JSON demo “sampleUsers.json”  to try and get data in it.
>Note: Create your sampleUser.json in the same folder with the index.html file for easy access.

```
[
    {
        "id": 1,
        "name": "Ahmad Abdul-Aziz",
        "email": "Ahmad.abdulaziz37@gmail.com"     
    },
    {
        "id": 2,
        "name": "Ahmad Habib Hussein",
        "email": "Ahmadhabibhussein@mail.com"     
    },
    {
        "id": 3,
        "name": "Abdullahi Aminu",
        "email": "Aminuawesome@mail.com"     
    },
    {
        "id": 4,
        "name": "Idris Muhammad",
        "email": "rismad@mail.com"     
    }
]
```

Good, now let write the fetch() script to get data from the sampleUser.json file you just created and output the result to the index.html

>Note: Write script inside getData() function
```
//getData function

//Using javascript ES5 function 

fetch('sampleUser.json')
    .then(function (res) {
        return res.json();
    })
    .then(function (data) {
        let result = `<h2> User Info From sampleUser.json </h2>`;
        data.forEach((user) => {
            const { id, name, email } = user
            result +=
            `<div>
                <h5> User ID: ${id} </h5>
                <ul class="w3-ul">
                    <li> User Name : ${name}</li>
                    <li> User Email: ${email} </li>
                </ul>
            </div>`;

            document.getElementById('result').innerHTML = result;
        });
       })

```


Ok, we are good to go. Run the code. “Yay” Simple and fast right? We will apply the same method to get data from a real  API but this time supplying the API endpoint. 

>Note: Write script inside getAPI() function

```
//sampleUser.json is replaced by an API endpoint.

//Using ES6 arrow function 

    fetch('https://jsonplaceholder.typicode.com/users')
        .then((res) => { return res.json() })
        .then((data) => {
            let result = `<h2> Random User Info From Jsonplaceholder API</h2>`;
            data.forEach((user) => {
                const { id, name, email, address: { city, street } } = user
                result +=
                    `<div>
                     <h5> User ID: ${id} </h5>
                         <ul class="w3-ul">
                             <li> User Full Name : ${name}</li>
                             <li> User Email : ${email} </li>
                             <li> User Address : ${city}, ${street} </li>
                         </ul>
                      </div>`;
                        document.getElementById('result').innerHTML = result;
                    });
                })
```

Sweet at this point, we can get data from both sampleUser.json locally and Jsonplaceholder API. Let go on and Post data


### How to use fetch API to POST data to an API
1. In our index.html file let add a form with an id='postData', two input box and a submit button.

```
<form  id="postData">
        <div>
            <input type="text" name="" id="tittle">
        </div>
        <div>
            <textarea name="" id="body" cols="20" rows="5"></textarea>
        </div>
        <input type="submit" value="SEND POST">
    </form>
```

2. Add an eventListener to handle the submit button in our form.

```
document.getElementById('postData').addEventListener('submit', postData);

 function postData(event){
            event.preventDefault();
            
            let tittle = document.getElementById('tittle').value;
            let body = document.getElementById('body').value;

            fetch('https://jsonplaceholder.typicode.com/posts', {
                method: 'POST',
                headers : new Headers(),
                body:JSON.stringify({tittle:tittle, body:body})
            }).then((res) => res.json())
            .then((data) =>  console.log(data))
            .catch((err)=>console.log(err))
        }
```

Use preventDefault() method to stop or prevents the browser from executing the default action. You can handle your response any way you feel like but in this example, we are going to output it to the console.


 
## Conclusion
We have come to the end of this tutorial. Thank you for reading thus far.

This post is just a simple introduction of how to GET and POST data with fetch API. Feel free to explore more:


You can grab the final source code with styling using [w3schools CSS ](https://www.w3schools.com/w3css/4/w3.css)
here on my GitHub repo, [Repo Link](https://github.com/devamaz/fetchAPI).  and [DEMO ON](https://devamaz.github.io/fetchAPI/).  Don't forget to star the repo

 If you’d like to learn more please visit.  [Mozilla fetchAPI](http://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).



Follow me on twitter [@dev_amaz](http://twitter.com/dev_amaz) and feel free to contact me if you need any help. You can also send me email on Ahmad.abdulaziz37@gmail.com.