serverless-apigwy-binary icon indicating copy to clipboard operation
serverless-apigwy-binary copied to clipboard

Works only for custom lambda integration

Open fte378 opened this issue 5 years ago • 1 comments

Please! add a prominent note that this works for custom lambda integration only.

It took me 6 hours to find this.

fte378 avatar Mar 28 '19 12:03 fte378

It seems that it does work with both the Proxy and Custom Lambda setups but there are some changes that need to be made to the output from the Lambdas depending on what configuration you have.

For the Lambda Proxy configuration, the following set up worked for me:

# serverless.yaml
custom:
  apigwBinary:
    types:
      - 'image/jpeg'

functions:
  outputBinary:
    handler: handler.binary
    events:
      - http:
          path: binary
          method: get
          contentHandling: CONVERT_TO_BINARY

plugins:
  - serverless-apigw-binary
  - serverless-apigwy-binary
export const binary = async () => {
  const image = readFileSync('cat.jpeg')
  const base64 = Buffer.from(image).toString('base64')
  return {
    statusCode: 200,
    headers: { 'Content-type': 'image/jpeg' },
    body: base64,
    isBase64Encoded: true // Without this it wasn't returning a binary file
  }
}

Importantly the you need to set Accept: image/jpeg on your request to the API Gateway to force the Gateway to convert the binary file and not get a Base64 string

For the Custom Integration configuration, the following set up seems to work:

# serverless.yaml
custom:
  apigwBinary:
    types:
      - 'image/jpeg'

functions:
  outputBinary:
    handler: handler.binary
    events:
      - http:
          path: binary
          method: get
          integration: lambda # Switching to lamba setup
          contentHandling: CONVERT_TO_BINARY

plugins:
  - serverless-apigw-binary
  - serverless-apigwy-binary
export const binary = async () => {
  const image = readFileSync('cat.jpeg')
  const base64 = Buffer.from(image).toString('base64')
  // Note below that you don't return an object, return the image/binary directly
  // as a Base64 string. Without this you can get the Gateway complaining it can't 
  // decode the response body from Base64
  return base64  
}

What's confusing with this setup is that when Lamba Proxy is enabled and you go to the AWS Console, you cannot access there area to configure the binary conversion, so it makes it seem like these values are incompatible, but this value is configurable via the AWS CLI and obviously via the CloudFormation template created by serverless.

tony2nite avatar Jul 25 '19 09:07 tony2nite