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.

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

style.css for the styling web page.

    background-color: tomato;
    text-align: center;
    width: 500px;
    height: 500px;
    margin-top: 10px;
    border: 5px solid white;
    border-radius: 10px;
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(){

        return res.json();
function display_pic(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 *