AWS Lambda and Compression
I've looked online repeatedly for code samples that discuss using gzip compression with AWS Lambdas, specifically with Python code, and I couldn't find any, so I decided to provide this code sample. I'm sure there's things that are missing with it, but this solves my underlying problem and does so in a manner that works well enough.
import json
import base64
import gzip
from decimal import *
class DecimalEncoder(json.JSONEncoder):
def default(self, obj):
# 👇️ if passed in object is instance of Decimal
# convert it to a string
if isinstance(obj, Decimal):
return str(obj)
# 👇️ otherwise use the default behavior
return json.JSONEncoder.default(self, obj)
def respond(statusCode: int = 200, body: dict = {}, headers: dict = {}, event: dict = {}):
isBase64Encoded = False
if 'Content-Type' not in headers or headers['Content-Type'] == 'application/json':
body = json.dumps(body, cls=DecimalEncoder)
if isinstance(body, str):
originalSize = len(body)
if event is not None and 'headers' in event and 'accept-encoding' in event['headers'] and 'gzip' in event['headers']['accept-encoding']:
body = base64.b64encode(gzip.compress(bytes(body, 'utf-8')))
isBase64Encoded = True
headers['Content-Encoding'] = 'gzip'
headers['Content-Length'] = len(body)
headers['X-Original-Content-Length'] = originalSize
return {
"statusCode": statusCode,
"body": body,
"headers": headers,
"isBase64Encoded": isBase64Encoded,
}