AWS API Gateway with Lambda proxy always produces base64 string response

做~自己de王妃 提交于 2020-01-22 12:28:47

问题


I'm using API Gateway Lambda proxy integration and trying to return a binary application/protobuf response. No matter what I do, the response body is always a base64 encoded string

  • I have application/protobuf setup as a binary media types in APIG
  • My client (javascript) is sending following headers in the POST: Accept: application/protobuf Content-Type: application/protobuf
  • My lambda is responing with content-type: application/protobuf, and correctly setting the IsBase64Encoded Lambda response to true

How do you get APIG to base64 decode the string? I swear I had this working a few months ago when I 1st tried this.

Note: I've also tried */* as a binary media types

Some related posts to add background:

  • https://github.com/twitchtv/twirp/issues/81
  • https://github.com/awslabs/aws-serverless-express/issues/39#issuecomment-276019222

Update:

Turns out I can only get it working if binary media type is set to */*. The client Accept header has no impact once it is set to this.

Many bad side effects of using */* because every response is attempted to get decoded (even when IsBase64Encoded is false or not set)

I thought it wasn't decoding because Chrome network inspect tools will always show binary data as base64 encoded in the Preview tab. You can see the protobuf in the Response tab.


回答1:


The problem was I'm using CloudFront in front of API Gateway, and I was not passing the Accept header to the origin (APIG).

The docs on handling binary with Lambda proxy are not great, so here is a quick summary:

  • Your client must send an Accept header who's 1st media type matches what you have set as a binary media types in API Gateway
  • Your Lambda, if serving a binary media type, must set IsBase64Encoded to true AND the body must be base64 encoded

If the clients Accept header matches an entry in API Gateway's binary media types and these conditions are met, API Gateway will transform (base64 decode) before sending a response to the client.

This blog post walks you through step-by-step on how to get it working (without CloudFront).

This is a full blown aws-blueprint for getting a production grade ci/cd with CloudFront.



来源:https://stackoverflow.com/questions/53510286/aws-api-gateway-with-lambda-proxy-always-produces-base64-string-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!