How to fetch data from public API using JavaScript?

In this tutorial, we will learn how to fetch data from public API in JavaScript.

What is the use of an API?

Basically, API specifies how two-component should interact with each other. It allows you to send information between two different software.

  • It has used web applications.
  • It provides an edge for desktop applications.
  • It also running in mobile applications possible.
  • It is used in payment gateway integrations.
  • It is used in many domains and devices like automobiles, watches, IoT devices.

For example, if you want to get news on your website or mobile app, API will help send data from server to client.

There are two ways of transferring the data.

  • Using JSON
  • Using XML

There are 3 types of API:

  1. Private
  2. Partner
  3. Public

Here, we will learn how to fetch dog images from public API.

Some public APIs are free available. You can use it in your project.

https://github.com/public-apis/public-apis/blob/master/README.md

<!DOCTYPE html>
<head>
 <!--     External css      -->
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div>
        <img id="image">
        <br>
        <button onclick="get_random_pic()">Random</button>
    </div>
    <script type="text/javascript" src="javascript.js"></script>
</body>
</html>

style.css for the styling web page.

body{
    background-color: tomato;
    text-align: center;
}
#image{
    width: 500px;
    height: 500px;
    margin-top: 10px;
    object-fit:cover;
    border: 5px solid white;
    border-radius: 10px;
}
button{
background-color: rgb(89, 0, 255);
color: white;
margin-top: 10px;
width: 100px;
height: 35px;
font-family: Verdana, Geneva, Tahoma, sans-serif;
font-size: medium;
border-radius: 5px;
border:3px solid white;
cursor: pointer;
}

JavaScript code to fetch data from public API

function get_random_pic(){

    url="https://dog.ceo/api/breeds/image/random";
    fetch(url)
    .then(function(res){
        return res.json();
    })
    .then(function(data){
        display_pic(data.message);
    })
    .catch(function(error){
        console.log("error"+error);
    });
}
function display_pic(img_url){
    document.getElementById("image").src=img_url;
}

Here, get_random_pic() function fetch image from given URL and display_pic(img_url)  function set on web page.

For the demo please use this code and save it.

index.html, style.css, and javascript.js.

Also read: Get YouTube video key from URL in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *