Home > database >  How to send image as a REST API response? What guidelines to follow?
How to send image as a REST API response? What guidelines to follow?

Time:09-21

I am making an application using Node.js and Express. I am able to save files to the server using multer, however while sending responses I have two options,

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

Since I am new to web development, I am confused as to which option to use. Some people have said that the first option requires two API calls, so can be slow. While I have also heard that the second option will take up more memory resources.

What other things should I consider while choosing, and is there any other way of sending images to the client side?

CodePudding user response:

Option 1

Is less complex since no conversion is needed. These 2 API calls won't slow you down. The image size is way more important!!.. The file can be stored/accessed directly on filesystem and served from there. Also a filedownload is implemented in a short period of time. Also the base64 encoding makes the file roughly ~33% (!!) bigger what has a huge impact on large files regarding performance.

Option 2

Base 64 is more secure as nobody can link to your website as described here . You only need to use base64 for security reasons OR if you have to transfer the image data as string if you cannot transfer it as binary.

Use Case
  • If this is your private non-productive project just try out both and use the one you like. In the end you are learning something.. It's only important to stay consistent !
  • If one option fits better to you, just implement it the way you like. You can always refactor a given part of the application later when you may have more experience or when the core parts of your application are finished. Sometimes, after working a while with one of the techniques it gets more clear which approach to use.
  • For learning it's sometimes better to go ahead, and implement something what works and start to refactor as problems occur. Rather than overengineering small
  • Related