I just implemented a test project for returning binary data (PDFs in my case). It even works to request directly from the browser without setting Accept header.
Sample code here:
The only manual change needed is to add to binary Media Types in API Gateway console.
The manual steps described by krisgholson was not needed for me.
Thank you so much for providing this example. I spend a few hours yesterday and was not able to figure it out. What I was missing was “isBase64Encoded” in the response and adding * / * to the binary media type on the API gateway.
I have to add image/png to the request header to get a valid png file. If I add * / * then I get a file slight larger and it is no longer a valid png file.
I had some serious fun trying to get this to work, when there were multiple media types in the header which for me I could not control AWS state it should pick the first one. This does not seem to work when configuring the relevant binaryType in the UI.
If anyone else comes across this and struggles, my solution for now at least was to create a local plugin that sets the CONVERT_TO_BINARY on the Integration Response (means I could not use Lambda Proxy Integration) and re-deploy the API.
Bit slow on the reply for this one, I would separate this out into its own plugin just not sure it is 100% the correct implementation. Mainly due to the having to wait 1 minute as otherwise AWS moans about API deployment limits.
That said I will try it without the wait and do some testing with Serverless 1.6.1 and see if it is all good. If so will tidy it up and release as a separate plugin.
Could you share your python in which you managed to return an image through AWS lambda? I would like to perform this action using lambda via api gateway without redirects (returning 200 code).
@bni
Thanks for the code. I am able to get the object back in binary format. I am able to test this in API Gateway. However the browser fails to load the PDF. I have added additional headers look at other blogs but it did not help. Can someone help?
The additional headers are:
“Expires” : “0”,
“Cache-Control” : “must-revalidate, post-check=0, pre-check=0”,
“Pragma” : “public”,
“Content-Length” : data.size