Enabling Binary response from AWS API Gateway endpoint with Lambda Proxy integration
Tags: aws, lambda, apigateway
Published: 2021-08-12 14:59:46

AWS API Gateway is a fully-managed service that helps you create, publish and manage RESTful APIs and WebSocket APIs with a significant level of scale-out/ scale-in at your disposal. AWS provides two possible integrations with AWS Lambda which is a FaaS (Function as a Service) to handle your business logic.
Lambda-Proxy is a simple integration which forwards the request/response without any mutations, whereas a Lambda integration is complex and enables us to customize the request/response based on request/response templates provided in the API Gateway integration.

This post describes how we can enable an API Gateway endpoint to return binary response (viz. pdf, image, etc.) which has a Lambda Proxy Integration.


![API Gateway returning a file/ binary response from proxy-integrated lambda ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rp1tj60bjkgwja4iq7u8.png)


Enabling binary response in a Lambda-Proxy integration is a bit different from the conventional non-proxy based Lambda integration.
>One can refer the following documents for the conventional Lambda request integration with API Gateway with Binary support enabled, check [Non-proxy integrations](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings.html)

>Also take into consideration the available [API Gateway quota limitations](https://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html#http-api-quotas) if you are planning to return a file blob.


####Steps for getting binary content response from API Gateway with lambda proxy integration:
- Unlike the conventional Lambda binary integration, proxy-integrated Lambda response requires explicit conversion of the binary data to a base64 encoded string before initiating the lambda callback. "isBase64Encoded" flag is also set in the response. The base64 encoded string is the only data added to the body of the response object.
  
######The below code-snippet exhibits the ideal response returned by the lambda function (javascript):


   ```javascript
    exports.handler = async function(event, context) {
      ...
      ...
      ...
      var response = {
        statusCode: 200,
          headers: {
          "Content-type": "application/pdf", // content-type may vary depending on the document to be sent
          ...,
          ...,
          ...
        },
        body: base64EncodedDocString,
        isBase64Encoded: true
      };
      return response;
    }
  ```


  >As the 'content-type' and 'accept' HTTP headers are referred by the API Gateway to decide how to handle the body, it is ideal not to fix the 'content-type' header to the binary type on response and to change it in case of a lambda execution exception or a different 'accept' header sent in the initial request

- The API Gateway converts the base64 string from the response to binary, and to ensure this, the required media type is to be added in the [API Gateway Settings](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-console.html).

You can add the Binary Media Types via aws-cli as well:
```bash
aws apigateway update-rest-api — rest-api-id XXX — patch-operations 
‘[{“op” : “replace”, “path” : “/binaryMediaTypes/*~1*”, “value” : “*~1*”}]’
```



####References:
+ [Return binary media from a Lambda proxy integration](https://docs.aws.amazon.com/apigateway/latest/developerguide/lambda-proxy-binary-media.html)
+ [Enabling binary support using the API Gateway console](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-paylapi oad-encodings-configure-with-console.html)
+ [Available Content type conversions](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-paylapi oad-encodings-configure-with-console.html)