How to Send an Image as a Response via AWS Lambda and API Gateway?
Sending an image as a response via AWS Lambda and API Gateway is not that straightforward.
I assume that you already have a connection between Lambda and API Gateway and you use LAMBDA_PROXY in the Integration Request.
In this blog post, I’ll walk you through the 3-step process of generating the image files. The example code is:
exports.handler = (event, context, callback) => {
const fs = require(‘fs’);
var image = fs.readFileSync(‘./car.png’);
var response = {
statusCode: 200,
headers:
{
“Content-Type”: “image/png”
},
body: image.toString(‘base64’),
isBase64Encoded: true
};
callback(null, response);
}
You must convert your image to a base64 string. So, you will send your image as a base64 string actually. Yeah, that sounds weird.
That’s all of it?
Nope.
You send the image as a base64 string. API Gateway must convert it from base64 to binary. You must add CONVERT_TO_BINARY to contentHandling path.
aws apigateway update-integration-response \
— rest-api-id XXX \
— resource-id YYY \
— http-method GET \
— status-code 200 \
— patch-operations ‘[{“op” : “replace”, “path” : “/contentHandling”, “value” : “CONVERT_TO_BINARY”}]’
And… You must add */* to binaryMediaTypes. Go to your API’s settings page:
You can edit the binaryMediaTypes via CLI as well:
aws apigateway update-rest-api — rest-api-id XXX — patch-operations ‘[{“op” : “replace”, “path” : “/binaryMediaTypes/*~1*”, “value” : “*~1*”}]’
If you want to add / to binaryMediaTypes then you must use ~1 instead of / while using CLI.
That’s it. Don’t forget to redeploy your API Gateway.