How to fetch images with Unsplash API using Javascript
Tags: javascript, api, webdev, unsplash
Published: 2023-09-09 14:20:11

##
## 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](https://codepen.io/pen/) or [JSFiddle](https://jsfiddle.net/). 
    



## 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](https://unsplash.com/documentation#creating-a-developer-account) 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 '](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0tg7yv335kgsntb3lcf1.png)
After setting up your demo app, You should have your API key like this below


!['Unsplash API key'](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/genwwuvjdt26q1fkdnkw.png)

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

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

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

```css
/* 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);
}
```

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 :

```javascript
 // 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;
    });
  });
```

Here should be the Output of all the codes put together


!['A simple gallery of 10 images'](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xkhhy2peul4nra44jh00.png)

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 :

```javascript
 //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);
```

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](https://github.com/maxixo)

Happy Coding!

  

###