4

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!

1
  • 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 stackoverflow.com/questions/44860486/… Commented Jul 16, 2020 at 13:45

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@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.
Had the same issue and this solution solved it. Also to decode just use base64.b64decode. Thank you @Mayank Raj

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.