Fetching and Displaying Images with the Fetch API (2024)

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
Fetching and Displaying Images with the Fetch API (2024)

FAQs

How to display an image from API response? ›

How to Dynamically Display Images from an API Response in Angular
  1. Step 1: Creating the Image Service. We'll begin by setting up a service to handle the HTTP request for the image URL. ...
  2. Step 2: Fetching the Image URL in the Component. ...
  3. Step 3: Displaying the Image. ...
  4. Step 4: HttpClientModule Configuration.
Oct 24, 2023

How to fetch images using Fetch API? ›

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. }); Note that there are various methods for formatting image data, such as JSON or base64 encoding.

How do I get responses from Fetch API? ›

Here's a simple example of a basic fetch request: fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); In this example, we're fetching data from https://api.example.com/data .

How to fetch data from API and display? ›

Ans.To fetch data from an API and display it in JS, you need to define a const data and store it in JSON by await response. json() method. When we get the data from API by fetch() method in the data variable; pass it to the function which will show the data fetched.

How to display image from API in React JS using Fetch? ›

The above code example shows how to fetch an image in ReactJS using the Fetch API. In the example, the URL of the image is set in the “imageUrl” variable. Then, a new “fetch” object is created with the URL of the image. Finally, the “fetch” function is called to fetch the image from the server.

How do I see API responses? ›

An API response consists of the response body, headers, cookies, and the HTTP status code. You can view details about the response, including test results, network information, response size, response time, and security warnings. You can also save responses as examples or files.

What is the difference between API and fetch? ›

FETCH API: The FETCH API is a modern way to make HTTP requests in JavaScript. It provides a more powerful and flexible way to interact with APIs. Unlike the GET method, FETCH can be used to make various types of HTTP requests, including POST, PUT, DELETE, and more.

Can you upload pictures on Fetch? ›

Fetch can only help transfer pictures from your Macintosh to a web server; it cannot host pictures for you. Fetch Softworks is not a service provider. To upload pictures for use on eBay, follow these steps: Create a digital picture of your item.

How to extract data from Fetch API? ›

To Get data using the Fetch API in JavaScript, we use the fetch() function with the URL of the resource we want to fetch. By default, the fetch method makes the Get request.

What is the purpose of Fetch API? ›

The Fetch API provides an interface for fetching resources (including across the network). It is a more powerful and flexible replacement for XMLHttpRequest .

How do I send data through Fetch API? ›

How to use Fetch API with the PUT method
  1. Prepare the data you want to update. Before making the API request, you need to prepare the data you want to send to the server. ...
  2. Convert the data to a JSON string. Before sending the data to the server, we need to convert it into a JSON string. ...
  3. Use the Fetch API to make the request.
Apr 26, 2023

How do I pull all data from an API? ›

How to use data extraction API?
  1. Step 1 - Kickstart your journey by signing up! ...
  2. Step 2 - Go through API documentation. ...
  3. Step 3 - Set up the platform. ...
  4. Step 4 - Send an API request. ...
  5. Step 5 - API authentication. ...
  6. Step 6 - Parameterizing requests. ...
  7. Step 7 - Errors handling. ...
  8. Step 8 - Extraction and integration.

How can I fetch data from API faster? ›

  1. #1. Cache Requests.
  2. #2. Prevent Abuse.
  3. #3. Use PATCH.
  4. #4. Limit Payloads.
  5. #5. Faster Network.
  6. Ensuring Performance With LoadNinja.
  7. Small Steps to Reliable Performance.

How does API fetch data from database? ›

The main API here is the Fetch API. This enables JavaScript running in a page to make an HTTP request to a server to retrieve specific resources. When the server provides them, the JavaScript can use the data to update the page, typically by using DOM manipulation APIs.

How do I show an image in Postman response? ›

Place your image file (e.g., 'image. jpg') inside the 'images' directory. Open your terminal, navigate to the project directory, and install the required dependencies.

How do I display an image from a URL in React? ›

Now that we have a basic understanding of React components, let's talk about how to display an image. In HTML, we use the <img> tag to display an image. The source of the image is defined with the src attribute. In React, we use the same <img> tag, and we can set the src attribute to a URL just like we would in HTML.

How do I send an image using API? ›

The steps to upload the image to the server, as shown in image #5, are the following:
  1. Select: Body.
  2. Select: Binary.
  3. Upload the desired image.
  4. Click on the Send button.
  5. Copy what appears in object_id.
Aug 2, 2022

How do I send image data in response? ›

Send the URI of the image in JSON, and let the front-end call this to display the image. Send the image data using some form of encoding like Base64 as part of JSON.

Top Articles
Latest Posts
Article information

Author: Fredrick Kertzmann

Last Updated:

Views: 5410

Rating: 4.6 / 5 (66 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Fredrick Kertzmann

Birthday: 2000-04-29

Address: Apt. 203 613 Huels Gateway, Ralphtown, LA 40204

Phone: +2135150832870

Job: Regional Design Producer

Hobby: Nordic skating, Lacemaking, Mountain biking, Rowing, Gardening, Water sports, role-playing games

Introduction: My name is Fredrick Kertzmann, I am a gleaming, encouraging, inexpensive, thankful, tender, quaint, precious person who loves writing and wants to share my knowledge and understanding with you.