How to get an image from API with JavaScript Fetch API?

Sometimes, we want to get an image from API with JavaScript Fetch API.

In this article, we’ll look at how to get an image from API with JavaScript Fetch API.

How to get an image from API with JavaScript Fetch API?

To get an image from API with JavaScript Fetch API, we can call the response’s blob method and use the FileReader to read the file into a base64 string.

For instance, we write:

const imageUrl = "https://picsum.photos/200/300";

const reader = new FileReader();
reader.onloadend = () => {
  const base64data = reader.result;                
  console.log(base64data);
}

(async () => {
  const response = await fetch(imageUrl)
  const imageBlob = await response.blob()
  reader.readAsDataURL(imageBlob);  
})()

We create the FileReader instance and set the onloadend property to a function that gets the base64 string from reader.result.

Next, we call fetch with the imageUrl to make a GET request to the image URL.

Then we call response.blob to return a promise with the image blob object.

Finally, we call readAsDataURL with imageBlob to read it into a base64 string.

Conclusion

To get an image from API with JavaScript Fetch API, we can call the response’s blob method and use the FileReader to read the file into a base64 string.