DEV Community

Cover image for How to fetch images with Unsplash API using Javascript
Usman
Usman

Posted on • Edited on • Originally published at maxidev.hashnode.dev

How to fetch images with Unsplash API using Javascript

Introduction

It's common in programming to find ourselves in situations where we have to upload images to hosting services to use in our projects, which can take up valuable time and slow down the coding process. In this tutorial, I'm going to guide you on how to easily request images from an API to be directly used in your projects, using the Unsplash API as a primary example.

Prerequisite

  • A basic understanding of HTML, CSS and Javascript is needed for this example below.

  • An Editor/IDE is also recommended, If you don’t have a setup IDE you can use an online editor such as Codepen or JSFiddle

Setting up the API

To begin, we need to create a developer account with the API provider. In this case, we are using the Unsplash API. Now, head over to the documentation link. You should see the page below. Head over to 'Create a developer account' and click 'Join' follow the provided instructions, and accept the terms for API use.

Note: You should create an account with Unsplash first.

'Unslpash developers page '
After setting up your demo app, You should have your API key like this below

'Unsplash API key'

It’s also important to know that you can only make 50 requests per hour for Demo apps and apps in production have access to 5,000 requests per hour. If you need to make more requests you can upgrade your limits or contact the support team. For our tutorial, we’re only fetching images for our simple gallery.

Let's get into the coding aspect.

Coding & Explanation

First, we start with our HTLM part of the code which should look like this

 <section id="gallery">
    <div><img  class="image" alt=""></div>
    <div><img  class="image" alt=""></div>
    <div><img  class="image" alt=""></div>
    <div><img  class="image" alt=""></div>
    <div><img  class="image" alt=""></div>
    <div><img  class="image" alt=""></div>
    <div><img  class="image" alt=""></div>
    <div><img  class="image" alt=""></div>
    <div><img  class="image" alt=""></div>
    <div><img  class="image" alt=""></div>
 </section>  
Enter fullscreen mode Exit fullscreen mode

In this code block, we have a section that contains 10 div elements, each of which holds an image element. These image elements are currently empty, but we will be adding the source files for the images later in the code.

Styling our Gallery

Now we need to style our images to make them look more appropriate. Paste the following code in the CSS part in your codepen

/* Portfolio */
#gallery {
  width:1200px;
  margin-left:30px;
  margin: auto;
  padding-bottom: 30px;
  display: grid;
  grid-gap: 20px;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  box-shadow:  0 1px 5px rgba(104, 104, 104, 0.8);
}
#gallery img {
  height:150px;
  width: 100%;
  box-shadow:  0 1px 5px rgba(104, 104, 104, 0.8);
}
Enter fullscreen mode Exit fullscreen mode

In this CSS block, we style our gallery with a width of 1200 pixels and a 30-pixel left margin for horizontal centering. We use a responsive grid layout that adapts to a minimum column width of 200 pixels with a 20-pixel gap between the image-containing divs. Lastly, we apply a box shadow to both the image and div elements for visibility.

Fetching the images

Our code wouldn't be complete without the Javascript aspect to interact with our API and fetch the images. Our JS code block should look like this :

 // Unsplash Images API request

const apiKey = 'Your API Key';
const images = document.querySelectorAll('.image');

fetch(`https://api.unsplash.com/photos/random?query=restaurant&count=10&client_id=${apiKey}`)
  .then(response => response.json())
  .then(data => {
    data.forEach((photo, index) => {
      images[index].src = photo.urls.regular;
    });
  });
Enter fullscreen mode Exit fullscreen mode

Here should be the Output of all the codes put together

'A simple gallery of 10 images'

You can take it a step further by wrapping our request into a function 'getImages', Now we can set this function to request images at different intervals, for example :

 //getImages Function
function getImages() {
   fetch(`https://api.unsplash.com/photos/random?query=food&count=10&client_id=${apiKey}`)
     .then(response => response.json())
     .then(data => {
       data.forEach((photo, index) => {
         images[index].src = photo.urls.regular;
      });
    });
 }

// Set interval
getImages();
setInterval(getImages, 10000);
Enter fullscreen mode Exit fullscreen mode

Here we are requesting new images at a 10-second interval (10,000 milliseconds).

Conclusion

We have covered the basic aspects of fetching images, This can apply to other APIs aside from Unslpash, It's the same method involved, All you need is an API key to request the server. Now you can begin to implement this in your upcoming projects or apps.

If you enjoyed the article, give me a follow here and on my GitHub

Happy Coding!

Top comments (3)

Collapse
 
thomasbnt profile image
Thomas Bnt

Awesome!

Collapse
 
the_riz profile image
Rich Winter • Edited

Oof! Sorry man - gotta call out some bad things here:

  • NO ERROR HANDLING!

  • Generally avoid using IDs in css when a class will do (though I'll let it slide because you do use it in your JS)

  • Better idea to build/remove the div/images in your code and append them into #gallery. What if your API call only returns, say, 3 results? You end up with strange extra empty boxes.

  • (small typo: you mean 10,000ms = 10sec)

Collapse
 
maxixo profile image
Usman • Edited

Thanks man , I appreciate your corrections.