How to Send an Image as a Response via AWS Lambda and API Gateway?

Adil Ilhan
Feb 21, 2018 · 2 min read

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,
“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?


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.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade