Home > Software design >  AWS Lambda function URL returns a different content-length value compared to API Gateway
AWS Lambda function URL returns a different content-length value compared to API Gateway

Time:05-07

I have a lambda that loads an S3 file and returns it as a Base64:

return {
    "isBase64Encoded": True,
    'statusCode': 200,
    'body': b64encode(...).decode('utf-8'),
    'headers': {
        'Content-Type': 'application/octet-stream',
    }
}

I created an API Gateway and when I call it I get:

<Response [200]>
Content-Type application/octet-stream
Content-Length 998356
apparent_encoding ascii

But calling the function URL returns:

<Response [200]>
Content-Type application/octet-stream
Content-Length 748765
apparent_encoding None

The correct content-length header value is the one API gateway is returning however the header is different when using the function URL even though they are both linked to the same Lambda function version & are invoking the same exact code.

What is the issue?

CodePudding user response:

When isBase64Encoded is set to true, the Lambda function is reversing the encoding to obtain the original data. This is why you're getting a lower content-length value.

However, b64encode(...).decode('utf-8') encodes your body content & then decodes it back to non-base64-encoded content. You're not actually returning base64-encoded data but you're specifying that you are.

Set isBase64Encoded to false and you should receive the correct full amount of data - as to why it works with API Gateway, it probably does an internal check, realises that you're not actually returning base-64 encoded data and returns the data as is.

  • Related