Reteurn binary content from lambda through api gateway

I want to return an image from lambda. AWS API gateway assume that returned content is text and re-encodes it using utf-8, which corrupts response with binary content. There are two writeups, one by AWS and one by Serverless about how to turn this feature off.

However, it does not work. Here’s my serverless.yml

name: aws
runtime: nodejs12.x
stage: dev
region: us-east-1
memorySize: 128
role: arn:aws:iam::xxxxxxxxxxxx:role/xxxxxxxxxxxxxxxxxx
ENV_NAME: develop
- ‘image/webp’
- ‘/

The browser asks for image/webp and I return and image file with content type image/webp. Still the API gateway tries to encode it as utf-8, adding bytes infront
of some other bytes. I also tried to remove ‘image/webp’ from serverless.yml leaving only ‘/’, but it did not help.

After deploying using npm run deploy-develop this is how it looks in AWS console

GET Lambda 1.0 (explicit response format)

If anyone is having this issue, in addition to declaring the binaryMediaTypes in yml files, the lambda response must also contain a header with same content-type, the body in base64 format and isBase64Encoded: true;

  statusCode: 200,
  headers: {
    'Content-Type': 'image/png'
  body: result.Body.toString('base64'),
  isBase64Encoded: true