3

I am a beginner so I am hoping to get some help here.

I want create a lambda function (written in Python) that is able to read an image stored in S3 then return the image as a binary file (eg. a byte array). The lambda function is triggered by an API gateway.

Right now, I have setup the API gateway to trigger the Lambda function and it can return a hello message. I also have a gif image stored in a S3 bucket.

import base64
import json
import boto3

s3 = boto.client('s3')

def lambda_handler(event, context):
# TODO implement
bucket = 'mybucket'
key = 'myimage.gif'

s3.get_object(Bucket=bucket, Key=key)['Body'].read()
return {
    "statusCode": 200,
    "body": json.dumps('Hello from AWS Lambda!!')
}

I really have no idea how to continue. Can anyone advise? Thanks in advance!

Kian
  • 31
  • 1
  • 2
  • AWS Lambda has 6mb response body limit, also in lambda you are billed per 100ms so I think a better solution would be to return a direct s3 download link but if you still want to return binary data from lambda, check this SO question https://stackoverflow.com/questions/44860486/how-to-return-binary-data-from-lambda-function-in-aws-in-python – hurlenko Jul 16 '20 at 13:45

1 Answers1

3

you can return Base64 encoded data from your Lambda function with appropriate headers.

Here the updated Lambda function:

import base64
import boto3

s3 = boto3.client('s3')


def lambda_handler(event, context):
    bucket = 'mybucket'
    key = 'myimage.gif'

    image_bytes = s3.get_object(Bucket=bucket, Key=key)['Body'].read()

    # We will now convert this image to Base64 string
    image_base64 = base64.b64encode(image_bytes)

    return {'statusCode': 200,
            # Providing API Gateway the headers for the response
            'headers': {'Content-Type': 'image/gif'},
            # The image in a Base64 encoded string
            'body': image_base64,
            'isBase64Encoded': True}

For further details and step by step guide, you can refer to this official blog.

Mayank Raj
  • 1,574
  • 11
  • 13
  • @Khan, if the answer did indeed address your question, do you mind accepting it. That way, others who stumble upon this can easily find the solution. Cheers. – Mayank Raj Jul 16 '20 at 17:29