Here i share how you preview image using API Gateway, S3 and Lambda Function. This function build on Node.js 18.x
Create A Lambda Function
Give a function name, Runtime, Architecture.
After creating the function. Need to Add trigger with S3 and API Gateway
Add Trigger at S3 and API Gateways
Here 1st i adding S3 as a trigger with this function.
Give the selected bucker name and event type. After that click Add.
2nd adding the API Gateway
At API Gateway, create intent as a create a new API
, Set API Type is HTTP API
, At Security, Select Open. Then Click Add Button.
Trigger configuration done.
Adding Code
Now Add Code at index.js
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
exports.handler = async (event, context) => {
const bucketName = '<BUCKET_NAME>';
const imageKey = '<IMAGE_KEY/NAME>'; // Replace 'your-image-key.jpg' with your actual image key
try {
const params = {
Bucket: bucketName,
Key: imageKey,
};
const s3Object = await s3.getObject(params).promise();
if (!s3Object || !s3Object.Body) {
return {
statusCode: 404,
body: JSON.stringify({ message: 'Image not found' })
};
}
const imageData = Buffer.from(s3Object.Body, 'binary').toString('base64') ;
return {
statusCode: 200,
headers: {
'Content-Type': 'image/jpeg'
},
isBase64Encoded: true,
body: imageData
};
} catch (error) {
return {
statusCode: 500,
body: JSON.stringify(error.message)
};
}
};
Here a a require package needed. But you can’t add node_modules
at Lambda function. Need to create a layer.
Goto Lambda Function > Layer (At Additional resources)
Creating a layer
Give a function name, upload the zip file, select the Compatible architectures and select the compatible runtimes. Then Create Layer.
After that, you need to add that layer to lambda function.
Adding Layer
At the Code Section, the bottom you find the Layers section.
Click Add a layer
Select Custom Layers, there it shows your created layers. Add that layer then click Add Button.
Then 1 layer has added.
Now goto Configuration > Click Triggers
Here you see a API Gateway endpoint and S3 bucket
When you click the link, you see the image,
Happy Coding…