DEV Community

Cover image for How to fetch images from an API
Satvik
Satvik

Posted on

How to fetch images from an API

Making a website that displays random cat images

API's are really helpful in performing designed function built around sharing data and executing pre-defined processes

We can quickly fetch images from an API for our website . In our case we will be fetching cat images from a popular public API and will display it on a website

API I'll be using : docs.catapi.com
Get your API Key from - thecatapi.com

Load api.thecatapi.com/v1/images/search
Get the first Array object of the JSON response
Load it’s .url

function fetchPics(){
    let catsImgDiv = document.querySelector(".catsImgDiv")
    catsImgDiv.innerHTML='';
    fetch("https://api.thecatapi.com/v1/images/search") .then(
    (response)=>
     response.json()
    )
}
Enter fullscreen mode Exit fullscreen mode

To use this in a website we add :

A button which fetches a new image when it's clicked
An empty div to show the image
in the .html file

<button class="btn btn-primary my-4 generate_btn">Generate</button>
<div class="catsImgDiv"></div>
Enter fullscreen mode Exit fullscreen mode

Final JavaScript iteration :

function fetchPics(){
    let catsImgDiv = document.querySelector(".catsImgDiv")
    catsImgDiv.innerHTML='';
    fetch("https://api.thecatapi.com/v1/images/search") .then(
    (response)=>
     response.json()
    )
    .then ((data) => {
        let catsImgUrl=data[0].url;
        let catImgEl = document.createElement("img")
        catImgEl.setAttribute('src',`${catsImgUrl}`)
        catImgEl.classList.add("showcase")
        let catsImgDiv = document.querySelector(".catsImgDiv")
        catsImgDiv.appendChild(catImgEl);
    })
    .catch (err=>console.log(err))
}
Enter fullscreen mode Exit fullscreen mode

You can also look up on how to setup a website with github pages here : Github Pages

Website : Live
Github : Github

Latest comments (0)