21

Am using API gateway to trigger a Lambda function, using Lambda Proxy integration, however the request body is encoded base64, why is that? and how can I change it to be JSON to stringify JSON?

Ersoy
  • 8,816
  • 6
  • 34
  • 48
user3462064
  • 455
  • 2
  • 6
  • 24

2 Answers2

14

If I am understanding your question correct, you are sending non base64 encoded JSON payload as request to API gateway, however your Lambda is receiving it as base64 encoded string.

It seems that you are not setting application/json as your request content-type. You can see in this table how API gateway decides whether Integration Request Payload (last column) is Base64-encoded string or some other type.

https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-workflow.html

Raf
  • 88
  • 1
  • 11
  • I have the same problem and I DO set the `application/json` request `content-type`. Everything works locally (serverless offline) and when testing in the AWS console (sending a json object as body), but not when invoking via http. – morgler Aug 23 '20 at 11:04
  • I solved it @gilads, but I don't know what I did anymore :(. – morgler Sep 23 '20 at 17:52
  • 1
    Thanks, I had the same problem as the OP calling my API using cURL and adding the header `-H "Content-Type: application/json"` solved it for me – jdnz Apr 20 '21 at 17:53
  • 2
    @morgler I had the same issue. I discovered it was because I had added "*/*" to the BinaryMediaTypes of my API gateway. Removing that fixed it. – Dausuul Jul 27 '22 at 15:04
10

That's because you are using Lambda Proxy Integration in API Gateway. If you use Lambda integration, it will be fine and you can get JSON.

Also you can change it to be JSON to stringify JSON with following method.

let buff = Buffer.from(event.body, "base64");
let eventBodyStr = buff.toString('UTF-8');
let eventBody = JSON.parse(eventBodyStr);
alpha-bird
  • 318
  • 2
  • 10