Fetching and Displaying Images with the Fetch API

•

Fri Mar 31 2023

•

4 min read

Images are an essential part of a web design that not only makes the website more visually appealing but also help us convey our message effectively.

Fetching Images

To fetch image data from a server, we first create a new Request object and pass in the URL of the image we want to fetch. Then, use the fetch() method to send the request and retrieve the response.

Once you have the response, you can use the blob() or arrayBuffer() methods to extract the image data, depending on the format of the image data. For example, if the image data is in blob format, use the following code to extract it:

js
fetch('API')
.then(response => response.blob())
.then(blob => {
// Do something with the image data
});

Note that there are various methods for formatting image data, such as JSON or base64 encoding. You may need to modify your code depending on the format used.

Fetch and display images

Let’s now look at how to fetch an image from an API using Fetch API. In the process, we will also focus on converting the image from a blob and then displaying it to the user. Fetch an image and display it.

Step #1: Choose an API

Let’s find an API that provides access to image data. For this example, we'll use the Any Anime API from Rapid API Hub. This API provides access to a large collection of high-quality photos of anime profile pictures. So please go ahead and subscribe to the API.

Loading component...

Step #2: Create an HTML file

Create an HTML file with a container element where you want to display the image(s).

html
<!DOCTYPE html>
<html>
<head>
<title>Fetching and Displaying Images</title>
</head>
<body>
<div id="image-container"></div>
<script src="script.js"></script>
</body>
</html>

Step #3: Call API to retrieve images

Create a JavaScript file (e.g. script.js) and write a function that uses the Fetch API to retrieve image data from the API. For the Any Anime API, you can make a GET request to the /img endpoint to retrieve images:

js
function fetchImage() {
const apiKey = 'YOUR_API_KEY';
fetch('https://any-anime.p.rapidapi.com/anime/img', {
method: 'GET',
headers: {
'x-rapidapi-key': apiKey,
"x-rapidapi-host": "any-anime.p.rapidapi.com"
}
})
.then(response => response.blob())
.then(data => {
// Do something with the image data
})
.catch(error => console.error(error));
}

Make sure to replace YOUR_API_KEY with your actual API key.

Step #4: Extract the image URL

Extract the image URL from the response data and create an <img> tag with the src attribute set to the image URL. Append the <img> tag to the container element.

Since the response we will receive is a stream, we need to convert it into an image link that we can use to display the image. We can do this by passing the blob to the createObjectURL method of the URL interface.

js
function fetchImage() {
const apiKey = 'YOUR_API_KEY';
fetch('https://any-anime.p.rapidapi.com/anime/img', {
method: 'GET',
headers: {
'x-rapidapi-key': apiKey,
"x-rapidapi-host": "any-anime.p.rapidapi.com"
}
})
.then((response) => response.blob())
.then((blob) => {
const imageUrl = URL.createObjectURL(blob);
const imageElement = document.createElement("img");
imageElement.src = imageUrl;
const container = document.getElementById("image-container");
container.appendChild(imageElement);
});
}

Step #5: Retrieve and display the image

Call the fetchImage() function to retrieve and display the image. You can do this by adding an event listener to a button or by calling the function on page load. For example:

js
const button = document.getElementById('fetch-image-button');
button.addEventListener('click', fetchImage);

You can find the complete code below.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Fetch API Image Example</title>
</head>
<body>
<h1>Fetch API Image Example</h1>
<button id="fetch-image-button">Fetch Image</button>
<div id="image-container"></div>
<script>
function fetchImage() {
const apiKey = "Your-apiKey";
fetch("https://any-anime.p.rapidapi.com/anime/img", {
method: "GET",
headers: {
"x-rapidapi-key": apiKey,
"x-rapidapi-host": "any-anime.p.rapidapi.com",
},
})
.then((response) => response.blob())
.then((blob) => {
const imageUrl = URL.createObjectURL(blob);
const imageElement = document.createElement("img");
imageElement.src = imageUrl;
const container = document.getElementById("image-container");
container.appendChild(imageElement);
})
.catch((error) => console.error(error));
}
const button = document.getElementById("fetch-image-button");
button.addEventListener("click", fetchImage);
</script>
</body>
</html>

Wrap up

Requesting images from a REST API using Fetch can be challenging. But if you follow the following four simple steps, you can easily take care of it:

  1. Request the API using Fetch
  2. Convert response to blob
  3. Convert the blob response to URL to display the image
  4. Add the URL to the image tag