In this post, I am gonna walk you through a small project that I build for fun as an example to better explain.
๐ Introduction
I wanted to build an API that would give me a random quote as an image every time I make a GET request. Now I was making a personal notion dashboard for tracking my productivity and I thought it would be nice to see a new motivational quote every time I open notion.
โก Install the required dependencies
If you are following through, do install these dependencies
express
- required to serve the imageinspirational-quotes
- this library provides with a random inspirational quotetext-to-image
- helps convert the quote into an imageimage-data-uri
- format the image data
Run this to install all the dependencies
npm i express inspirational-quotes text-to-image image-data-uri
๐ Driver Code
const express = require('express');
const quote = require('inspirational-quotes');
const textToImage = require('text-to-image');
const ImageDataURI = require('image-data-uri');
const app = express();
app.get('/', async (req,res) => {
try {
res.setHeader("content-type", "image/png");
res.setHeader("Cache-Control", "no-cache");
const img = await textToImage.generate(quote.getRandomQuote(), {
maxWidth: 800,
fontSize: 28,
fontWeight: 'bold',
textAlign: 'center',
textColor: '#11324D',
margin: 40
});
return res.send(ImageDataURI.decode(img).dataBuffer);
} catch (error) {
return res.send(error);
}
})
app.listen(process.env.PORT);
You can check the GitHub Repo ๐ฆ. Feel free to open an issue for any ideas or doubt.