Engineer bro!

Fri Mar 04 2022 (3 months ago)

Engineer by mistake!

I am a software engineer by passion

How to use the free image API of Imgur with NodeJs?

Almost all applications either small or big needs some sort of service to host the image. Imgur is one of those services that provide image hosting for free. We can also use its API to programmatically upload the images. In this article, we'll see how can we upload the image programmatically using Imgur APIs.

Table of contents

Pricing of Imgur

Imgur is paid and free also, for more information you can go https://rapidapi.com/imgur/api/imgur-9/pricing

Getting API credentials

In order to use the APIs of Imgur, we need their API credentials.

What is API credential

The first step in this process is signup. Once you signup, then you can go to https://imgur.com/account/settings/apps and copy Client ID.

Using it with NodeJs

Now you have Client ID and NodeJs installed, we can use this to access the API of Imgur.

export function uploadImage(path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, { encoding: "base64" }, (err, data) => {
      if (err) {
        reject(err);
        return;
      }
      const options = {
        method: "POST",
        url: "https://api.imgur.com/3/image",
        headers: {
          authorization: "Client-ID ....",
        },
        data: {
          image: data,
        },
      };
      axios
        .request(options)
        .then(function (response) {
          resolve(response.data);
        })
        .catch(function (error) {
          reject(error.response.data);
        });
    });
  });
}

uploadImage("./img.png")
  .then((res) => console.log(res))
  .catch((err) => console.log(err));

You can use the above function in NodeJs to read the local image file and upload it on Imgur. We need to send the file in base64 format. So, encode the data into base64 format before uploading.

If you know any better service, then you can suggest in the comments below.

Thank You ❤️

JavaScriptNodeJsImgurSoftware Engineering

Comments (0)

Discussions (0)


© 2021 dsabyte. All rights reserved