Display a Random Image Using the Unsplash API

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

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.

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

Hi @BJJB - welcome to the forums :grinning:

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.

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.

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

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 :slight_smile:

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.

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):


this is the non-functional code:

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

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

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

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:

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!

:upside_down_face:

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

<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>
1 Like

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:

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

I describe this in more detail here:

Here is the full code:

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);
  });

that did it! :+1:. 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.

1 Like

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

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’)
.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.

1 Like