DEV Community

Ahmad Abdulaziz
Ahmad Abdulaziz

Posted on • Updated on

Using Fetch API to Get and Post

fetchAPI

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 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

  1. 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, Random User API. But in this example, we will be using JSONPlaceholder API. An API that generates random users.

  1. 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> 
  1. 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>
  1. 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
here on my GitHub repo, Repo Link. and DEMO ON. Don't forget to star the repo

If you’d like to learn more please visit. Mozilla fetchAPI.

Follow me on twitter @dev_amaz and feel free to contact me if you need any help. You can also send me email on Ahmad.abdulaziz37@gmail.com.

Top comments (7)

Collapse
 
gilesomofa profile image
Giles Smith

A salam, greetings, and salutations. Thanks for taking the time to share. I'm working on my final project for a Bootcamp and this is helping me a lot. Much respects!!!

Collapse
 
dtsiridakis profile image
dtsiridakis

Nice post !

Trying to fetch HTML data with fetch() method is possible?

I am facing some issues with cors
And I can’t fetch HTML data back.

Collapse
 
devamaz profile image
Ahmad Abdulaziz • Edited

fetch accept URL not sure how you want to fetch HTML for more understanding visit the links in the above comment

Collapse
 
justsml profile image
Daniel Levy

I know this is a bit late of a response, but for anyone interested you can get any string data response via response.text() similar to how response.json() will give you a parsed JSON object.

Collapse
 
silasonyango93 profile image
silasonyango93

Cors is an issue with the api itself and not the front-end.

For more information : daveceddia.com/access-control-allo...

Collapse
 
pranay_rauthu profile image
pranay rauthu

I want to add a couple of resources here. check this link for polyfill and fetcher to generate code with GUI.

Collapse
 
devamaz profile image
Ahmad Abdulaziz

Thanks nice resources