Binary responses with Serverless Framework and API Gateway

Michael Marner
Nov 3, 2017 · 2 min read

Today we’re looking at how to send binary data to clients using Serverless Framework and AWS API Gateway.

Image for post
Image for post
Jellyfish are cool. Photo by 贝莉儿 NG on Unsplash

We’re big fans of serverless technologies and the Serverless Framework if the use case supports it. While API Gateway supports binary data, there’s a bit of work involved to configure Serverless.

An example: Lambda based on-the-fly image processing

Suppose you want to build an image resizing service using Lambda. You’d have an API endpoint that accepts an image source url, and the desired width and height as url query parameters. The lambda would process the image and return it in the response body.

The lambda function is actually pretty simple:

This example is using Typescript, error checking is omitted for brevity, and we’re using Jimp to do the image processing. Important parts:

  • Output the binary data as a base64 encoded string in the response body
  • Set the Content-Type header appropriately.

Unfortunately if you deploy this you won’t get the desired result. You’ll get the base64 encoded string, when what you really want is the binary data. There are two parts to the solution: allowing binary data for our content type, and telling Lambda to convert the base64 string to raw binary.

Enabling Binary Output for your content-type

We’ll use a plugin for configuring binary output for specificContent-Types.

We then need to modify our serverless.yml

As you can see, we just list the mime types that should be allowed as binary. You can also use wildcards such as */* . After a deployment you can see in the AWS console that the binary type is enabled:

Image for post
Image for post

Convert the base64 output to binary

That’s half the work done. We now need to tell AWS to convert the base64 string into raw binary data before sending it through to the client. We do this with another, painfully similarly named plugin.

And configure serverless.yml , it will end up looking something like this:

The key changes are:

  • Add the second plugin
  • Set contentHandling: CONVERT_TO_BINARY in our event configuration

And that’s it. This technique works with any binary data format, you just need to enable binary for that mime type.

Happy coding!

NextFaze

Smart developers for smart ideas

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store