# Display a Random Image Using the Unsplash API

**URL:** https://forum.kirupa.com/t/display-a-random-image-using-the-unsplash-api/653866
**Category:** web dev
**Created:** [October 5, 2022, 12:39am UTC](https://forum.kirupa.com/t/display-a-random-image-using-the-unsplash-api/653866 "2022-10-05T00:39:34Z")
**Posts on this page:** 12
**Page:** 1

<div class="post-metadata">

### Author: ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)
#### Post date: [October 5, 2022, 12:39am UTC](https://forum.kirupa.com/t/display-a-random-image-using-the-unsplash-api/653866/1 "2022-10-05T00:39:34Z")

</div>

This is the companion topic to the **Display a Random Image Using the Unsplash API** coding exercise:

> **[Display a Random Image Using the Unsplash API : Frontend Coding Exercises](https://www.kirupa.com/codingexercises/display_random_image_unsplash.htm)**
>
> Navigate the fun world of APIs in this coding exercise where you display a random image from Unsplash.

---

<div class="post-metadata">

### Author: ![BJJB](https://avatars.discourse-cdn.com/v4/letter/b/bc79bd/32.png) [@BJJB](https://forum.kirupa.com/u/BJJB)
#### Post date: [April 17, 2023, 12:14pm UTC](https://forum.kirupa.com/t/display-a-random-image-using-the-unsplash-api/653866/2 "2023-04-17T12:14:31Z")

</div>

Here’s my solution, your YouTube example was very helpful, but I could not get the "let clientID = " line to work with my client ID on macOS, so I just included it in the Unsplash API URL. Thank you.

```auto
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Display Random Image</title>
</head>
<style>
  body {
    background-color: yellow;
    text-align: center;
    font-family: sans-serif;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  #unsplashImage {
    max-height: 500px;
    border: 20px solid black;
    transform: rotate(3deg);
  }

  h1 {
    font-size: 56px;
  }

  .imageDetails {
    background-color: black;
    margin-top: 50px;
    padding: 10px;
    color: white;
    text-decoration: none;
    font-weight: bold;
    width: fit-content;
  }

  .imageDetails a {
    color: #FFF;
  }

  .imageDetails a:hover {
    color: yellow;
  }
</style>

<body>
  <h1>Random Unsplash Image</h1>
  <div class="imageContainer">
    <a id="imageLink" href="#">
      <img alt="" id="unsplashImage" />
    </a>
  </div>
  <p class="imageDetails">Photo by <a id="creator" href="#">NAME</a> on <a href="https://www.unsplash.com">Unsplash</a>!</p>
  <script>
    /*let clientID = "[CLIENT ID]"; (I could not make this line work)*/
    let endpoint = 'https://api.unsplash.com/photos/random?client_id=[CLIENT ID]&orientation=landscape&query=architecture';
    let imageElement = document.querySelector("#unsplashImage");
    let imageLink = document.querySelector("#imageLink");
    let creator = document.querySelector("#creator")
    fetch(endpoint)
      .then((response) => response.json())
      .then((jsonData) => {
        imageElement.src = jsonData.urls.full;
        imageLink.setAttribute("href", jsonData.links.html);
        creator.innerText = jsonData.user.name;
        creator.setAttribute("href", jsonData.user.portfolio_url);
      })
        .catch((error) => {
        console.log("Error: " + error);
      });
  </script>
</body>

</html>

```

---

<div class="post-metadata">

### Author: ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)
#### Post date: [April 17, 2023, 3:27pm UTC](https://forum.kirupa.com/t/display-a-random-image-using-the-unsplash-api/653866/3 "2023-04-17T15:27:01Z")

</div>

Hi @BJJB - welcome to the forums 😀

Glad you got it working! Would you mind posting your version as shown in the video? Having the API key embedded in the URL is the end result of what I was showcasing in the video by having the clientID be stored in a separate variable.

---

<div class="post-metadata">

### Author: ![BJJB](https://avatars.discourse-cdn.com/v4/letter/b/bc79bd/32.png) [@BJJB](https://forum.kirupa.com/u/BJJB)
#### Post date: [April 17, 2023, 6:44pm UTC](https://forum.kirupa.com/t/display-a-random-image-using-the-unsplash-api/653866/4 "2023-04-17T18:44:36Z")

</div>

Here is my code with an Unsplash API key. Note I could not get the "let clientID = " line to work as described in your YouTube example, so I included the API key in the URL on the next line “let endpoint =” which seems to work. See the commented text.

```auto
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Display Random Image</title>
</head>
<style>
  body {
    background-color: yellow;
    text-align: center;
    font-family: sans-serif;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  #unsplashImage {
    max-height: 500px;
    border: 20px solid black;
    transform: rotate(3deg);
  }

  h1 {
    font-size: 56px;
  }

  .imageDetails {
    background-color: black;
    margin-top: 50px;
    padding: 10px;
    color: white;
    text-decoration: none;
    font-weight: bold;
    width: fit-content;
  }

  .imageDetails a {
    color: #FFF;
  }

  .imageDetails a:hover {
    color: yellow;
  }
</style>

<body>
  <h1>Random Unsplash Image</h1>
  <div class="imageContainer">
    <a id="imageLink" href="#">
      <img alt="" id="unsplashImage" />
    </a>
  </div>
  <p class="imageDetails">Photo by <a id="creator" href="#">NAME</a> on <a href="https://www.unsplash.com">Unsplash</a>!</p>
  <script>
    /*let clientID = "---";*/
    let endpoint = 'https://api.unsplash.com/photos/random?client_id=---&orientation=landscape&query=architecture';
    let imageElement = document.querySelector("#unsplashImage");
    let imageLink = document.querySelector("#imageLink");
    let creator = document.querySelector("#creator")
    fetch(endpoint)
      .then((response) => response.json())
      .then((jsonData) => {
        imageElement.src = jsonData.urls.full;
        imageLink.setAttribute("href", jsonData.links.html);
        creator.innerText = jsonData.user.name;
        creator.setAttribute("href", jsonData.user.portfolio_url);
      })
        .catch((error) => {
        console.log("Error: " + error);
      });
  </script>
</body>

</html>

```

---

<div class="post-metadata">

### Author: ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)
#### Post date: [April 17, 2023, 7:01pm UTC](https://forum.kirupa.com/t/display-a-random-image-using-the-unsplash-api/653866/5 "2023-04-17T19:01:32Z")

</div>

Oh, sorry! I didn’t mean for you to post your clientID itself into the code. I edited your post to remove it before it gets indexed forever 🙂

What I meant was what your code looked like when you had the `clientID` variable passed into the `endpoint` variable. I wonder if there was a syntax error that prevented it from working.

---

<div class="post-metadata">

### Author: ![BJJB](https://avatars.discourse-cdn.com/v4/letter/b/bc79bd/32.png) [@BJJB](https://forum.kirupa.com/u/BJJB)
#### Post date: [April 17, 2023, 11:19pm UTC](https://forum.kirupa.com/t/display-a-random-image-using-the-unsplash-api/653866/6 "2023-04-17T23:19:22Z")

</div>

No worries, that Client ID is one someone posted on Git or Stack that still works.  
The following is what I get when I used the exact method from your YouTube example (basically no change from the starting point you provided on Code Pen):

 ![Screen Shot 2023-04-17 at 4.07.51 PM](https://canada1.discourse-cdn.com/flex011/uploads/kirupa/original/3X/e/8/e87490aa9fce8de4ab651c2fb61aaa86f18ebea8.png)  
this is the non-functional code:

```auto
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Display Random Image</title>
</head>
<style>
  body {
    background-color: yellow;
    text-align: center;
    font-family: sans-serif;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  #unsplashImage {
    max-height: 500px;
    border: 20px solid black;
    transform: rotate(3deg);
  }

  h1 {
    font-size: 56px;
  }

  .imageDetails {
    background-color: black;
    margin-top: 50px;
    padding: 10px;
    color: white;
    text-decoration: none;
    font-weight: bold;
    width: fit-content;
  }

  .imageDetails a {
    color: #FFF;
  }

  .imageDetails a:hover {
    color: yellow;
  }
</style>

<body>
  <h1>Random Unsplash Image</h1>
  <div class="imageContainer">
    <a id="imageLink" href="#">
      <img alt="" id="unsplashImage" />
    </a>
  </div>
  <p class="imageDetails">Photo by <a id="creator" href="#">NAME</a> on <a href="https://www.unsplash.com">Unsplash</a>!</p>
  <script>
    let clientID = "[CLIENT ID]";
    let endpoint = 'https://api.unsplash.com/photos/random?query=architecture&orientation=landscape';
    let imageElement = document.querySelector("#unsplashImage");
    let imageLink = document.querySelector("#imageLink");
    let creator = document.querySelector("#creator")
    fetch(endpoint)
      .then((response) => response.json())
      .then((jsonData) => {
        imageElement.src = jsonData.urls.full;
        imageLink.setAttribute("href", jsonData.links.html);
        creator.innerText = jsonData.user.name;
        creator.setAttribute("href", jsonData.user.portfolio_url);
      })
        .catch((error) => {
        console.log("Error: " + error);
      });
  </script>
</body>

</html>

```

---

<div class="post-metadata">

### Author: ![BJJB](https://avatars.discourse-cdn.com/v4/letter/b/bc79bd/32.png) [@BJJB](https://forum.kirupa.com/u/BJJB)
#### Post date: [April 17, 2023, 11:25pm UTC](https://forum.kirupa.com/t/display-a-random-image-using-the-unsplash-api/653866/7 "2023-04-17T23:25:15Z")

</div>

this what the working example looks like (client ID redacted):

 ![Screen Shot 2023-04-17 at 4.21.48 PM](https://canada1.discourse-cdn.com/flex011/uploads/kirupa/original/3X/d/5/d5772242df9d7ecc71b74b5c09f1694076e4b62f.jpeg)

```auto
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Display Random Image</title>
</head>
<style>
  body {
    background-color: yellow;
    text-align: center;
    font-family: sans-serif;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  #unsplashImage {
    max-height: 500px;
    border: 20px solid black;
    transform: rotate(3deg);
  }

  h1 {
    font-size: 56px;
  }

  .imageDetails {
    background-color: black;
    margin-top: 50px;
    padding: 10px;
    color: white;
    text-decoration: none;
    font-weight: bold;
    width: fit-content;
  }

  .imageDetails a {
    color: #FFF;
  }

  .imageDetails a:hover {
    color: yellow;
  }
</style>

<body>
  <h1>Random Unsplash Image</h1>
  <div class="imageContainer">
    <a id="imageLink" href="#">
      <img alt="" id="unsplashImage" />
    </a>
  </div>
  <p class="imageDetails">Photo by <a id="creator" href="#">NAME</a> on <a href="https://www.unsplash.com">Unsplash</a>!</p>
  <script>
    /*let clientID = "[CLIENT ID]";*/
    let endpoint = 'https://api.unsplash.com/photos/random?query=architecture&orientation=landscape&client_id=[CLIENT ID]';
    let imageElement = document.querySelector("#unsplashImage");
    let imageLink = document.querySelector("#imageLink");
    let creator = document.querySelector("#creator")
    fetch(endpoint)
      .then((response) => response.json())
      .then((jsonData) => {
        imageElement.src = jsonData.urls.full;
        imageLink.setAttribute("href", jsonData.links.html);
        creator.innerText = jsonData.user.name;
        creator.setAttribute("href", jsonData.user.portfolio_url);
      })
        .catch((error) => {
        console.log("Error: " + error);
      });
  </script>
</body>

</html>

```

---

<div class="post-metadata">

### Author: ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)
#### Post date: [April 18, 2023, 1:08am UTC](https://forum.kirupa.com/t/display-a-random-image-using-the-unsplash-api/653866/8 "2023-04-18T01:08:20Z")

</div>

Ah! I see what is going on here. You need to insert the API key into the contents of the URL stored by the `endpoint` variable! You can see me doing this at the 8:35 mark in the video:

[![](https://canada1.discourse-cdn.com/flex011/uploads/kirupa/original/3X/3/0/3095ad4a080c650e2eee8873ebb2ecbd6d73e612.jpeg "Displaying a Random Image Using the Unsplash API") ](https://www.youtube.com/watch?v=e8p1zSNmK7Q&t=517s)

The end result should still be the same as what you have with the API key manually inserted, so neither approach is better or worse. I was just curious, for it could have been that my video was wrong!

🙃

---

<div class="post-metadata">

### Author: ![BJJB](https://avatars.discourse-cdn.com/v4/letter/b/bc79bd/32.png) [@BJJB](https://forum.kirupa.com/u/BJJB)
#### Post date: [April 18, 2023, 1:47am UTC](https://forum.kirupa.com/t/display-a-random-image-using-the-unsplash-api/653866/9 "2023-04-18T01:47:47Z")

</div>

My prior post wasn’t correct, the non-functioning code I used was:

```auto
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Display Random Image</title>
</head>
<style>
  body {
    background-color: yellow;
    text-align: center;
    font-family: sans-serif;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  #unsplashImage {
    max-height: 500px;
    border: 20px solid black;
    transform: rotate(3deg);
  }

  h1 {
    font-size: 56px;
  }

  .imageDetails {
    background-color: black;
    margin-top: 50px;
    padding: 10px;
    color: white;
    text-decoration: none;
    font-weight: bold;
    width: fit-content;
  }

  .imageDetails a {
    color: #FFF;
  }

  .imageDetails a:hover {
    color: yellow;
  }
</style>

<body>
  <h1>Random Unsplash Image</h1>
  <div class="imageContainer">
    <a id="imageLink" href="#">
      <img alt="" id="unsplashImage" />
    </a>
  </div>
  <p class="imageDetails">Photo by <a id="creator" href="#">NAME</a> on <a href="https://www.unsplash.com">Unsplash</a>!</p>
  <script>
    let clientID = "[CLIENT ID]";
    let endpoint = 'https://api.unsplash.com/photos/?client_id=${clientID}';
    let imageElement = document.querySelector("#unsplashImage");
    let imageLink = document.querySelector("#imageLink");
    let creator = document.querySelector("#creator")
    fetch(endpoint)
      .then((response) => response.json())
      .then((jsonData) => {
        imageElement.src = jsonData.urls.full;
        imageLink.setAttribute("href", jsonData.links.html);
        creator.innerText = jsonData.user.name;
        creator.setAttribute("href", jsonData.user.portfolio_url);
      })
        .catch((error) => {
        console.log("Error: " + error);
      });
  </script>
</body>

</html>

```

---

<div class="post-metadata">

### Author: ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)
#### Post date: [April 18, 2023, 2:05am UTC](https://forum.kirupa.com/t/display-a-random-image-using-the-unsplash-api/653866/10 "2023-04-18T02:05:57Z")

</div>

Oh! I found the issue. It is a bit subtle. We are using the string literal syntax to place the `clientID` value into the URL we are creating with `endpoint`.

To do that, we need to wrap our string value for endpoing in a backtick character: ` instead of a quotation mark: " as shown below:

```auto
let endpoint = `https://api.unsplash.com/photos/random/?client_id=${clientID}`;

```

I describe this in more detail here:

> **[Combining Strings and Variables](https://www.kirupa.com/javascript/combining_strings_variables.htm)**
>
> Learn how to combine strings made up of static text and variable values using both the concatenation and template literal approaches.

Here is the full code:

```auto
let clientID = "IvbMghKxN0pdegdJGnZZ9rSLThS9qdWn5lzg8abY5NY";
let endpoint = `https://api.unsplash.com/photos/random/?client_id=${clientID}`;

let imageElement = document.querySelector("#unsplashImage");
let imageLink = document.querySelector("#imageLink");
let creator = document.querySelector("#creator")
fetch(endpoint)
  .then((response) => response.json())
  .then((jsonData) => {
    imageElement.src = jsonData.urls.full;
    imageLink.setAttribute("href", jsonData.links.html);
    creator.innerText = jsonData.user.name;
    creator.setAttribute("href", jsonData.user.portfolio_url);
  })
    .catch((error) => {
    console.log("Error: " + error);
  });

```

---

<div class="post-metadata">

### Author: ![BJJB](https://avatars.discourse-cdn.com/v4/letter/b/bc79bd/32.png) [@BJJB](https://forum.kirupa.com/u/BJJB)
#### Post date: [April 18, 2023, 2:30am UTC](https://forum.kirupa.com/t/display-a-random-image-using-the-unsplash-api/653866/11 "2023-04-18T02:30:03Z")

</div>

that did it! 👍. part of the issue was my browser originally showed the video at low res 360P so ` looks like ’ and { looks like [ or ( etc. Thank you.

---

<div class="post-metadata">

### Author: ![davidoliver](https://avatars.discourse-cdn.com/v4/letter/d/5e9695/32.png) [@davidoliver](https://forum.kirupa.com/u/davidoliver)
#### Post date: [April 20, 2023, 4:55am UTC](https://forum.kirupa.com/t/display-a-random-image-using-the-unsplash-api/653866/13 "2023-04-20T04:55:12Z")

</div>

To display a random image using the Unsplash API, you can follow these steps:

Go to the Unsplash website and sign up for an API key.

Once you have your API key, you can use it to make requests to the Unsplash API. In this case, you will use the following endpoint to retrieve a random image: [https://api.unsplash.com/photos/random](https://api.unsplash.com/photos/random)

You can make a GET request to this endpoint using a programming language of your choice. Here is an example using JavaScript and the Fetch API:

javascript  
Copy code  
fetch(‘[https://api.unsplash.com/photos/random?client\_id=YOUR\_ACCESS\_KEY](https://api.unsplash.com/photos/random?client_id=YOUR_ACCESS_KEY)’)  
.then(response =\> response.json())  
.then(data =\> {  
const imageUrl = data.urls.regular;  
const imageAlt = data.alt\_description;  
const imageElement = document.createElement(‘img’);  
imageElement.src = imageUrl;  
imageElement.alt = imageAlt;  
document.body.appendChild(imageElement);  
})  
.catch(error =\> {  
console.error(‘Error fetching random image’, error);  
});  
In this example, we are making a request to the random image endpoint and passing our API key as a query parameter. When we receive a response, we extract the image URL and alt description from the JSON data and create an img element with the image source and alt attributes. Finally, we append the img element to the body of the document.

You can customize the request by adding additional parameters to the endpoint URL, such as orientation, query, or collections, to retrieve images that match specific criteria.
